问:
How to remove the default "Successfully deleted ..." message for "Delete Selected" in Django Admin Action?
In the overridden delete_queryset(), I deleted loaded messages and added the new message "Deleted successfully!!" as shown below:

# "store/admin.py"

from .models import Person
from django.contrib import admin, messages

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):

    def delete_queryset(self, request, queryset):
        msgs = messages.get_messages(request)

        # Delete loaded messages
        for i in range(len(msgs)):
            del msgs[i]

        # Add a new message
        self.message_user(request, "Deleted successfully!!", messages.SUCCESS)

        queryset.delete()
```

Then, when clicking Go to go to delete the selected persons as shown below:

Then, clicking Yes I'm sure to delete the selected persons:

But, the default message "Successfully deleted 2 persons." is not removed as shown below:

So, how can I remove the default message for Delete Selected in Django Admin Action?

Body:
In the overridden delete_queryset(), I deleted loaded messages and added the new message "Deleted successfully!!" as shown below:

# "store/admin.py"

from .models import Person
from django.contrib import admin, messages

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):

    def delete_queryset(self, request, queryset):
        msgs = messages.get_messages(request)

        # Delete loaded messages
        for i in range(len(msgs)):
            del msgs[i]

        # Add a new message
        self.message_user(request, "Deleted successfully!!", messages.SUCCESS)

        queryset.delete()

Then, when clicking Go to go to delete the selected persons as shown below:

Then, clicking Yes I'm sure to delete the selected persons:

But, the default message "Successfully deleted 2 persons." is not removed as shown below:

So, how can I remove the default message for Delete Selected in Django Admin Action?


来源: stackexchange

问:
How to format decimals separators in DecimalFormat
I'm using DecimalFormat and need to add thousands separator to the decimal places of numbers. For example, I need to:

DecimalFormat fmt = new DecimalFormat("#,##0.0##_#"); // ?
System.out.println(fmt.format(1234.0));     // 1,234.0
System.out.println(fmt.format(0.1201));     // 0.120_1
System.out.println(fmt.format(0.00001234)); // 0.000_012_34
```

How do I specify the format for the decimal places?

ContentLicense: CC BY-SA 4.0

Body:
I'm using DecimalFormat and need to add thousands separator to the decimal places of numbers. For example, I need to:

DecimalFormat fmt = new DecimalFormat("#,##0.0##_#"); // ?
System.out.println(fmt.format(1234.0));     // 1,234.0
System.out.println(fmt.format(0.1201));     // 0.120_1
System.out.println(fmt.format(0.00001234)); // 0.000_012_34

How do I specify the format for the decimal places?


问:
TouchAction deprecated in Selenium 4
Here is my code to bring the Keyboard on the real ipad devices. Since Touch actions is been deprecated in Selenium 4. Can anyone help with the new solution?</p>
```<code>public void tapOnElementToBringKeyboard(By locator) {
TeasyElement element = element(locator);
clickActions(locator);
int fromX = element.getLocation().getX();
int fromY = element.getLocation().getY();

TouchAction touchAction = new TouchAction((IOSDriver<?>) getDriver());
touchAction.tap(PointOption.point(fromX, fromY)).release().perform().tap(PointOption.point(fromX, fromY)) .release().perform();
}
</code>```
```<code>

Dont have any solution
</code>```

Title: TouchAction deprecated in Selenium 4

Body:
Here is my code to bring the Keyboard on the real ipad devices. Since Touch actions is been deprecated in Selenium 4. Can anyone help with the new solution?

public void tapOnElementToBringKeyboard(By locator) {
TeasyElement element = element(locator);
clickActions(locator);
int fromX = element.getLocation().getX();
int fromY = element.getLocation().getY();

TouchAction touchAction = new TouchAction((IOSDriver<?>) getDriver());
touchAction.tap(PointOption.point(fromX, fromY)).release().perform().tap(PointOption.point(fromX, fromY)) .release().perform();
}

Dont have any solution


问:
Refactor React Components Code Using Context API
I am suppose to refactor this code. The task is to avoid passing username, updateUsername all the way down and without passing props directly. I am suppose to do this without using any third party library or framework.
This is the code

```<code>import { useState } from "react";

export default function App() {
  const [username, setUsername] = useState("owais");
  const [otherUsername, setOtherUsername] = useState("calvin");
  return (
    <>
      <User username={username} updateUsername={setUsername} />
      <User username={otherUsername} updateUsername={setOtherUsername} />
    </>
  );
}

function User({ username, updateUsername }) {
  return (
    <div>
      Username: {username}
      <UsernameEditor username={username} updateUsername={updateUsername} />
    </div>
  );
}

function UsernameEditor({ username, updateUsername }) {
  return (
    <div>
      <input
        type="text"
        value={username}
        onChange={(e) => updateUsername(e.target.value)}
      />
    </div>
  );
}
</code>```

I decided to use ContextAPI but I cannot seem to find a way to achieve this without either duplicating the user component and userNameEditor component code or passing the props directly to the component. Any ways I can achieve this?
This is what I currently have

```<code>import { createContext, useContext, useState } from "react"

interface AppContextInterface {
  username: string;
  setUsername: Function;
  otherUsername: string;
  setOtherUsername: Function;
}

const AppCtx = createContext<AppContextInterface | null>(null);

export default function App() {
  const [username, setUsername] = useState("owais");
  const [otherUsername, setOtherUsername] = useState("calvin");

  const value = { username, setUsername, otherUsername, setOtherUsername };

  return (
    <AppCtx.Provider value={value}>
      <User />
      <OtherUser />
    </AppCtx.Provider>
  );
}

function UsernameEditor() {
  const appContext = useContext(AppCtx);
  return (
    <div>
      <input
        type="text"
        value={appContext?.username}
        onChange={(e) => appContext?.setUsername(e.target.value)}
      />
    </div>
  );
}

function User() {
  const appContext = useContext(AppCtx);
  return (
    <div>
      Username: {appContext?.username}
      <UsernameEditor />
    </div>
  );
}

function OtherUserEditor() {
  const appContext = useContext(AppCtx);
  return (
    <div>
      <input
        type="text"
        value={appContext?.otherUsername}
        onChange={(e) => appContext?.setOtherUsername(e.target.value)}
      />
    </div>
  );
}

function OtherUser() {
  const appContext = useContext(AppCtx);
  return (
    <div>
      Username: {appContext?.otherUsername}
      <OtherUserEditor />
    </div>
  );
}
</code>```

Body:
I am suppose to refactor this code. The task is to avoid passing username, updateUsername all the way down and without passing props directly. I am suppose to do this without using any third party library or framework.
This is the code

import { useState } from "react";

export default function App() {
  const [username, setUsername] = useState("owais");
  const [otherUsername, setOtherUsername] = useState("calvin");
  return (
    <>
      <User username={username} updateUsername={setUsername} />
      <User username={otherUsername} updateUsername={setOtherUsername} />
    </>
  );
}

function User({ username, updateUsername }) {
  return (

      Username: {username}
      <UsernameEditor username={username} updateUsername={updateUsername} />

  );
}

function UsernameEditor({ username, updateUsername }) {
  return (

      <input
        type="text"
        value={username}
        onChange={(e) => updateUsername(e.target.value)}
      />

  );
}

I decided to use ContextAPI but I cannot seem to find a way to achieve this without either duplicating the user component and userNameEditor component code or passing the props directly to the component. Any ways I can achieve this?
This is what I currently have

import { createContext, useContext, useState } from "react"

interface AppContextInterface {
  username: string;
  setUsername: Function;
  otherUsername: string;
  setOtherUsername: Function;
}

const AppCtx = createContext<AppContextInterface | null>(null);

export default function App() {
  const [username, setUsername] = useState("owais");
  const [otherUsername, setOtherUsername] = useState("calvin");

  const value = { username, setUsername, otherUsername, setOtherUsername };

  return (
    <AppCtx.Provider value={value}>
      <User />
      <OtherUser />
    </AppCtx.Provider>
  );
}

function UsernameEditor() {
  const appContext = useContext(AppCtx);
  return (

      <input
        type="text"
        value={appContext?.username}
        onChange={(e) => appContext?.setUsername(e.target.value)}
      />

  );
}

function User() {
  const appContext = useContext(AppCtx);
  return (

      Username: {appContext?.username}
      <UsernameEditor />

  );
}

function OtherUserEditor() {
  const appContext = useContext(AppCtx);
  return (

      <input
        type="text"
        value={appContext?.otherUsername}
        onChange={(e) => appContext?.setOtherUsername(e.target.value)}
      />

  );
}

function OtherUser() {
  const appContext = useContext(AppCtx);
  return (

      Username: {appContext?.otherUsername}
      <OtherUserEditor />

  );
}


问:
What is the SQL Server "datepart", syntactically?
There's something about the SQL Server time functions that I haven't noticed anywhere else in the language.

For example, let's look at the function DATEADD():

DECLARE a_date datetime = '2006-08-31';
DATEADD(month, 1, a_date);
```

The 2nd and 3rd arguments are both expressions which evaluate to a value whose type I understand (int and datetime, in this case). But what exactly is the first argument? Is month a pre-defined global variable of some type? Is it a literal? Or a keyword? But it doesn't seem that every valid datepart is in the list of reserved words. Or is it some special syntactical category? If so, are there other examples of that category in the language? It doesn't seem I can treat it the same way as another variable or literal (SELECT month gives an error, for example).

Sorry if this is off topic for this site, but I wasn't sure which one it fit best under.

Body:
There's something about the SQL Server time functions that I haven't noticed anywhere else in the language.

For example, let's look at the function DATEADD():

DECLARE a_date datetime = '2006-08-31';
DATEADD(month, 1, a_date);

The 2nd and 3rd arguments are both expressions which evaluate to a value whose type I understand (int and datetime, in this case). But what exactly is the first argument? Is month a pre-defined global variable of some type? Is it a literal? Or a keyword? But it doesn't seem that every valid datepart is in the list of reserved words. Or is it some special syntactical category? If so, are there other examples of that category in the language? It doesn't seem I can treat it the same way as another variable or literal (SELECT month gives an error, for example).

Sorry if this is off topic for this site, but I wasn't sure which one it fit best under.


问:
VSCode: Is there a way to hide 'deprecated' Extensions from Marketplace search?
In the VSCode Extensions panel listings, is there a way to simply hide Extensions marked as deprecated?

For most folks, they generally won't have any use for these.

Link to image: Deprecated Extensions

I've tried looking in the VS Code Settings for something similar, and couldn't find one.

Also looked at the @deprecated filter in the Extensions search box.

Of course that shows only deprecated items, but I don't know how to "Invert" this search criteria (i.e. something like "NOT @deprecated")


问:
.NET App Won't Connect to DB - IIS 8.5 Deployment
I'm adding a new .NET MVC App that runs on the same data model as an older .NET app to IIS 8.5 and for now uses the same connection string for Microsoft SQL Server. It is giving me an error I can't figure out.

Here's the (censored) connection string I'm using for both apps:

```<code>Data Source=www2.oursite.com;Initial Catalog=*******;Persist Security Info=True;User ID=******;Password=●●●●●●●●●●●●●●●●;MultipleActiveResultSets=True;Integrated Security=False
</code>```

This is the error I recieve:

SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details. )

The new app belongs to the same AppPool as the old app, and the directory is granted permissions for that AppPool. I have also tried adding the app to its own AppPool in case that's the issue, and it doesn't seem to change anything.

When I go into the AppPool settings and set Load User Profile = True, marvelously, the app runs without any errors. However, it cannot retrieve any items from the database. It's like the database were totally empty.

Possibly related facts:

The apps are two different target runtimes for .NET. The old runs on v4.7.2. The new runs on .NET 5.0.

The two apps use the same data model - they are dependent on another .NET Module. The .NET Module runs EntityFramework v4.0.30319. The old application uses EntityFramework v4.0.30319. The new application uses EntityFramework v6.44.

IIS (Version 8.5) itself is run on Windows Server 2012. (Yes, we pray to upgrade this year.)

To run these apps on IIS, I package them and move them manually into the webroot, where I then set the settings.

Both apps run in AppPool where the CLR Version is 4.7.2. Both are set to Integrated.

When I try loading the new app and it spits out the above error, it takes a long time, like there's a timeout happening when the app tries to connect to the SQL Server.

I tried setting the AppPool Identity to LocalService, LocalSystem, and NetworkService. Setting to LocalSystem gives me the same error as when I set LoadUserProfile = True -  the app runs, but it's as if it's database queries are returning empty sets of data. The other settings just give the error.

This is all I can think of that might be relevant. Let me know if I can provide more info. I am no expert on this.

Does anyone have any clue? Usually when I'm stuck like this, I can figure it out with some fiddling or come up with a workaround, but I'm so lost here.

What I've tried:

I've granted the AppPool permissions on the project folder.

I've also tried putting the new app into a different AppPool.

I've set UserProfile = True, got the app running but not retrieving data (see above)

I tried setting the connection string in web.config, appsettings.json, and in IIS.

I've made sure the old project and new project have NO differing settings in IIS.

I've trawled through logs. I've did a looooooot of fiddling.

Body:
I'm adding a new .NET MVC App that runs on the same data model as an older .NET app to IIS 8.5 and for now uses the same connection string for Microsoft SQL Server. It is giving me an error I can't figure out.

Here's the (censored) connection string I'm using for both apps:

Data Source=www2.oursite.com;Initial Catalog=*******;Persist Security Info=True;User ID=******;Password=●●●●●●●●●●●●●●●●;MultipleActiveResultSets=True;Integrated Security=False

This is the error I recieve:

SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details. )

The new app belongs to the same AppPool as the old app, and the directory is granted permissions for that AppPool. I have also tried adding the app to its own AppPool in case that's the issue, and it doesn't seem to change anything.

When I go into the AppPool settings and set Load User Profile = True, marvelously, the app runs without any errors. However, it cannot retrieve any items from the database. It's like the database were totally empty.

Possibly related facts:

The apps are two different target runtimes for .NET. The old runs on v4.7.2. The new runs on .NET 5.0.

The two apps use the same data model - they are dependent on another .NET Module. The .NET Module runs EntityFramework v4.0.30319. The old application uses EntityFramework v4.0.30319. The new application uses EntityFramework v6.44.

IIS (Version 8.5) itself is run on Windows Server 2012. (Yes, we pray to upgrade this year.)

To run these apps on IIS, I package them and move them manually into the webroot, where I then set the settings.

Both apps run in AppPool where the CLR Version is 4.7.2. Both are set to Integrated.

When I try loading the new app and it spits out the above error, it takes a long time, like there's a timeout happening when the app tries to connect to the SQL Server.

I tried setting the AppPool Identity to LocalService, LocalSystem, and NetworkService. Setting to LocalSystem gives me the same error as when I set LoadUserProfile = True -  the app runs, but it's as if it's database queries are returning empty sets of data. The other settings just give the error.

This is all I can think of that might be relevant. Let me know if I can provide more info. I am no expert on this.

Does anyone have any clue? Usually when I'm stuck like this, I can figure it out with some fiddling or come up with a workaround, but I'm so lost here.

What I've tried:

I've granted the AppPool permissions on the project folder.

I've also tried putting the new app into a different AppPool.

I've set UserProfile = True, got the app running but not retrieving data (see above)

I tried setting the connection string in web.config, appsettings.json, and in IIS.

I've made sure the old project and new project have NO differing settings in IIS.

I've trawled through logs. I've did a looooooot of fiddling.


问:
didn't get any gpu using sbatch when submitting a job script through slurm
Here is my slurm job script. I requested 4 gpu and 1 computing node. My script is as follows:

```<code>#!/bin/bash
#SBATCH --partition=gpu
#SBATCH --gres=gpu:4
#SBATCH --ntasks-per-gpu=12
#SBATCH --mem-per-gpu=40G
#SBATCH --time=0:15:00

module use /ifs/opt_cuda/modulefiles
module load python/gcc/3.10
module load cuda11.1/toolkit cuda11.1/blas cuda11.1/fft cudnn8.0-cuda11.1 tensorrt-cuda11.1/7.2.3.4

# activate TF venv
source /ifs/groups/rweberGrp/venvs/py310-tf210/bin/activate

python -c "import torch;print(torch.cuda.device_count())"
</code>```

so the torch.cuda.device_count() should give me 4 but actually the output is 0

```<code>0
</code>```

I have no idea why this is happening. Anyone has any idea? Thanks

Body:
Here is my slurm job script. I requested 4 gpu and 1 computing node. My script is as follows:

#!/bin/bash
#SBATCH --partition=gpu
#SBATCH --gres=gpu:4
#SBATCH --ntasks-per-gpu=12
#SBATCH --mem-per-gpu=40G
#SBATCH --time=0:15:00

module use /ifs/opt_cuda/modulefiles
module load python/gcc/3.10
module load cuda11.1/toolkit cuda11.1/blas cuda11.1/fft cudnn8.0-cuda11.1 tensorrt-cuda11.1/7.2.3.4

# activate TF venv
source /ifs/groups/rweberGrp/venvs/py310-tf210/bin/activate

python -c "import torch;print(torch.cuda.device_count())"

so the torch.cuda.device_count() should give me 4 but actually the output is 0

0

I have no idea why this is happening. Anyone has any idea? Thanks


问:
Best way to type "makeStyles"
I know this API is deprecated/legacy, but I'm really curios about what's the best way to type this function/utility as to provide the type for props when using function value callbacks signature to define properties:

```<code>import { createTheme } from '@mui/material';
import { makeStyles } from '@mui/styles';

interface ThemeProps {
  alignItems: boolean;
  themeVersion: 'primary' | 'secondary'
}

const appTheme = createTheme();

const useStyles = makeStyles((theme: typeof appTheme) => {
  return {
    mainContainer: ({ alignItems }: ThemeProps) => ({
      alignItems: alignItems ? 'center' : '',
      height: '100%',
      padding: theme.spacing(2),
    }),
    subContainer: {
      display: 'flex',
      justifyContent: 'center',
      backgroundColor: ({ themeVersion }: ThemeProps) =>
        themeVersion === 'secondary'
          ? theme.palette.secondary.main
          : theme.palette.primary.main,
    },
  };
});
</code>```

This works just fine, but I'd like to define the types at the very beginning in order to omit specifying the props' type every single time I use a function value:

```<code>const useStyles = makeStyles<typeof appTheme, ThemeProps>(theme => {
  return {
    mainContainer: ({ alignItems }) => ({
      alignItems: alignItems ? 'center' : '',
      height: '100%',
      padding: theme.spacing(2),
    }),
    subContainer: {
      display: 'flex',
      justifyContent: 'center',
      backgroundColor: ({ themeVersion }) =>
        themeVersion === 'secondary'
          ? theme.palette.secondary.main
          : theme.palette.primary.main,
    },
  };
});
</code>```

the problem here is that the retuning type of useStyles is no longer what I need, instead of being ClassNameMap<"mainContainer" | "subContainer">, the value that it is "defaulted" to is ClassNameMap<string>.

Any idea on how to make it work without having to resort to something like

```<code>makeStyles<typeof appTheme, ThemeProps, 'mainContainer' | 'subContainer'>
</code>```

Title: Best way to type "makeStyles"

Body:
I know this API is deprecated/legacy, but I'm really curios about what's the best way to type this function/utility as to provide the type for props when using function value callbacks signature to define properties:

import { createTheme } from '@mui/material';
import { makeStyles } from '@mui/styles';

interface ThemeProps {
  alignItems: boolean;
  themeVersion: 'primary' | 'secondary'
}

const appTheme = createTheme();

const useStyles = makeStyles((theme: typeof appTheme) => {
  return {
    mainContainer: ({ alignItems }: ThemeProps) => ({
      alignItems: alignItems ? 'center' : '',
      height: '100%',
      padding: theme.spacing(2),
    }),
    subContainer: {
      display: 'flex',
      justifyContent: 'center',
      backgroundColor: ({ themeVersion }: ThemeProps) =>
        themeVersion === 'secondary'
          ? theme.palette.secondary.main
          : theme.palette.primary.main,
    },
  };
});

This works just fine, but I'd like to define the types at the very beginning in order to omit specifying the props' type every single time I use a function value:

const useStyles = makeStyles<typeof appTheme, ThemeProps>(theme => {
  return {
    mainContainer: ({ alignItems }) => ({
      alignItems: alignItems ? 'center' : '',
      height: '100%',
      padding: theme.spacing(2),
    }),
    subContainer: {
      display: 'flex',
      justifyContent: 'center',
      backgroundColor: ({ themeVersion }) =>
        themeVersion === 'secondary'
          ? theme.palette.secondary.main
          : theme.palette.primary.main,
    },
  };
});

the problem here is that the retuning type of useStyles is no longer what I need, instead of being ClassNameMap<"mainContainer" | "subContainer">, the value that it is "defaulted" to is ClassNameMap<string>.

Any idea on how to make it work without having to resort to something like

makeStyles<typeof appTheme, ThemeProps, 'mainContainer' | 'subContainer'>


问:
converting BLOB to String Laravel 9.x
So i have a database with documents saved in it. The content is saved in BLOB type. Now i want to be able to edit it. For that, my programm uses an editor, which is imbedded in html. My idea was to decode the binary type BLOB to string and then insert it into the textarea from html via a blade template. Sending the data from php to html works, but there seems to be something wrong while converting. My testdocument has the content 'test' in it however, it shows 'AA==' when loading the page.
Here are my code snippets:

This is my database migration:

```<code>public function up()
{
    Schema::create('documents', function (Blueprint $table) {
        $table->id('id');
        $table->foreignId('owner_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('document_name');
        $table->string('release_state')->default('Privat');
        $table->integer('call')->default(0); //wird erzeugt und auf null gesetzt inkrement erfolgt woanders
        $table->binary('document_data'); //BLOB equivalent, hier ist der Content des Dokuments gespeichert
        $table->timestamps();
    });
}
</code>```

The data is originally saved here:

```<code>function save()
{
    if (!empty($_REQUEST['documentContent'])) {
        $documentContent = $_REQUEST['documentContent'];
    }
    else {

    }
    $id = Auth::id();

    $document = Documents::create([
        'owner_id' => $id,
        'document_name' => 'Placeholder will be replaced', //$daten->input('document_name'),
        'document_data' => $documentContent
    ]);
    return redirect('editor');
}
</code>```

This is my function, where i get the id from the document and try to convert it

```<code>function document_edit(Request $daten)
    {

        $document_databinary = Documents::select('document_data')->where('id', $daten->input('id'))->get();
        $document_data = base64_encode(pack('H*', base_convert($document_databinary, 2, 16)));

        return view('editor', ['document_data' => $document_data]);
    }
</code>```

This is where i want to put the data

```<code><div class="container-fluid">
  <form method="POST" action="/editor/save">
    @csrf
    @isset($document_data)
    <textarea name="documentContent" id="documentContent" required>
    <p>{{$document_data}}</p>
    </textarea>
    @else
    <textarea name="documentContent" id="documentContent">
      <p></p>
    </textarea>

    @endif

    <button type="submit" class="btn btn-primary" value="save">Datei speichern</button>
  </form>
</div>
</code>```

I already checked the .bin file from the database, there is no problem in saving the data to it in the first place.
Any suggestions to solve this problem?

Title: converting BLOB to String Laravel 9.x

Body:
So i have a database with documents saved in it. The content is saved in BLOB type. Now i want to be able to edit it. For that, my programm uses an editor, which is imbedded in html. My idea was to decode the binary type BLOB to string and then insert it into the textarea from html via a blade template. Sending the data from php to html works, but there seems to be something wrong while converting. My testdocument has the content 'test' in it however, it shows 'AA==' when loading the page.
Here are my code snippets:

This is my database migration:

public function up()
{
    Schema::create('documents', function (Blueprint $table) {
        $table->id('id');
        $table->foreignId('owner_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('document_name');
        $table->string('release_state')->default('Privat');
        $table->integer('call')->default(0); //wird erzeugt und auf null gesetzt inkrement erfolgt woanders
        $table->binary('document_data'); //BLOB equivalent, hier ist der Content des Dokuments gespeichert
        $table->timestamps();
    });
}

The data is originally saved here:

function save()
{
    if (!empty($_REQUEST['documentContent'])) {
        $documentContent = $_REQUEST['documentContent'];
    }
    else {

    }
    $id = Auth::id();

    $document = Documents::create([
        'owner_id' => $id,
        'document_name' => 'Placeholder will be replaced', //$daten->input('document_name'),
        'document_data' => $documentContent
    ]);
    return redirect('editor');
}

This is my function, where i get the id from the document and try to convert it

function document_edit(Request $daten)
    {

        $document_databinary = Documents::select('document_data')->where('id', $daten->input('id'))->get();
        $document_data = base64_encode(pack('H*', base_convert($document_databinary, 2, 16)));

        return view('editor', ['document_data' => $document_data]);
    }

This is where i want to put the data

  <form method="POST" action="/editor/save">
    @csrf
    @isset($document_data)
    <textarea name="documentContent" id="documentContent" required>

{{$document_data}}

    </textarea>
    @else
    <textarea name="documentContent" id="documentContent">

    </textarea>

    @endif

    <button type="submit" class="btn btn-primary" value="save">Datei speichern</button>
  </form>

I already checked the .bin file from the database, there is no problem in saving the data to it in the first place.
Any suggestions to solve this problem?


问:
I can't validate the files extension in javascript/js. Could someone tell me what the error is and how to fix it?
The following code does not recognize the extensions of the files that I try to enter, which leads to always getting the "It is not a valid file" alert. I can't find the error, can someone help me? Thanks a lot.

This code is from JavaScript.

```<code>
const dropArea = document.querySelector(".drop-area");
const dragText = dropArea.querySelector('h2');
const button = dropArea.querySelector("button");
const input = dropArea.querySelector("#input-file");
let files;

button.addEventListener("click", (e) => {
    input.click();
});

input.addEventListener("change", (e) => {
    files = this.files;
    dropArea.classList.add("active");
    showFiles(files);
    dropArea.classList.remove("active");
});

dropArea.addEventListener("dragover", (e) => {
    e.preventDefault();
    dropArea.classList.add("active");
    dragText.textContent = "Suelta para subir los archivos";
});

dropArea.addEventListener("dragleave", (e) => {
    e.preventDefault();
    dropArea.classList.remove("active");
    dragText.textContent = "Arrastra y suelta archivos";
});

dropArea.addEventListener("drop", (e) => {
    e.preventDefault();
    files = e.dataTransfer.files;
    showFiles(files);
    dropArea.classList.remove("active");
    dragText.textContent = "Arrastra y suelta archivos";
});

function showFiles(files) {
    if (files.lenght === undefined) {
        processFile(files);
    } else {
        for (const file of files) {
            processFile(file);
        }
    }
}

function processFile(file) {
    const docType = file.type;
    const validExtensions = ["image/jpeg", "image/jpg", "image/png", "image/gif"];

    if (validExtensions.includes(docType)) {
        //Archivo valido.
    } else {
        //No es archivo valido.
        alert('No es un archivo valido');
    }
}
</code>```

Body:
The following code does not recognize the extensions of the files that I try to enter, which leads to always getting the "It is not a valid file" alert. I can't find the error, can someone help me? Thanks a lot.

This code is from JavaScript.

const dropArea = document.querySelector(".drop-area");
const dragText = dropArea.querySelector('h2');
const button = dropArea.querySelector("button");
const input = dropArea.querySelector("#input-file");
let files;

button.addEventListener("click", (e) => {
    input.click();
});

input.addEventListener("change", (e) => {
    files = this.files;
    dropArea.classList.add("active");
    showFiles(files);
    dropArea.classList.remove("active");
});

dropArea.addEventListener("dragover", (e) => {
    e.preventDefault();
    dropArea.classList.add("active");
    dragText.textContent = "Suelta para subir los archivos";
});

dropArea.addEventListener("dragleave", (e) => {
    e.preventDefault();
    dropArea.classList.remove("active");
    dragText.textContent = "Arrastra y suelta archivos";
});

dropArea.addEventListener("drop", (e) => {
    e.preventDefault();
    files = e.dataTransfer.files;
    showFiles(files);
    dropArea.classList.remove("active");
    dragText.textContent = "Arrastra y suelta archivos";
});

function showFiles(files) {
    if (files.lenght === undefined) {
        processFile(files);
    } else {
        for (const file of files) {
            processFile(file);
        }
    }
}

function processFile(file) {
    const docType = file.type;
    const validExtensions = ["image/jpeg", "image/jpg", "image/png", "image/gif"];

    if (validExtensions.includes(docType)) {
        //Archivo valido.
    } else {
        //No es archivo valido.
        alert('No es un archivo valido');
    }
}


问:
How can we access Settings > Safety & emergency on Pixel XL API 33 via adb commands?
access Settings > Safety & emergency via adb commands?

I tried below commands but none are working.

adb shell am start -n com.android.settings/com.android.settings.emergency.EmergencyDashboardFragment

```<code>Starting: Intent { cmp=com.android.settings/.emergency.EmergencyDashboardFragment }
Error type 3
Error: Activity class {com.android.settings/com.android.settings.emergency.EmergencyDashboardFragment} does not exist.
emu64xa:/ # am start -n com.android.settings/com.android.settings.emergency.EmergencyDashboardFragment
</code>```

adb shell am start -n com.android.settings/com.android.settings.SubSettings -e :android:show_fragment com.android.settings.emergency.EmergencyDashboardFragment

This only opens the settings, but not Settings > Safety & emergency

Body:
access Settings > Safety & emergency via adb commands?

I tried below commands but none are working.

adb shell am start -n com.android.settings/com.android.settings.emergency.EmergencyDashboardFragment

Starting: Intent { cmp=com.android.settings/.emergency.EmergencyDashboardFragment }
Error type 3
Error: Activity class {com.android.settings/com.android.settings.emergency.EmergencyDashboardFragment} does not exist.
emu64xa:/ # am start -n com.android.settings/com.android.settings.emergency.EmergencyDashboardFragment

adb shell am start -n com.android.settings/com.android.settings.SubSettings -e :android:show_fragment com.android.settings.emergency.EmergencyDashboardFragment

This only opens the settings, but not Settings > Safety & emergency


问:
Cannot import pandas in Jupyter-Notebook
I'm trying to import pandas in a Jupyter-Notebook, but I keep getting the following error. BTW, I use conda as my package/virtual environment manager and this error arises regardless of the environment currently active:

Additionally, when I try to install pandas (again) I am met with the following message:

I'm aware that my post is similar to this one: ModuleNotFoundError: No module named 'pandas._libs.interval' and I would like to try to uninstall the user-level Python, as suggested in the afore mentioned post, but I don't know how and I would greatly appreciate concrete steps to doing so:

Thank you for your time!

I have tried the following:

Creating a new conda environment as shown in the following code:

```<code>conda create --name py37 python=3.7 pandas numpy ipykernel matplotlib jupyter
</code>```

Uninstalling and reinstalling pandas in the Jupyter-Notebook.

I have also tried the following code using a different environment:

```<code>source activate penv
conda install ipykernel
python -m ipykernel install --user --name penv --display-name "py37k"
</code>```

Body:
I'm trying to import pandas in a Jupyter-Notebook, but I keep getting the following error. BTW, I use conda as my package/virtual environment manager and this error arises regardless of the environment currently active:

Additionally, when I try to install pandas (again) I am met with the following message:

I'm aware that my post is similar to this one: ModuleNotFoundError: No module named 'pandas._libs.interval' and I would like to try to uninstall the user-level Python, as suggested in the afore mentioned post, but I don't know how and I would greatly appreciate concrete steps to doing so:

Thank you for your time!

I have tried the following:

Creating a new conda environment as shown in the following code:

conda create --name py37 python=3.7 pandas numpy ipykernel matplotlib jupyter

Uninstalling and reinstalling pandas in the Jupyter-Notebook.

I have also tried the following code using a different environment:

source activate penv
conda install ipykernel
python -m ipykernel install --user --name penv --display-name "py37k"


问:
Getting different number of samples from Python mlab.specgram and JavaScript audioContext Analyser for the same audio
I'm trying to fingerprint audio using Python on the backend and javascript on the client. However, I'm getting a different number of samples back using these two methods:

Python:

```<code>audio = AudioSegment.from_file(sys.argv[1])
audio_data = np.frombuffer(audio.raw_data, np.int16)

for channel in range(audio.channels):
    logging.info(f"Processing channel {channel}")
    channel_data = audio_data[channel :: audio.channels]

    arr2D = mlab.specgram(
        channel_data,
        NFFT=4096,
        Fs=audio.frame_rate,
        window=mlab.window_hanning,
        noverlap=4096 // 2,
    )[0]`
</code>```

Javascript:

```<code>analyser = audioContext.createAnalyser(4096, 2048);
analyser.smoothingTimeConstant = 0.5;
analyser.getByteFrequencyData(array);`
</code>```

The Python code returns 233 samples per channel for a 10-second audio file, while the Javascript code returns way over 500 total samples (both are size 2048). This is making it difficult to properly fingerprint the audio. How can I fix this issue?

I've tried different smoothing parameters for Analyser and I've tried to find things that could affect the sample amount. I've also tried specgram with mlab.window_none, which did not affect the amount of samples returned.

Body:
I'm trying to fingerprint audio using Python on the backend and javascript on the client. However, I'm getting a different number of samples back using these two methods:

Python:

audio = AudioSegment.from_file(sys.argv[1])
audio_data = np.frombuffer(audio.raw_data, np.int16)

for channel in range(audio.channels):
    logging.info(f"Processing channel {channel}")
    channel_data = audio_data[channel :: audio.channels]

    arr2D = mlab.specgram(
        channel_data,
        NFFT=4096,
        Fs=audio.frame_rate,
        window=mlab.window_hanning,
        noverlap=4096 // 2,
    )[0]`

Javascript:

analyser = audioContext.createAnalyser(4096, 2048);
analyser.smoothingTimeConstant = 0.5;
analyser.getByteFrequencyData(array);`

The Python code returns 233 samples per channel for a 10-second audio file, while the Javascript code returns way over 500 total samples (both are size 2048). This is making it difficult to properly fingerprint the audio. How can I fix this issue?

I've tried different smoothing parameters for Analyser and I've tried to find things that could affect the sample amount. I've also tried specgram with mlab.window_none, which did not affect the amount of samples returned.


问:
JavaFX WebView doesn't open HTML file for geocoding
I'm trying to open a map for geocoding and reverse geocoding with a webview, but for some reason webview doesn't load anything, while in all browsers this html file works.

Here the html

```<code><html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>ArcGIS Developer Guide: Reverse geocoding</title>

    <style>
        html, body, #viewDiv {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
        }
        .esri-view .esri-search {
            width: 250px;
        }
    </style>

    <link rel="stylesheet" href="https://js.arcgis.com/4.25/esri/themes/light/main.css">
    <script src="https://js.arcgis.com/4.25"></script>

    <script>
        require([
            "esri/config",
            "esri/Map",
            "esri/views/MapView",
            "esri/widgets/Search",
            "esri/geometry/Point",
            "esri/Graphic",
            "esri/rest/locator",
            "esri/widgets/Expand"
        ],(esriConfig, Map, MapView, Search, Point, Graphic, locator,Expand)=> {

            esriConfig.apiKey = "AAPK84b818a7a36047d094261edabf194302AJjfzaeaGPdP3Yv5V3XLEA6mBMNdrMD-VLRIi6c4ZzQioCVKDcrI5GoYHZG60uhk";

            const map = new Map({
                basemap: "arcgis-navigation", //Basemap layer service
            });

            const view = new MapView({
                container: "viewDiv",
                map: map,
                center: [6.1432,46.215], //Geneva
                zoom: 11,
                constraints: {
                    snapToZoom: false
                }
            });

            view.popup.actions = [];

            const geocodingService = "https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer";

            // Add Search widget
            const search = new Search({
                view: view
            });

            view.ui.add(new Expand({
                view:view,
                content:search,
                expanded:true,
                mode:"floating"
            }), "top-right");

            view.when(() => {
                search.watch("activeSource", (source) =>{
                    reverseGeocode(view.center);
                });
            });

            // Find address from clicking on map
            view.on("click", (event) => {
                view.when(() => {
                    search.clear();
                    view.popup.clear();
                    reverseGeocode(event.mapPoint);
                });
            });

            function reverseGeocode(pt) {
                const params = {
                    location: pt
                };
                locator.locationToAddress(geocodingService, params).then(
                    (response) => {
                        if (response) {
                            search.searchTerm = response.attributes.LongLabel;
                            showPopup(response);
                        }
                    },
                    (err) => {
                        showPopup("No address found.", pt);
                    }
                );
            }

            // Information shown when map is clicked
            function showPopup(response) {
                if (!response) {
                    return;
                }
                view.popup.open({
                    title: response.attributes.PlaceName || "Address",
                    content:
                        response.attributes.LongLabel +
                        "<br><br>" +
                        response.location.longitude.toFixed(5) +
                        ", " +
                        response.location.latitude.toFixed(5),
                    location: response.location,
                });
                addGraphic(response);
            }

            function addGraphic(response) {
                if (!response.location) {
                    return;
                }
                view.graphics.removeAll();
                view.graphics.add(
                    new Graphic({
                        symbol: {
                            type: "simple-marker",
                            outline: {
                                color: "white",
                                width: 1.5,
                            },
                            color: "black",
                            size: 6,
                        },
                        geometry: response.location,
                    })
                );
            }
        });

    </script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html>
</code>```

this is the code where i initialize the webview, with other html files it works, but not with this one above

```<code>WebEngine webEngine = webView.getEngine();
URL url = this.getClass().getResource("/webView/geocoding.html");
System.out.println(url);
webEngine.load(url.toString());
</code>```

and if it really can't work, is there any alternative to be able to retrieve the address using geocoding and reverse geocoding through the webview or maybe there is some alternative to webview

Body:
I'm trying to open a map for geocoding and reverse geocoding with a webview, but for some reason webview doesn't load anything, while in all browsers this html file works.

Here the html

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>ArcGIS Developer Guide: Reverse geocoding</title>

    <link rel="stylesheet" href="https://js.arcgis.com/4.25/esri/themes/light/main.css">

this is the code where i initialize the webview, with other html files it works, but not with this one above

WebEngine webEngine = webView.getEngine();
URL url = this.getClass().getResource("/webView/geocoding.html");
System.out.println(url);
webEngine.load(url.toString());

and if it really can't work, is there any alternative to be able to retrieve the address using geocoding and reverse geocoding through the webview or maybe there is some alternative to webview


问:
Telegram Bot Via Integromat/Make: Using URL Params in the button Callback Query
I am creating a Telegram bot inside of Make/Integromat. Everything is great but I am struggling to send a Callback Query with URL parameters.

The goal is to send a webhook with dynamic data using the Callback Query option in the button. This will then initiate a differnt scenario in Make and once complete, end by send a Telegram confirmation message.

As it stands I can send the webhook url via the Callback Query. But when I add URL Parameters I get the error "Button Data is Invalid"

So I currently have to send the webhook+params via the button URL link option. Which isn't ideal because this opens the 'Accepted' webpage when they click the button and takes them away from Telegram.

Any ideas, if it is possible to send a URL with query params using the Callback Query?

I have tried adding the webhoook like this
https://hook.integromat.com/abcd1234567?Name={{3.callback_query.from.first_name}}


问:
php - PHPUnit with PCOV code coverage show 0% coverage on window
I use phpUnit with PCOV on code coverage on window.  But somehow, I get 0.0% code coverage. I am sure the function is called. Why is this happening?

Versions:

PHP: 8.1.12

PHPUnit: 9.5.0

PCOV: 1.0.11

The running log is as follows

```<code>PS C:\xampp\php> vendor\bin\phpunit
PHPUnit 9.5.0 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.1.12
Configuration: C:\xampp\php\phpunit.xml

R                                        1 / 1 (100%)Called1
Time: 00:00.215, Memory: 10.00 MB
There was 1 risky test:

1) AAATest::testaccess
This test printed output: Called1
OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 1, Risky: 1.
PS C:\xampp\php\
</code>```

Following is my simplified code AAA.php

class AAA
{
    public $flag;
    public function __construct($flag)
    {
        $this->flag = $flag;
    }

    public function access()
    {
        $this->flag = 1;
    }
}
```
<h1>Following is my testing AAATest.php</h1>
<pre class="lang-php prettyprint-override"><code><?php

require '/xampp/php/vendor/autoload.php';
require '/xampp/htdocs/Performance/scripts-php/AAA.php';

use PHPUnit\Framework\TestCase;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Driver\Driver;
use SebastianBergmann\CodeCoverage\Filter;
use SebastianBergmann\CodeCoverage\Report\Html\Facade as HtmlReport;

$filter = new Filter;
$filter->includeFile('/xampp/htdocs/Performance/scripts-php/AAA.php');
$driver = Driver::forLineCoverage($filter);
$coverage = new CodeCoverage($driver, $filter);

$flag = 0;

class AAATest extends TestCase
{
    protected $AAA;

    protected function setUp(): void
    {
        global $flag;
        global $coverage;
        $this->AAA = new AAA($flag);
        print("Called");
    }

    /**
     * @covers AAA::access
    */
    public function testaccess()
    {
        global $flag;
        global $coverage;

        $coverage->start('testaccess');

        $this->AAA->access();

        print($this->AAA->flag);

        $this->assertEquals(1, $this->AAA->flag);

        $coverage->stop();

        (new HtmlReport)->process($coverage, 'code-coverage-report\report');
    }
}
</code>```

Following is the php.ini

........
extension=php_gd
extension=php_pcov
extension=gettext
.......
```
<h1>Following is the <code>phpunit.xml</code></h1>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
        bootstrap="vendor/autoload.php"
        cacheResultFile=".phpunit.cache/test-results"
        executionOrder="depends,defects"
        forceCoversAnnotation="true"
        beStrictAboutCoversAnnotation="true"
        beStrictAboutOutputDuringTests="true"
        beStrictAboutTodoAnnotatedTests="true"
        convertDeprecationsToExceptions="true"
        failOnRisky="true"
        failOnWarning="true"
        verbose="true">

    <testsuites>
        <testsuite name="default">
            <file>/xampp/htdocs/Performance/scripts-php/AAA.php</file>
            <directory>/xampp/htdocs/Performance/scripts-php/</directory>
        </testsuite>
    </testsuites>

    <coverage cacheDirectory=".phpunit.cache/code-coverage"
            processUncoveredFiles="true"
    >
        <include>
            <directory suffix=".php">/xampp/htdocs/Performance/scripts-php</directory>
        </include>
        <exclude>
            <directory>./vendor</directory>
            <directory>./tests</directory>
        </exclude>
    </coverage>
    <php>
        <env name="APP_ENV" value="testing"/>
    </php>

</phpunit>
</code>```

Following is the composer.json

{
    "require-dev": {
        "phpunit/phpunit": "9.5",
        "phpunit/php-code-coverage": "^9.2",
        "phpunit/phpunit-selenium": "^9.0",
        "pcov/clobber": "^2.0"
    },
    "require": {
        "php": ">=8.0",
        "php-webdriver/webdriver": "1.13.1",
        "symfony/symfony": "5.2"
    }
}
```
<p>Here is the result. I am expecting 100% code coverage</p>
<pre class="lang-none prettyprint-override"><code>C:\xampp\php\code-coverage-report\report\AAA.php.html

                       Code Coverage
       Lines                        Functions and Methods               Classes and Traits
Total
  0.00% covered(danger)    0.00% 0/2 0.00% covered(danger)    0.00% 0/2 CRAP0.00% covered (danger)  0.00%  0/1
AAA
  0.00% covered (danger)   0.00% 0/2 0.00% covered(danger)    0.00% 0/26 0.00% covered (danger)
0.00% 0/1
 __construct
  0.00% covered(danger)    0.00% 0/1 0.00% covered(danger)    0.00% 0/1 2
access
  0.00% covered (danger)   0.00% 0/1 0.00% covered(danger)    0.00% 0/1 2
</code>```

Body:
I use phpUnit with PCOV on code coverage on window.  But somehow, I get 0.0% code coverage. I am sure the function is called. Why is this happening?

Versions:

PHP: 8.1.12

PHPUnit: 9.5.0

PCOV: 1.0.11

The running log is as follows

PS C:\xampp\php> vendor\bin\phpunit
PHPUnit 9.5.0 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.1.12
Configuration: C:\xampp\php\phpunit.xml

R                                        1 / 1 (100%)Called1
Time: 00:00.215, Memory: 10.00 MB
There was 1 risky test:

1) AAATest::testaccess
This test printed output: Called1
OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 1, Risky: 1.
PS C:\xampp\php\

Following is my simplified code AAA.php

class AAA
{
    public $flag;
    public function __construct($flag)
    {
        $this->flag = $flag;
    }

    public function access()
    {
        $this->flag = 1;
    }
}

Following is my testing AAATest.php

<?php

require '/xampp/php/vendor/autoload.php';
require '/xampp/htdocs/Performance/scripts-php/AAA.php';

use PHPUnit\Framework\TestCase;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Driver\Driver;
use SebastianBergmann\CodeCoverage\Filter;
use SebastianBergmann\CodeCoverage\Report\Html\Facade as HtmlReport;

$filter = new Filter;
$filter->includeFile('/xampp/htdocs/Performance/scripts-php/AAA.php');
$driver = Driver::forLineCoverage($filter);
$coverage = new CodeCoverage($driver, $filter);

$flag = 0;

class AAATest extends TestCase
{
    protected $AAA;

    protected function setUp(): void
    {
        global $flag;
        global $coverage;
        $this->AAA = new AAA($flag);
        print("Called");
    }

    /**
     * @covers AAA::access
    */
    public function testaccess()
    {
        global $flag;
        global $coverage;

        $coverage->start('testaccess');

        $this->AAA->access();

        print($this->AAA->flag);

        $this->assertEquals(1, $this->AAA->flag);

        $coverage->stop();

        (new HtmlReport)->process($coverage, 'code-coverage-report\report');
    }
}

Following is the php.ini

........
extension=php_gd
extension=php_pcov
extension=gettext
.......

Following is the phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
        bootstrap="vendor/autoload.php"
        cacheResultFile=".phpunit.cache/test-results"
        executionOrder="depends,defects"
        forceCoversAnnotation="true"
        beStrictAboutCoversAnnotation="true"
        beStrictAboutOutputDuringTests="true"
        beStrictAboutTodoAnnotatedTests="true"
        convertDeprecationsToExceptions="true"
        failOnRisky="true"
        failOnWarning="true"
        verbose="true">

    <testsuites>
        <testsuite name="default">
            <file>/xampp/htdocs/Performance/scripts-php/AAA.php</file>
            <directory>/xampp/htdocs/Performance/scripts-php/</directory>
        </testsuite>
    </testsuites>

    <coverage cacheDirectory=".phpunit.cache/code-coverage"
            processUncoveredFiles="true"
    >
        <include>
            <directory suffix=".php">/xampp/htdocs/Performance/scripts-php</directory>
        </include>
        <exclude>
            <directory>./vendor</directory>
            <directory>./tests</directory>
        </exclude>
    </coverage>
    <php>
        <env name="APP_ENV" value="testing"/>
    </php>

</phpunit>

Following is the composer.json

{
    "require-dev": {
        "phpunit/phpunit": "9.5",
        "phpunit/php-code-coverage": "^9.2",
        "phpunit/phpunit-selenium": "^9.0",
        "pcov/clobber": "^2.0"
    },
    "require": {
        "php": ">=8.0",
        "php-webdriver/webdriver": "1.13.1",
        "symfony/symfony": "5.2"
    }
}

Here is the result. I am expecting 100% code coverage

C:\xampp\php\code-coverage-report\report\AAA.php.html

                       Code Coverage
       Lines                        Functions and Methods               Classes and Traits
Total
  0.00% covered(danger)    0.00% 0/2 0.00% covered(danger)    0.00% 0/2 CRAP0.00% covered (danger)  0.00%  0/1
AAA
  0.00% covered (danger)   0.00% 0/2 0.00% covered(danger)    0.00% 0/26 0.00% covered (danger)
0.00% 0/1
 __construct
  0.00% covered(danger)    0.00% 0/1 0.00% covered(danger)    0.00% 0/1 2
access
  0.00% covered (danger)   0.00% 0/1 0.00% covered(danger)    0.00% 0/1 2


问:
CloudConvert API returning 401 error when converting PDF to Word with JavaScript
I am trying to use the CloudConvert API to convert a PDF file to a Word document using JavaScript, but I am getting a 401 error when making the request. I have checked that my API key is correct and has the necessary scope, but I am still getting the error. What could be causing this issue and how can I fix it?

I tried to use the provided code to convert a PDF file to a Word document using the CloudConvert API and JavaScript. I expected the code to send a request to the CloudConvert API with the base64-encoded PDF file and to receive a response with a download link for the converted Word document. However, I received a 401 error when making the request, indicating that the request was unauthorized. I checked that my API key was correct and had the necessary scope, but the error persisted. I also tried troubleshooting by logging the API response and any error messages to the console, but this did not provide any additional information about the issue.


问:
Timer affect other variables in the struct
In this code, the timer affects the countN variable. Why does it do that? Can someone help?

(@Binding var names: [String] gets the String from another SwiftUI View before opening NamesView.)

Whenever I press the "Start" button to start the countdown from 10-0, the names (that is connected to countN) also change as the countdown goes down. The reason I do not understand this, is that the variable counter stays the same.

Variable counter is for questions, and variable countN is for names.

```<code>struct NamesView: View {

      @Binding var names: [String]
      @State private var counter = 0
      @State private var countN = 0
      @State var showSheet: Bool = false
      @Environment(\.presentationMode) var presentationMode

      func startTimer() {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
          if self.remainingTime > 0 {
            self.remainingTime -= 1
          }
        }
      }

      @State private var remainingTime = 10
      @State private var timer: Timer?

    @State private var fysiskUtf =
    ["Find", "Get", "Photo", "Steal"].shuffled()

    var body: some View {

        ZStack {

            LinearGradient(colors:[
            Color(red: 164/255, green: 199/255, blue: 149/255), Color(red: 99/255, green: 193/255, blue: 147/255)]
                           ,startPoint: .topLeading, endPoint: .bottomTrailing).ignoresSafeArea()

            HStack{

                Button("Start") {
                    self.startTimer()
                }
                .fontWeight(.bold)
                .foregroundColor(.black)
                .frame(width: 75, height: 75)
                .overlay(
                    RoundedRectangle(cornerRadius: 50)
                        .stroke(Color.black, lineWidth: 6)
                )
                .background()
                .cornerRadius(50)
                .rotationEffect(.degrees(90))

                Text("\(remainingTime)")
                    .padding()
                    .font(.system(size: 40, weight: .bold))
                    .rotationEffect(.degrees(90))

            }
      .padding(.top,750)

// MARK: GAME VIEW
            ZStack {

                LazyVStack(spacing:300) {

                    Button {
                        showSheet.toggle()
                    } label: {
                        Image(systemName: "arrowshape.turn.up.backward")
                            .foregroundColor(.black)
                            .font(.largeTitle)

                    }
                    .padding(.bottom, 300)
                    .padding(.leading, 300)
                    .rotationEffect(.degrees(90))
                    .fullScreenCover(isPresented: $showSheet) {
                        ContentView()
                    }

                    Text("FØRSTEMANN")
                        .frame(width: 400, height: 100)
                        .fontWeight(.bold)
                        .font(.system(size: 50, design: .rounded))
                        .rotationEffect(.degrees(90))
                        .padding(.trailing, -300)
                        .padding(.bottom, 650)

// END LAZYVSTACK:
                }
// MARK: FØRSTE MANN SPILLET:
                ZStack {

                    Text(fysiskUtf[counter])
                    .multilineTextAlignment(.center)
                    .padding(20)
                    .frame(width: 650, height: 200)
                    .fontWeight(.medium)
                    .font(.system(size: 23, design: .rounded))
                    .background(Color.orange.opacity(0.12))
                    .overlay(
                        RoundedRectangle(cornerRadius: 50)
                            .stroke(Color.black, lineWidth: 6)
                    )
                    .cornerRadius(50)
                    .foregroundColor(.black)
                    .padding(.top, 60)
                    .rotationEffect(.degrees(90))

                    Text(names.shuffled()[countN])
                        .rotationEffect(.degrees(90))
                        .font(.system(size: 25, design: .rounded))
                        .fontWeight(.bold)
                        .padding(.leading, 45)
                        .multilineTextAlignment(.center)

// END VSTACK:
            }
// END ZSTACK:
                }
            .navigationBarBackButtonHidden(true)

// END ZSTACK:
        } .statusBarHidden()
            .onTapGesture {
                if fysiskUtf != ["Takk for spillet!"] {
                    self.counter += 1
                    self.countN = (self.countN + 1) % self.names.count
                }

// MARK: SET COUNTER TIL X SPØRSMÅL:
              if counter == 49 {
                    counter = 0
                    fysiskUtf = ["Takk for spillet!"]
                    names = [""]
                    countN = 0
                }

                if self.names.isEmpty {
                    self.names = names.shuffled()
                }
            }

// MARK: END VIEWS:
    }
}
´´´
</code>```

Body:
In this code, the timer affects the countN variable. Why does it do that? Can someone help?

(@Binding var names: [String] gets the String from another SwiftUI View before opening NamesView.)

Whenever I press the "Start" button to start the countdown from 10-0, the names (that is connected to countN) also change as the countdown goes down. The reason I do not understand this, is that the variable counter stays the same.

Variable counter is for questions, and variable countN is for names.

struct NamesView: View {

      @Binding var names: [String]
      @State private var counter = 0
      @State private var countN = 0
      @State var showSheet: Bool = false
      @Environment(\.presentationMode) var presentationMode

      func startTimer() {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
          if self.remainingTime > 0 {
            self.remainingTime -= 1
          }
        }
      }

      @State private var remainingTime = 10
      @State private var timer: Timer?

    @State private var fysiskUtf =
    ["Find", "Get", "Photo", "Steal"].shuffled()

    var body: some View {

        ZStack {

            LinearGradient(colors:[
            Color(red: 164/255, green: 199/255, blue: 149/255), Color(red: 99/255, green: 193/255, blue: 147/255)]
                           ,startPoint: .topLeading, endPoint: .bottomTrailing).ignoresSafeArea()

            HStack{

                Button("Start") {
                    self.startTimer()
                }
                .fontWeight(.bold)
                .foregroundColor(.black)
                .frame(width: 75, height: 75)
                .overlay(
                    RoundedRectangle(cornerRadius: 50)
                        .stroke(Color.black, lineWidth: 6)
                )
                .background()
                .cornerRadius(50)
                .rotationEffect(.degrees(90))

                Text("\(remainingTime)")
                    .padding()
                    .font(.system(size: 40, weight: .bold))
                    .rotationEffect(.degrees(90))

            }
      .padding(.top,750)

// MARK: GAME VIEW
            ZStack {

                LazyVStack(spacing:300) {

                    Button {
                        showSheet.toggle()
                    } label: {
                        Image(systemName: "arrowshape.turn.up.backward")
                            .foregroundColor(.black)
                            .font(.largeTitle)

                    }
                    .padding(.bottom, 300)
                    .padding(.leading, 300)
                    .rotationEffect(.degrees(90))
                    .fullScreenCover(isPresented: $showSheet) {
                        ContentView()
                    }

                    Text("FØRSTEMANN")
                        .frame(width: 400, height: 100)
                        .fontWeight(.bold)
                        .font(.system(size: 50, design: .rounded))
                        .rotationEffect(.degrees(90))
                        .padding(.trailing, -300)
                        .padding(.bottom, 650)

// END LAZYVSTACK:
                }
// MARK: FØRSTE MANN SPILLET:
                ZStack {

                    Text(fysiskUtf[counter])
                    .multilineTextAlignment(.center)
                    .padding(20)
                    .frame(width: 650, height: 200)
                    .fontWeight(.medium)
                    .font(.system(size: 23, design: .rounded))
                    .background(Color.orange.opacity(0.12))
                    .overlay(
                        RoundedRectangle(cornerRadius: 50)
                            .stroke(Color.black, lineWidth: 6)
                    )
                    .cornerRadius(50)
                    .foregroundColor(.black)
                    .padding(.top, 60)
                    .rotationEffect(.degrees(90))

                    Text(names.shuffled()[countN])
                        .rotationEffect(.degrees(90))
                        .font(.system(size: 25, design: .rounded))
                        .fontWeight(.bold)
                        .padding(.leading, 45)
                        .multilineTextAlignment(.center)

// END VSTACK:
            }
// END ZSTACK:
                }
            .navigationBarBackButtonHidden(true)

// END ZSTACK:
        } .statusBarHidden()
            .onTapGesture {
                if fysiskUtf != ["Takk for spillet!"] {
                    self.counter += 1
                    self.countN = (self.countN + 1) % self.names.count
                }

// MARK: SET COUNTER TIL X SPØRSMÅL:
              if counter == 49 {
                    counter = 0
                    fysiskUtf = ["Takk for spillet!"]
                    names = [""]
                    countN = 0
                }

                if self.names.isEmpty {
                    self.names = names.shuffled()
                }
            }

// MARK: END VIEWS:
    }
}
´´´


问:
Working example of UMONITOR/UMWAIT-based assembly (asm) spin-wait loops as a replacement for PAUSE-based test-test-and-set loops
In the Intel 64 and IA-32 Architectures Optimization Reference Manual, Intel gives an example of a PAUSE-based spin-wait loop ("Example 11-4. Spin-wait Loop and PAUSE Instruction").

However, as for the UMONITOR/UMWAIT instruction, there are only mentions without any example ("Support for user level low-power and low-latency spin-loop instructions UMWAIT/UMONITOR and TPAUSE", and "UMWAIT/UMONITOR/TPAUSE instructions enable power savings in user level spin loops"). These new instructions came out with the Tremont Microarchitecture, released by Intel on September 2020 within the Elkhart Lake platform.

Can you please give a working example, on the assembly language, of SpinWaitAndAquireLock and ReleaseLock functions that use a byte value as a synchronization variable (in either 64-bit or 32-bit addressing mode), so that this byte can be only in one of the two states, i.e., contain just two values: cLockByteLocked (e.g., 0FFh) and cLockByteAvailable (e.g., 0)!? I can give such functions using the PAUSE instruction as a reference example, that can be compiled by nasm -f win64:

```<code>section .text

; This code exposes two global functions: (1) SpinWaitAndAquireLock; (2) ReleaseLock.

cLockByteLocked     equ 0FFh
cLockByteAvailable  equ 0

; wait for the byte to not be locked and lock it
global SpinWaitAndAquireLock

; release lock obtained previously by SpinWaitAndAquireLock
global ReleaseLock

SpinWaitAndAquireLock:
; input: rcx - address of the synchronization variable lock byte
   mov  eax, cLockByteLocked ; load the value that denotes "locked" into al; use eax to clear remaining bits to avoid false dependency on existing eax value, bits 32-63 of rax are also cleared
   jmp  @FirstCompare
@NormalLoadLoop:
   pause
@FirstCompare:
; use the "test, test-and-set" technique
   cmp  [rcx], al   ; try normal load first instead of the locked load - "test" is a first part of "test, test-and-set"
   je   @NormalLoadLoop ; for static branch prediction, jump backward means "likely"
   lock xchg [rcx], al  ; since normal load shows the synchronization variable is available, try locked load and store ("test-and-set")
   cmp  al, cLockByteLocked
   je   @NormalLoadLoop
   ret

ReleaseLock:
; input: rcx - address of the synchronization variable lock byte
   mov   byte [rcx], cLockByteAvailable ; just use normal store
   ret
</code>```

Body:
In the Intel 64 and IA-32 Architectures Optimization Reference Manual, Intel gives an example of a PAUSE-based spin-wait loop ("Example 11-4. Spin-wait Loop and PAUSE Instruction").

However, as for the UMONITOR/UMWAIT instruction, there are only mentions without any example ("Support for user level low-power and low-latency spin-loop instructions UMWAIT/UMONITOR and TPAUSE", and "UMWAIT/UMONITOR/TPAUSE instructions enable power savings in user level spin loops"). These new instructions came out with the Tremont Microarchitecture, released by Intel on September 2020 within the Elkhart Lake platform.

Can you please give a working example, on the assembly language, of SpinWaitAndAquireLock and ReleaseLock functions that use a byte value as a synchronization variable (in either 64-bit or 32-bit addressing mode), so that this byte can be only in one of the two states, i.e., contain just two values: cLockByteLocked (e.g., 0FFh) and cLockByteAvailable (e.g., 0)!? I can give such functions using the PAUSE instruction as a reference example, that can be compiled by nasm -f win64:

section .text

; This code exposes two global functions: (1) SpinWaitAndAquireLock; (2) ReleaseLock.

cLockByteLocked     equ 0FFh
cLockByteAvailable  equ 0

; wait for the byte to not be locked and lock it
global SpinWaitAndAquireLock

; release lock obtained previously by SpinWaitAndAquireLock
global ReleaseLock

SpinWaitAndAquireLock:
; input: rcx - address of the synchronization variable lock byte
   mov  eax, cLockByteLocked ; load the value that denotes "locked" into al; use eax to clear remaining bits to avoid false dependency on existing eax value, bits 32-63 of rax are also cleared
   jmp  @FirstCompare
@NormalLoadLoop:
   pause
@FirstCompare:
; use the "test, test-and-set" technique
   cmp  [rcx], al   ; try normal load first instead of the locked load - "test" is a first part of "test, test-and-set"
   je   @NormalLoadLoop ; for static branch prediction, jump backward means "likely"
   lock xchg [rcx], al  ; since normal load shows the synchronization variable is available, try locked load and store ("test-and-set")
   cmp  al, cLockByteLocked
   je   @NormalLoadLoop
   ret

ReleaseLock:
; input: rcx - address of the synchronization variable lock byte
   mov   byte [rcx], cLockByteAvailable ; just use normal store
   ret


问:
How to embed MHTML into page source?
How to embed MHTML into page?

I am using AngularJS and can't find any possible way to achieve something like WaybackMachine does.

Title: How to embed MHTML into page source?


问:
Hibernate "Referencial Integrity Constraint Violation" for ManyToMany Bidirectional Mapping
I have the following model stored in a data base. Upon deletion of a room i receive a Referencial Integrity Constraint Violation, which I can't figure out.

An important rule for the model is: a person MUST have access to a room. If they lose all access (e.g. all rooms they have access to are deleted), they are removed from the database.

The ManyToMany Mapping in Question exists between Person and Room and exists in the form of the table "access". Ill be sharing some code for:

Person.java

Room.java

an excerpt from DAO.java (data access object)

DeleteRoom.java (main)

In order to uphold consistency in my data base i have come up with the following logic which i have tried to implement in DAO.deleteRoomWithConsistency(RoomId roomId), which I shared below:

When a room is deleted i run a loop over all persons who have access to that room:

Now the code:

Person.java:

```<code>@Entity(name = "Person")
@Table(name = "Person")
public class Person {

    public Person(int persNumber, String name, LocalDate dob) {
        super();
        this.persNumber = persNumber;
        this.name = name;
        this.dob = dob;
    }

    @Id
    @Column(name = "persNumber")
    private int persNumber;

    @Column(name = "name")
    private String name;

    @Column(name = "dob")
    private LocalDate dob;

    @ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH}, fetch=FetchType.LAZY)
    @JoinColumn(name="orgUnit")
    private OrgUnit orgUnit;

    public void setOrgUnit(OrgUnit orgUnit) {
        this.orgUnit = orgUnit;
    }

    // List of Rooms a Person has Access to
    // Owning Side of Bidirectional Relationship with Room
    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH}
            )
    @JoinTable(name = "access", joinColumns = @JoinColumn(name = "person_id"),
              inverseJoinColumns = {@JoinColumn(name = "building", referencedColumnName = "building"),
                                   @JoinColumn(name = "number", referencedColumnName = "number")})
    private Set<Room> roomAccess = new HashSet<>();
</code>```

Room.java:

```<code>@Entity(name = "Room")
@Table(name = "Room")
public class Room {

    @EmbeddedId
    private RoomId roomId;

    @Column(name = "area")
    private int area;

    @Column(name = "usetype")
    @Enumerated(EnumType.STRING) //Adds the String Value of the Enum, instead of the ordinal value
    private UseType usetype;

    //List of Persons with Access to a Room
    //Inverse Side of Bidirectional Relationship with Person
    @ManyToMany(mappedBy = "roomAccess", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})
    private Set<Person> personsWithAccess = new HashSet<>();
</code>```

DeleteRoom.java

```<code>public class DeleteRoom {

    public static void main(String[] args) throws SQLException {

        //Connection to the database
        DAO dao = new DAO();
        dao.connect("./db/hw01", "bitub", "");

        //Inputs
        Building b1 = DAO.getInstance().readBuildingByName(
                "Beispielhaus"  //Enter the Building of the Room
                );
        Integer roomNumber = 102; //Enter Room Number

        RoomId toBeDeletedRoomId = new RoomId(b1, roomNumber);

        //Room r = DAO.getInstance().readRoom(toBeDeletedRoomId);
        //System.out.println(r);

        DAO.getInstance().deleteRoomWithConsistency(toBeDeletedRoomId);

        dao.closeConnection();
    }

}
</code>```

excerpt from DAO.java

```<code>public class DAO {

    private static Connection conn;

    public void connect(String url, String username, String password) throws SQLException {

        String connectionURL = "jdbc:h2:" + url;

        try {
            conn = DriverManager.getConnection(connectionURL, username, password);

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

        System.out.println("connecting to " +connectionURL);

    }

    /**
     * Close
     *
     */
    public void closeConnection() throws SQLException {
        conn.close();
    }

/**
* deletes a room by their primary key with consistency
*/
    public void deleteRoomWithConsistency(RoomId roomId) throws SQLException {

        Session session = null;
        Transaction transaction = null;

        try {
            // open the session
            session = HibernateUtil.getSessionFactory().openSession();
            // begin the transaction
            transaction = session.beginTransaction();

            //retrieving room from the database
            Room deletedRoom = (Room) session.find(Room.class, roomId);

            //Set of people who have access to the room with roomId
            Set<Person> peopleWithAccess = this.readPersonsWithAccessForRoom(roomId);
            //keeping consistency
            //for all persons with access to the deleted room
            for (Person pWithAccess : peopleWithAccess) {

                //Set of rooms a pWithAccess has access to
                Set<Room> roomsWithAccess = this.readRoomsWithAccessForPerson(pWithAccess);
                //if
                //this person only has access to one room (the deleted room), the person is deleted
                if (roomsWithAccess.size()==1) {

                    //Set of People who are in the same org unit as pWithAccess
                    Set<Person> orgUnitMembers = this.readOrgUnitMembers(pWithAccess.getOrgUnit().getName());
                    //if
                    //this person is the only person in the org unit, the org unit is deleted, by orphan removal the person is also deleted
                    if(orgUnitMembers.size()==1) {

                        //remove org unit -> remove lonely member (has access to only one room and is the only member of his org unit)
                        session.delete(pWithAccess.getOrgUnit().getName());
                    //there are other people in the orgunit, he/she might be the head of the unit
                    }else{

                        //Boolean if pWithAccess is the head of the unit
                        Boolean isHeadOfUnit = this.checkIfHeadOfUnit(pWithAccess);
                        //if
                        //he/she is head of the unit, a new head of the unit must be appointed
                        if(isHeadOfUnit==true) {

                            Iterator<Person> it = orgUnitMembers.iterator();

                            //appoint the first person, who isn't the old head of unit, the new head of unit
                            while (it.hasNext()) {
                                if (it.next() != pWithAccess) {
                                    pWithAccess.getOrgUnit().setHeadOfUnit(it.next());
                                    break;
                                }
                            }
                        }

                        //remove person (has access to only one room, but is not the only one in his org unit)
                        session.delete(pWithAccess);
                    }
                //this person has access to multiple rooms, the room is deleted from the rooms this person has access to
                } else {
                    session.createSQLQuery(""
                            + "DELETE FROM access  "
                            + "WHERE person_id = '" + pWithAccess.getPersNumber() +"'"
                            + "AND building='" + roomId.getBuildingName()+ "' "
                            + "AND number ='" + roomId.getNumber()+ "' ");
                    //roomsWithAccess.remove(deletedRoom);
                }
            }

            //removing the room
            session.delete(deletedRoom);

            // commit the transaction
            transaction.commit();

        } catch (final HibernateException e) {
            rollbackTransactionIfPossible(transaction);
            e.printStackTrace();
        } catch (final Exception e) {
            rollbackTransactionIfPossible(transaction);
            e.printStackTrace();
        } finally {
            // close the session
            if ((session != null) && session.isOpen()) {
                session.close();
            }
        }
    }

}
</code>```

And finally, when I run my main method to delete a room I get the following output:

```<code>Hibernate: select room0_.building as building4_5_0_, room0_.number as number1_5_0_, room0_.area as area2_5_0_, room0_.usetype as usetype3_5_0_ from Room room0_ where room0_.building=? and room0_.number=?
Hibernate: delete from Room where building=? and number=?
...
Referential integrity constraint violation: "FK3SHH9TEIQLTR6V1EAPFWO13WM: PUBLIC.ACCESS FOREIGN KEY(BUILDING, NUMBER) REFERENCES PUBLIC.ROOM(BUILDING, NUMBER) ('Beispielhaus', 102)"; SQL statement:
delete from Room where building=? and number=? [23503-214]
Dez. 29, 2022 10:04:38 NACHM. org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
...
</code>```

I hope I could provide enough information for someone to help me out. Any insight would be greatly appreciated.

I have tried tinkering with the mapping, adding or removing the CascadeType.REMOVE. But in my research I learned that CascadeType.REMOVE or ALL shouldn't be used for "...ToMany" associations.

I have also tried debugging, but I didn't learn anything from that. The transaction builds up and when it is commited, the error happens.

Any help with this error is greatly appreciated.

Body:
I have the following model stored in a data base. Upon deletion of a room i receive a Referencial Integrity Constraint Violation, which I can't figure out.

An important rule for the model is: a person MUST have access to a room. If they lose all access (e.g. all rooms they have access to are deleted), they are removed from the database.

The ManyToMany Mapping in Question exists between Person and Room and exists in the form of the table "access". Ill be sharing some code for:

Person.java

Room.java

an excerpt from DAO.java (data access object)

DeleteRoom.java (main)

In order to uphold consistency in my data base i have come up with the following logic which i have tried to implement in DAO.deleteRoomWithConsistency(RoomId roomId), which I shared below:

When a room is deleted i run a loop over all persons who have access to that room:

Now the code:

Person.java:

@Entity(name = "Person")
@Table(name = "Person")
public class Person {

    public Person(int persNumber, String name, LocalDate dob) {
        super();
        this.persNumber = persNumber;
        this.name = name;
        this.dob = dob;
    }

    @Id
    @Column(name = "persNumber")
    private int persNumber;

    @Column(name = "name")
    private String name;

    @Column(name = "dob")
    private LocalDate dob;

    @ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH}, fetch=FetchType.LAZY)
    @JoinColumn(name="orgUnit")
    private OrgUnit orgUnit;

    public void setOrgUnit(OrgUnit orgUnit) {
        this.orgUnit = orgUnit;
    }

    // List of Rooms a Person has Access to
    // Owning Side of Bidirectional Relationship with Room
    @ManyToMany(fetch = FetchType.LAZY,
            cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH}
            )
    @JoinTable(name = "access", joinColumns = @JoinColumn(name = "person_id"),
              inverseJoinColumns = {@JoinColumn(name = "building", referencedColumnName = "building"),
                                   @JoinColumn(name = "number", referencedColumnName = "number")})
    private Set<Room> roomAccess = new HashSet<>();

Room.java:

@Entity(name = "Room")
@Table(name = "Room")
public class Room {

    @EmbeddedId
    private RoomId roomId;

    @Column(name = "area")
    private int area;

    @Column(name = "usetype")
    @Enumerated(EnumType.STRING) //Adds the String Value of the Enum, instead of the ordinal value
    private UseType usetype;

    //List of Persons with Access to a Room
    //Inverse Side of Bidirectional Relationship with Person
    @ManyToMany(mappedBy = "roomAccess", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})
    private Set<Person> personsWithAccess = new HashSet<>();

DeleteRoom.java

public class DeleteRoom {

    public static void main(String[] args) throws SQLException {

        //Connection to the database
        DAO dao = new DAO();
        dao.connect("./db/hw01", "bitub", "");

        //Inputs
        Building b1 = DAO.getInstance().readBuildingByName(
                "Beispielhaus"  //Enter the Building of the Room
                );
        Integer roomNumber = 102; //Enter Room Number

        RoomId toBeDeletedRoomId = new RoomId(b1, roomNumber);

        //Room r = DAO.getInstance().readRoom(toBeDeletedRoomId);
        //System.out.println(r);

        DAO.getInstance().deleteRoomWithConsistency(toBeDeletedRoomId);

        dao.closeConnection();
    }

}

excerpt from DAO.java

public class DAO {

    private static Connection conn;

    public void connect(String url, String username, String password) throws SQLException {

        String connectionURL = "jdbc:h2:" + url;

        try {
            conn = DriverManager.getConnection(connectionURL, username, password);

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

        System.out.println("connecting to " +connectionURL);

    }

    /**
     * Close
     *
     */
    public void closeConnection() throws SQLException {
        conn.close();
    }

/**
* deletes a room by their primary key with consistency
*/
    public void deleteRoomWithConsistency(RoomId roomId) throws SQLException {

        Session session = null;
        Transaction transaction = null;

        try {
            // open the session
            session = HibernateUtil.getSessionFactory().openSession();
            // begin the transaction
            transaction = session.beginTransaction();

            //retrieving room from the database
            Room deletedRoom = (Room) session.find(Room.class, roomId);

            //Set of people who have access to the room with roomId
            Set<Person> peopleWithAccess = this.readPersonsWithAccessForRoom(roomId);
            //keeping consistency
            //for all persons with access to the deleted room
            for (Person pWithAccess : peopleWithAccess) {

                //Set of rooms a pWithAccess has access to
                Set<Room> roomsWithAccess = this.readRoomsWithAccessForPerson(pWithAccess);
                //if
                //this person only has access to one room (the deleted room), the person is deleted
                if (roomsWithAccess.size()==1) {

                    //Set of People who are in the same org unit as pWithAccess
                    Set<Person> orgUnitMembers = this.readOrgUnitMembers(pWithAccess.getOrgUnit().getName());
                    //if
                    //this person is the only person in the org unit, the org unit is deleted, by orphan removal the person is also deleted
                    if(orgUnitMembers.size()==1) {

                        //remove org unit -> remove lonely member (has access to only one room and is the only member of his org unit)
                        session.delete(pWithAccess.getOrgUnit().getName());
                    //there are other people in the orgunit, he/she might be the head of the unit
                    }else{

                        //Boolean if pWithAccess is the head of the unit
                        Boolean isHeadOfUnit = this.checkIfHeadOfUnit(pWithAccess);
                        //if
                        //he/she is head of the unit, a new head of the unit must be appointed
                        if(isHeadOfUnit==true) {

                            Iterator<Person> it = orgUnitMembers.iterator();

                            //appoint the first person, who isn't the old head of unit, the new head of unit
                            while (it.hasNext()) {
                                if (it.next() != pWithAccess) {
                                    pWithAccess.getOrgUnit().setHeadOfUnit(it.next());
                                    break;
                                }
                            }
                        }

                        //remove person (has access to only one room, but is not the only one in his org unit)
                        session.delete(pWithAccess);
                    }
                //this person has access to multiple rooms, the room is deleted from the rooms this person has access to
                } else {
                    session.createSQLQuery(""
                            + "DELETE FROM access  "
                            + "WHERE person_id = '" + pWithAccess.getPersNumber() +"'"
                            + "AND building='" + roomId.getBuildingName()+ "' "
                            + "AND number ='" + roomId.getNumber()+ "' ");
                    //roomsWithAccess.remove(deletedRoom);
                }
            }

            //removing the room
            session.delete(deletedRoom);

            // commit the transaction
            transaction.commit();

        } catch (final HibernateException e) {
            rollbackTransactionIfPossible(transaction);
            e.printStackTrace();
        } catch (final Exception e) {
            rollbackTransactionIfPossible(transaction);
            e.printStackTrace();
        } finally {
            // close the session
            if ((session != null) && session.isOpen()) {
                session.close();
            }
        }
    }

}

And finally, when I run my main method to delete a room I get the following output:

Hibernate: select room0_.building as building4_5_0_, room0_.number as number1_5_0_, room0_.area as area2_5_0_, room0_.usetype as usetype3_5_0_ from Room room0_ where room0_.building=? and room0_.number=?
Hibernate: delete from Room where building=? and number=?
...
Referential integrity constraint violation: "FK3SHH9TEIQLTR6V1EAPFWO13WM: PUBLIC.ACCESS FOREIGN KEY(BUILDING, NUMBER) REFERENCES PUBLIC.ROOM(BUILDING, NUMBER) ('Beispielhaus', 102)"; SQL statement:
delete from Room where building=? and number=? [23503-214]
Dez. 29, 2022 10:04:38 NACHM. org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
...

I hope I could provide enough information for someone to help me out. Any insight would be greatly appreciated.

I have tried tinkering with the mapping, adding or removing the CascadeType.REMOVE. But in my research I learned that CascadeType.REMOVE or ALL shouldn't be used for "...ToMany" associations.

I have also tried debugging, but I didn't learn anything from that. The transaction builds up and when it is commited, the error happens.

Any help with this error is greatly appreciated.


问:
How to reference div container in vue3 (js) - antv/x6
How do I reference contaniner from template within the script?

```<code><template>
<div id="container"></div>
</template>

<script>
import { Graph, Node, Shape, Edge } from '@antv/x6'

const graph = new Graph({
   container: document.getElementById('container'),
   width: 100,
   height: 100,
});

export default {

   data() {
      return {
         items: [],
      };
   },
   created() {
   },
   methods: {
   }

};
</script>

<style></style>
</code>```

Body:
How do I reference contaniner from template within the script?

<template>

</template>


问:
Why am I not seeing my platform driver in my Yocto distribution?
I am using Yocto for on a raspberry pi 3.
I patched my distribution's device tree so it contains the following simplistic node:

```<code>       mynode {
                compatible = "my_driver";
                firmware = <0x06>;
                status = "okay";
                phandle = <0x31>;
        };

</code>```

This is the actual patch I applied:

```<code>+/ {
+       myNode: mynode {
+               compatible = "my_driver";
+               firmware = <0x06>;
+               status = "okay";
+               phandle = <0x31>;
+       };
+};
+
</code>```

I also wrote a simplistic platform driver like so:

```<code>...
#include <linux/mod_devicetable.h>
#include <linux/of.h>
#include <linux/platform_device.h>

int my_probe(struct platform_device * pDev)
{
    printk("Entered my probe.\n");

    struct resource* regs = platform_get_resource(pDev, IORESOURCE_MEM, 0);
    if (!regs) {
        dev_err(&pDev->dev, "could not get IO memory\n");
        printk("Failed to get resource\n");
        return -ENXIO;
    }

    printk("My module initialized.\n");

    return 0;
}

static int my_remove(struct platform_device *pdev)
{
    return 0;
}

static const struct of_device_id my_match_table[] = {
    {
        .compatible = "my_driver",
    },
    { },
};

static struct platform_driver my_platform_driver = {
    .probe      = my_probe,
    .remove     = my_remove,
    .driver     = {
        .name   = "my_driver",
        .owner = THIS_MODULE,
        .of_match_table = of_match_ptr(my_match_table),
    },
};

static int __init my_init(void)
{
        printk("My driver's init\n");
        return platform_driver_probe(&my_platform_driver, my_probe);
}

static void __exit my_exit(void)
{
        printk("My driver's exit\n");
        platform_driver_unregister(&my_platform_driver);
}

module_init(my_init);
module_exit(my_exit);
MODULE_DEVICE_TABLE(of, my_match_table);
MODULE_LICENSE("GPL");

</code>```

This is how I compile the driver itself:

```<code>obj-m += my_driver.o
all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
        rm -f *.ko *.symvers *.mod *.mod.c *.mod.o *.o *.order

</code>```

I can see my node under:

/sys/firmware/devicetree/base/mynode

/sys/firmware/devicetree/base/symbols/myNode

/sys/bus/platform/device/mynode

sys/devices/platform/mynode

nothing on the system wrt "my_driver".

This is the recipe specifically for the driver:

```<code>FILESEXTRAPATHS_prepend := "${THISDIR}:"

LICENSE="CLOSED"
LIC_FILES_CHKSUM=""

ALLOW_EMPTY_${PN} = "1"

SRC_URI = "file://src"
S = "${WORKDIR}/src"
TARGET_CC_ARCH += "${LDFLAGS}"

do_compile() {
    oe_runmake
}

</code>```

So I set up a couple of things right so far. I do however:

not see a my_driver entry in /dev

not see my printk messages in dmesg when the system boots

I thought that with all of the above setup I should see something in my dmesg and under /dev. Yet, I don't see anything. Are there additional steps that need to be undertaken in order for this to happen? I thought that as my device tree's compatible property is the same as my platform's driver the kernel would match them and do what I just said above.

Is my understanding wrong? What am I missing here?

I tried going through the Linux's documentation again but nothing caught my attention. I at least expected something to appear in dmesg to understand what is going on, but nothing in there.

EDIT:

This is the device full tree https://pastebin.com/jvNnN0es

Body:
I am using Yocto for on a raspberry pi 3.
I patched my distribution's device tree so it contains the following simplistic node:

       mynode {
                compatible = "my_driver";
                firmware = <0x06>;
                status = "okay";
                phandle = <0x31>;
        };

This is the actual patch I applied:

+/ {
+       myNode: mynode {
+               compatible = "my_driver";
+               firmware = <0x06>;
+               status = "okay";
+               phandle = <0x31>;
+       };
+};
+

I also wrote a simplistic platform driver like so:

...
#include <linux/mod_devicetable.h>
#include <linux/of.h>
#include <linux/platform_device.h>

int my_probe(struct platform_device * pDev)
{
    printk("Entered my probe.\n");

    struct resource* regs = platform_get_resource(pDev, IORESOURCE_MEM, 0);
    if (!regs) {
        dev_err(&pDev->dev, "could not get IO memory\n");
        printk("Failed to get resource\n");
        return -ENXIO;
    }

    printk("My module initialized.\n");

    return 0;
}

static int my_remove(struct platform_device *pdev)
{
    return 0;
}

static const struct of_device_id my_match_table[] = {
    {
        .compatible = "my_driver",
    },
    { },
};

static struct platform_driver my_platform_driver = {
    .probe      = my_probe,
    .remove     = my_remove,
    .driver     = {
        .name   = "my_driver",
        .owner = THIS_MODULE,
        .of_match_table = of_match_ptr(my_match_table),
    },
};

static int __init my_init(void)
{
        printk("My driver's init\n");
        return platform_driver_probe(&my_platform_driver, my_probe);
}

static void __exit my_exit(void)
{
        printk("My driver's exit\n");
        platform_driver_unregister(&my_platform_driver);
}

module_init(my_init);
module_exit(my_exit);
MODULE_DEVICE_TABLE(of, my_match_table);
MODULE_LICENSE("GPL");

This is how I compile the driver itself:

obj-m += my_driver.o
all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
        rm -f *.ko *.symvers *.mod *.mod.c *.mod.o *.o *.order

I can see my node under:

/sys/firmware/devicetree/base/mynode

/sys/firmware/devicetree/base/symbols/myNode

/sys/bus/platform/device/mynode

sys/devices/platform/mynode

nothing on the system wrt "my_driver".

This is the recipe specifically for the driver:

FILESEXTRAPATHS_prepend := "${THISDIR}:"

LICENSE="CLOSED"
LIC_FILES_CHKSUM=""

ALLOW_EMPTY_${PN} = "1"

SRC_URI = "file://src"
S = "${WORKDIR}/src"
TARGET_CC_ARCH += "${LDFLAGS}"

do_compile() {
    oe_runmake
}

So I set up a couple of things right so far. I do however:

not see a my_driver entry in /dev

not see my printk messages in dmesg when the system boots

I thought that with all of the above setup I should see something in my dmesg and under /dev. Yet, I don't see anything. Are there additional steps that need to be undertaken in order for this to happen? I thought that as my device tree's compatible property is the same as my platform's driver the kernel would match them and do what I just said above.

Is my understanding wrong? What am I missing here?

I tried going through the Linux's documentation again but nothing caught my attention. I at least expected something to appear in dmesg to understand what is going on, but nothing in there.

EDIT:

This is the device full tree https://pastebin.com/jvNnN0es