问:
How can I consolidate likes and dislikes so that it happens on one button click depending on which user's logged in
The backend is functional and works as intended in terms of tracking which user liked which photo so no problem there.  The data is coming in via the useEffect() gridData hook.

The issue I'm facing is implementing in on the frontend.  In handleLikesBasedOnUserId(), I'm trying to check whether or not the photo is_liked'd by the currently logged in user followed by carrying out likes-- or likes++ depending on is_liked'd value.

I've tried adding && is_liked in the if() block in handleLikesBasedOnUserId() but that didn't work either.

For testing purposes - I've also verified that the is_liked value coming from server is correct because it correctly displays Like and Dislike buttons based on is_liked value:

{ photos.is_liked ? <Button variant="success" onClick={() => handleLikesBasedOnUserId(photos.UserID, photos.name, photos.photo_id, photos.is_liked)}>Like</Button> : <button>Dislike</button> }

But I'd like for this behavior to transpire on one button.  How can I achieve this?

Here's the code:

```<code>const Grid = () => {
let authToken                                                 = localStorage.getItem('token');

const [gridData, setGridData]                                 = useState([]);
const [userLikedPhotos, setUserLikedPhotos]                   = useState({});

useEffect(() => {
    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    };

    axios.get('http://127.0.0.1:8000/api/get-user-uploads-data', {headers})
        .then(resp => {
            console.log(resp.data);
            setGridData(resp.data);
        }).catch(err => {
        console.log(err);
    });

}, []);

const handleLikesBasedOnUserId = (likedPhotoUserId, userName, likedPhotoId, is_liked) => {
    if(userLikedPhotos[likedPhotoUserId]) {
        // dislike
        delete userLikedPhotos[likedPhotoUserId];
        gridData.find(photo => (photo.UserID === likedPhotoUserId && photo.is_liked === is_liked)).likes--;
        handleDislike(likedPhotoUserId, userName, likedPhotoId);
    } else {
        // like
        userLikedPhotos[likedPhotoUserId] = true;
        gridData.find(photo => (photo.UserID === likedPhotoUserId && photo.is_liked === is_liked)).likes++;
        handleLike(likedPhotoUserId, userName, likedPhotoId);
    }

    setUserLikedPhotos({...userLikedPhotos});
};

const handleLike = (likedPhotoUserId, userName, likedPhotoId) => {
    const url = 'http://127.0.0.1:8000/api/like';

    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    };

    let data = {
        'UserID': likedPhotoUserId,
        'userName' : userName,
        'likedPhotoId' : likedPhotoId
    };

    axios.post(url, data, {headers})
        .then(resp => {
            console.log(resp.data);
        }).catch(err => {
        console.log(err);
    });

};

const handleDislike = (likedPhotoUserId, userName, likedPhotoId) => {
    const url = 'http://127.0.0.1:8000/api/dislike';

    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    };

    let data = {
        'UserID': likedPhotoUserId,
        'userName' : userName,
        'dislikedPhotoId' : likedPhotoId
    };

    axios.post(url, data, {headers})
        .then(resp => {
            console.log(resp.data);
        }).catch(err => {
        console.log(err);
    });

};

return (
    <>
        <div className="img-container">
            {
                gridData.map((photos, index) => {
                    return (
                        <>
                            <div className="userDetails">
                                <span className="likesAmt">❤ {photos.likes}</span>
                                <Button variant="success" onClick={() => handleLikesBasedOnUserId(photos.UserID, photos.name, photos.photo_id, photos.is_liked)}>Like/Dislike</Button>
                            </div>
                        </>
                    )
                })
            }
        </div>
    </>
)
}

export default Grid;
</code>```

Body:
The backend is functional and works as intended in terms of tracking which user liked which photo so no problem there.  The data is coming in via the useEffect() gridData hook.

The issue I'm facing is implementing in on the frontend.  In handleLikesBasedOnUserId(), I'm trying to check whether or not the photo is_liked'd by the currently logged in user followed by carrying out likes-- or likes++ depending on is_liked'd value.

I've tried adding && is_liked in the if() block in handleLikesBasedOnUserId() but that didn't work either.

For testing purposes - I've also verified that the is_liked value coming from server is correct because it correctly displays Like and Dislike buttons based on is_liked value:

{ photos.is_liked ? <Button variant="success" onClick={() => handleLikesBasedOnUserId(photos.UserID, photos.name, photos.photo_id, photos.is_liked)}>Like</Button> : <button>Dislike</button> }

But I'd like for this behavior to transpire on one button.  How can I achieve this?

Here's the code:

const Grid = () => {
let authToken                                                 = localStorage.getItem('token');

const [gridData, setGridData]                                 = useState([]);
const [userLikedPhotos, setUserLikedPhotos]                   = useState({});

useEffect(() => {
    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    };

    axios.get('http://127.0.0.1:8000/api/get-user-uploads-data', {headers})
        .then(resp => {
            console.log(resp.data);
            setGridData(resp.data);
        }).catch(err => {
        console.log(err);
    });

}, []);

const handleLikesBasedOnUserId = (likedPhotoUserId, userName, likedPhotoId, is_liked) => {
    if(userLikedPhotos[likedPhotoUserId]) {
        // dislike
        delete userLikedPhotos[likedPhotoUserId];
        gridData.find(photo => (photo.UserID === likedPhotoUserId && photo.is_liked === is_liked)).likes--;
        handleDislike(likedPhotoUserId, userName, likedPhotoId);
    } else {
        // like
        userLikedPhotos[likedPhotoUserId] = true;
        gridData.find(photo => (photo.UserID === likedPhotoUserId && photo.is_liked === is_liked)).likes++;
        handleLike(likedPhotoUserId, userName, likedPhotoId);
    }

    setUserLikedPhotos({...userLikedPhotos});
};

const handleLike = (likedPhotoUserId, userName, likedPhotoId) => {
    const url = 'http://127.0.0.1:8000/api/like';

    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    };

    let data = {
        'UserID': likedPhotoUserId,
        'userName' : userName,
        'likedPhotoId' : likedPhotoId
    };

    axios.post(url, data, {headers})
        .then(resp => {
            console.log(resp.data);
        }).catch(err => {
        console.log(err);
    });

};

const handleDislike = (likedPhotoUserId, userName, likedPhotoId) => {
    const url = 'http://127.0.0.1:8000/api/dislike';

    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    };

    let data = {
        'UserID': likedPhotoUserId,
        'userName' : userName,
        'dislikedPhotoId' : likedPhotoId
    };

    axios.post(url, data, {headers})
        .then(resp => {
            console.log(resp.data);
        }).catch(err => {
        console.log(err);
    });

};

return (
    <>

            {
                gridData.map((photos, index) => {
                    return (
                        <>

                                ❤ {photos.likes}
                                <Button variant="success" onClick={() => handleLikesBasedOnUserId(photos.UserID, photos.name, photos.photo_id, photos.is_liked)}>Like/Dislike</Button>

                        </>
                    )
                })
            }

    </>
)
}

export default Grid;


来源: stackexchange

问:
generate a list<Object> from all docs inside a firebase collection reference using withConverter
I'm using Firebase in my Flutter based Anroid-App to store some user data, but I'm a little confused on how to get it back inside a list<Object>.

```<code>
  final ref = db.collection('users').doc(user.uid).collection('presets').withConverter(
    fromFirestore: Preset.fromFirestore,
    toFirestore: (Preset preset, options) => preset.toFirestore(),
  );
  final snapshot = await ref.get();
  if (snapshot.size == 0) {
    //Presetlist doesn't exist, store default preset-list to firestore
    List<Preset>? presets = AppState.list; //list that holds preset-objects
    for (var preset in presets!) {
      await ref.doc(preset.id.toString()).set(preset).onError((e, _) => print("Error writing document: $e"));
  }
  } else {
    final queryList = snapshot.docs; // ??? - returns List<QueryDocumentSnapshot<Preset>>
    // how do i use 'fromFirestore' here to fill the list
}

</code>```

the corresponding functions in the Preset class look like this:

```<code>
  Map<String, Object?> toFirestore() {
    return {
      "eggWeight": eggWeight,
      "yolkTemp": yolkTemp,
      "envTemp": envTemp,
    };
  }

  factory Preset.fromFirestore(
    DocumentSnapshot<Map<String, dynamic>> snapshot,
    SnapshotOptions? options,
  ) {
    final data = snapshot.data();
    return Preset(eggWeight: data?['eggWeight'], envTemp: data?['envTemp'], yolkTemp: data?['yolkTemp']);
  }

</code>```

all this was written referencing this doc: https://firebase.google.com/docs/firestore/query-data/get-data

writing to firestore here works as it should, but I'm unsure on how to iterate the List<QueryDocumentSnapshot> which gets returned from snapshot.data() to call Preset.fromFirestore.

i tried queryList.forEach but i can't invoke Preset.fromFirestore from the elements. Only way i can see would be to read the data of each element and call the standard constructor of Preset manually, but this kind of defeats the point of using .withConverter in the CollectionsReference.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Firebase in my Flutter based Anroid-App to store some user data, but I'm a little confused on how to get it back inside a list<Object>.

  final ref = db.collection('users').doc(user.uid).collection('presets').withConverter(
    fromFirestore: Preset.fromFirestore,
    toFirestore: (Preset preset, options) => preset.toFirestore(),
  );
  final snapshot = await ref.get();
  if (snapshot.size == 0) {
    //Presetlist doesn't exist, store default preset-list to firestore
    List<Preset>? presets = AppState.list; //list that holds preset-objects
    for (var preset in presets!) {
      await ref.doc(preset.id.toString()).set(preset).onError((e, _) => print("Error writing document: $e"));
  }
  } else {
    final queryList = snapshot.docs; // ??? - returns List<QueryDocumentSnapshot<Preset>>
    // how do i use 'fromFirestore' here to fill the list
}

the corresponding functions in the Preset class look like this:

  Map<String, Object?> toFirestore() {
    return {
      "eggWeight": eggWeight,
      "yolkTemp": yolkTemp,
      "envTemp": envTemp,
    };
  }

  factory Preset.fromFirestore(
    DocumentSnapshot<Map<String, dynamic>> snapshot,
    SnapshotOptions? options,
  ) {
    final data = snapshot.data();
    return Preset(eggWeight: data?['eggWeight'], envTemp: data?['envTemp'], yolkTemp: data?['yolkTemp']);
  }

all this was written referencing this doc: https://firebase.google.com/docs/firestore/query-data/get-data

writing to firestore here works as it should, but I'm unsure on how to iterate the List<QueryDocumentSnapshot> which gets returned from snapshot.data() to call Preset.fromFirestore.

i tried queryList.forEach but i can't invoke Preset.fromFirestore from the elements. Only way i can see would be to read the data of each element and call the standard constructor of Preset manually, but this kind of defeats the point of using .withConverter in the CollectionsReference.


问:
.Net ClientWebSocket ReceiveAsync throwing The remote party closed the WebSocket
I have a Console App that needs to send a message to a web socket and after receive messages from it.

The problem I am having is, when ClientWebSocket "ReceiveAsync" method is called, I am getting the following error message:

The remote party closed the WebSocket connection without completing the close handshake.

Here is the Exception StackTrace:

Exception thrown: 'System.Net.WebSockets.WebSocketException' in System.Private.CoreLib.dll
An exception of type 'System.Net.WebSockets.WebSocketException' occurred in System.Private.CoreLib.dll but was not handled in user code
The remote party closed the WebSocket connection without completing the close handshake.

And here is my code:

```<code>        var connectMsg = ConnectMsg.Replace("token", token);

        using var socket = new ClientWebSocket();

        await socket.ConnectAsync(new Uri(Uri), CancellationToken.None);

        var data = Encoding.ASCII.GetBytes(connectMsg);

        var buffer = new ArraySegment<byte>(data, 0, data.Length);

        await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);

        var reciveBuffer = new byte[32000];

        while (socket.State == WebSocketState.Open)
        {
            var result = await socket.ReceiveAsync(new ArraySegment<byte>(reciveBuffer), CancellationToken.None);

            if (result.MessageType == WebSocketMessageType.Close)
            {
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
            else
            {
                await HandleMessage(reciveBuffer, result.Count);
            }
        }
</code>```

Can anyone explain me why am I getting that Error and how I can solve it?

Bests

Body:
I have a Console App that needs to send a message to a web socket and after receive messages from it.

The problem I am having is, when ClientWebSocket "ReceiveAsync" method is called, I am getting the following error message:

The remote party closed the WebSocket connection without completing the close handshake.

Here is the Exception StackTrace:

Exception thrown: 'System.Net.WebSockets.WebSocketException' in System.Private.CoreLib.dll
An exception of type 'System.Net.WebSockets.WebSocketException' occurred in System.Private.CoreLib.dll but was not handled in user code
The remote party closed the WebSocket connection without completing the close handshake.

And here is my code:

        var connectMsg = ConnectMsg.Replace("token", token);

        using var socket = new ClientWebSocket();

        await socket.ConnectAsync(new Uri(Uri), CancellationToken.None);

        var data = Encoding.ASCII.GetBytes(connectMsg);

        var buffer = new ArraySegment<byte>(data, 0, data.Length);

        await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);

        var reciveBuffer = new byte[32000];

        while (socket.State == WebSocketState.Open)
        {
            var result = await socket.ReceiveAsync(new ArraySegment<byte>(reciveBuffer), CancellationToken.None);

            if (result.MessageType == WebSocketMessageType.Close)
            {
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
            else
            {
                await HandleMessage(reciveBuffer, result.Count);
            }
        }

Can anyone explain me why am I getting that Error and how I can solve it?

Bests


问:
How to change part of a muon object in python when the shape differs
I've been trying to make changes to a muon object in python.

```<code>import pandas as pd
import sys
import os
import muon
import muon as mu
import numpy as np

madata = mu.read("Example_data.h5mu")
df = madata.mod['atac'].var

# change the data frame

madata.mod['atac'].var = df2
madata.write("data.h5mu")
</code>```

It fails on the line madata.mod['atac'].var = df2

```<code>ValueError: Length of passed value for var_names is 145857, but this AnnData has shape: (82798, 111556)
</code>```

The problem is pretty obviously that the muon object doesn't expect the shape to change but I can't find an obvious setter function or a way to change the shape of an existing table in muon or update one though I may be missing an option.

Body:
I've been trying to make changes to a muon object in python.

import pandas as pd
import sys
import os
import muon
import muon as mu
import numpy as np

madata = mu.read("Example_data.h5mu")
df = madata.mod['atac'].var

# change the data frame

madata.mod['atac'].var = df2
madata.write("data.h5mu")

It fails on the line madata.mod['atac'].var = df2

ValueError: Length of passed value for var_names is 145857, but this AnnData has shape: (82798, 111556)

The problem is pretty obviously that the muon object doesn't expect the shape to change but I can't find an obvious setter function or a way to change the shape of an existing table in muon or update one though I may be missing an option.


问:
How do I get Powershell's Intellisense to auto-complete properties, cmdlets, parameters based on modules and Azure tenant values?
I'm using Powershell ISE, Powershell 5.1, and the Az module. I've got a wonderful Intellisense auto-complete setup that I can't seem to replicate in other powershell environments, so I'm wondering what I need to add to get the same behaviour. My current Intellisense can auto-complete:

Cmdlets based on my installed modules:
If I type in "Connect-" it suggests "Connect-AzAccount"

Cmdlet parameters, based on my installed modules:
If I type in '-' after the Set-AzContext cmdlet, it lists all of that cmdlet's available parameters

Parameter values, based on my Azure tenant and current context:
After typing in the '-ResourceGroupName' parameter, it lists existing resource group names from my context's subscription

Object properties
Typing in '.' after the variable lists all the members and functions of the object within

All of these makes this environment ideal for development, but Powershell ISE is no longer being developed and can't support any Powershell version beyond 5.1. I want to get this same capability on a fresh install of Powershell 7.3 while working in Visual Studio Code. What do I need to make this happen?

Current powershell versions:
Current PSVersion

I've tried installing other Intellisense packages on an install of Powershell 7.3, but they're all history-based, which isn't as useful as suggestions based on modules or Azure, and my few hours of searching for module-based or azure-based Intellisense autocomplete haven't yielded anything useful yet.

I want a better understanding of what libraries and tools are powering my Intellisense suggestions, so that I can replicate this excellent Intellisense setup elsewhere.


问:
Automate the requirements.txt file install with pip for git password
I have a requirements.txt file that has some packages from a private repo. When I run the command pip install -r requirements.txt it prompts me to enter username and password for this repo.

I am wondering if there is a way to supply that to it or use some sort of environment variable that it gets the username and password?

e.g.

```<code>boto3
myproject@git+https://git.my-repo.com/com/bla.git@ksdidmop1012m
</code>```

Body:
I have a requirements.txt file that has some packages from a private repo. When I run the command pip install -r requirements.txt it prompts me to enter username and password for this repo.

I am wondering if there is a way to supply that to it or use some sort of environment variable that it gets the username and password?

e.g.

boto3
myproject@git+https://git.my-repo.com/com/bla.git@ksdidmop1012m


问:
Angular material theme select renders with dark background at first?
In this Angular Material theme demo the first time we click the theme select dropdown the select background is dark (It's supposed to be light).

If we select the dark theme and then select the light theme again, and then again click on the theme select dropdown, it is rendered with the proper light background.

Anyone know why it gets rendered with a dark background at first?

This is the styles.scss file defining the themes:

```<code>@use 'sass:map';
@use '@fireflysemantics/sass-logger' as logger;
// Custom Theming for Angular Material
// For more information: https://material.angular.io/guide/theming
@use '@angular/material' as mat;
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat.core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$app-primary: mat.define-palette(mat.$indigo-palette, A400);
$app-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

$app-dark-primary: mat.define-palette(mat.$indigo-palette, A400, A400);
$app-dark-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

// The warn palette is optional (defaults to red).
$app-warn: mat.define-palette(mat.$red-palette);

// Create the theme object. A theme consists of configurations for individual
// theming systems such as "color" or "typography".
$light-theme: mat.define-light-theme(
  (
    color: (
      primary: $app-primary,
      accent: $app-accent,
      warn: $app-warn,
    ),
  )
);

$dark-theme: mat.define-dark-theme(
  (
    color: (
      primary: $app-dark-primary,
      accent: $app-dark-accent,
      warn: $app-warn,
    ),
  )
);

$result: logger.pretty-map($dark-theme);
@debug ($result);

.light-theme {
  @include mat.core-theme($light-theme);
  @include mat.all-component-colors($light-theme);
}

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
.dark-theme {
  @include mat.core-theme($dark-theme);
  @include mat.all-component-colors($dark-theme);
}

/* You can add global styles to this file, and also import other style files */

html,
body {
  height: 100%;
}

body {
  margin: 0;
  font-family: Roboto, 'Helvetica Neue', sans-serif;
}
</code>```

Body:
In this Angular Material theme demo the first time we click the theme select dropdown the select background is dark (It's supposed to be light).

If we select the dark theme and then select the light theme again, and then again click on the theme select dropdown, it is rendered with the proper light background.

Anyone know why it gets rendered with a dark background at first?

This is the styles.scss file defining the themes:

@use 'sass:map';
@use '@fireflysemantics/sass-logger' as logger;
// Custom Theming for Angular Material
// For more information: https://material.angular.io/guide/theming
@use '@angular/material' as mat;
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat.core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$app-primary: mat.define-palette(mat.$indigo-palette, A400);
$app-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

$app-dark-primary: mat.define-palette(mat.$indigo-palette, A400, A400);
$app-dark-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

// The warn palette is optional (defaults to red).
$app-warn: mat.define-palette(mat.$red-palette);

// Create the theme object. A theme consists of configurations for individual
// theming systems such as "color" or "typography".
$light-theme: mat.define-light-theme(
  (
    color: (
      primary: $app-primary,
      accent: $app-accent,
      warn: $app-warn,
    ),
  )
);

$dark-theme: mat.define-dark-theme(
  (
    color: (
      primary: $app-dark-primary,
      accent: $app-dark-accent,
      warn: $app-warn,
    ),
  )
);

$result: logger.pretty-map($dark-theme);
@debug ($result);

.light-theme {
  @include mat.core-theme($light-theme);
  @include mat.all-component-colors($light-theme);
}

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
.dark-theme {
  @include mat.core-theme($dark-theme);
  @include mat.all-component-colors($dark-theme);
}

/* You can add global styles to this file, and also import other style files */

html,
body {
  height: 100%;
}

body {
  margin: 0;
  font-family: Roboto, 'Helvetica Neue', sans-serif;
}


问:
Laravel Custom Exception not being detected by expectException Assertion
I am having trouble detecting if my custom exception is thrown.

In my unit test, if I do:

```<code>throw new MyCustomException("an exception");
$this->expectException(MyCustomException::class);
</code>```

The exception is detected no problem.

If however, I throw this Exception within Laravel Excel, the exception is thrown,
AND shows up in $this->response->exceptions array,

BUT is NOT detected

Why is it not being detected?

When I xDebug into PhPUnits TestCase.php

Line 1547, the exception is not caught in the try

```<code>    try {
            $testResult = $this->{$this->name}(...array_values($testArguments));
        } catch (Throwable $exception) {
            if (!$this->checkExceptionExpectations($exception)) {
                throw $exception;
            }

            if ($this->expectedException !== null) {
                if ($this->expectedException === Error::class) {
                    $this->assertThat(
                        $exception,
                        LogicalOr::fromConstraints(
                            new ExceptionConstraint(Error::class),
                            new ExceptionConstraint(\Error::class)
                        )
                    );
                } else {
                    $this->assertThat(
                        $exception,
                        new ExceptionConstraint(
                            $this->expectedException
                        )
                    );
                }
            }

            if ($this->expectedExceptionMessage !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionMessage(
                        $this->expectedExceptionMessage
                    )
                );
            }

            if ($this->expectedExceptionMessageRegExp !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionMessageRegularExpression(
                        $this->expectedExceptionMessageRegExp
                    )
                );
            }

            if ($this->expectedExceptionCode !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionCode(
                        $this->expectedExceptionCode
                    )
                );
            }

            return;
        }
</code>```

Body:
I am having trouble detecting if my custom exception is thrown.

In my unit test, if I do:

throw new MyCustomException("an exception");
$this->expectException(MyCustomException::class);

The exception is detected no problem.

If however, I throw this Exception within Laravel Excel, the exception is thrown,
AND shows up in $this->response->exceptions array,

BUT is NOT detected

Why is it not being detected?

When I xDebug into PhPUnits TestCase.php

Line 1547, the exception is not caught in the try

    try {
            $testResult = $this->{$this->name}(...array_values($testArguments));
        } catch (Throwable $exception) {
            if (!$this->checkExceptionExpectations($exception)) {
                throw $exception;
            }

            if ($this->expectedException !== null) {
                if ($this->expectedException === Error::class) {
                    $this->assertThat(
                        $exception,
                        LogicalOr::fromConstraints(
                            new ExceptionConstraint(Error::class),
                            new ExceptionConstraint(\Error::class)
                        )
                    );
                } else {
                    $this->assertThat(
                        $exception,
                        new ExceptionConstraint(
                            $this->expectedException
                        )
                    );
                }
            }

            if ($this->expectedExceptionMessage !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionMessage(
                        $this->expectedExceptionMessage
                    )
                );
            }

            if ($this->expectedExceptionMessageRegExp !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionMessageRegularExpression(
                        $this->expectedExceptionMessageRegExp
                    )
                );
            }

            if ($this->expectedExceptionCode !== null) {
                $this->assertThat(
                    $exception,
                    new ExceptionCode(
                        $this->expectedExceptionCode
                    )
                );
            }

            return;
        }


问:
Displaying Full Column Names in DTale output
I just discovered the dtale python module and am extremely impressed. One issue that I'm having trouble with is fully displaying long column names in output (correlation heatmap for example). Does anyone have any suggestions to remedy this?

Thanks!


问:
Splunk DBConnect JDBC When Running Query - com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name
When running this query from Splunk DBConnect I get the following error

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column 'name'

The query runs fine in SSMS.   It is a complex query that JDBC can't process.

Any suggestions would be greatly appreciated

Query:

```<code>SELECT [name]
     , [message]
     , [step_name]
     , [run_status]
     , [server]
     , date_modified
     , msdb.dbo.agent_datetime(run_date, run_time ) as start_time
     , run_duration/10000 as run_duration_hours --hours
     , run_duration/100%100 as run_duration_minutes --minutes
     , run_duration%100 as run_duration_seconds --seconds
     , (run_duration/10000 * 60 * 60) + -- hours as seconds
      (run_duration/100%100 * 60) + --minutes as seconds
      dateadd(ss, run_duration%100, [msdb].[dbo].[agent_datetime](run_date, run_time )) As stop_time
from [msdb].[dbo].[sysjobhistory] jh  join [msdb].[dbo].[sysjobs] sj on jh.job_id=sj.job_id
WHERE ([name] = 'RecurrJob' or [name] = 'AuditLog' or [name] = 'AuditlogArchieve' or [name] = 'AccessRequestRelatedJobs')
        and DATEDIFF(minute, dateadd(ss, run_duration%100, [msdb].[dbo].[agent_datetime](run_date, run_time )),GETDATE()) <= 90
order by [run_date],[run_time] desc
</code>```

I ran the query successfully in SSMS

Body:
When running this query from Splunk DBConnect I get the following error

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column 'name'

The query runs fine in SSMS.   It is a complex query that JDBC can't process.

Any suggestions would be greatly appreciated

Query:

SELECT [name]
     , [message]
     , [step_name]
     , [run_status]
     , [server]
     , date_modified
     , msdb.dbo.agent_datetime(run_date, run_time ) as start_time
     , run_duration/10000 as run_duration_hours --hours
     , run_duration/100%100 as run_duration_minutes --minutes
     , run_duration%100 as run_duration_seconds --seconds
     , (run_duration/10000 * 60 * 60) + -- hours as seconds
      (run_duration/100%100 * 60) + --minutes as seconds
      dateadd(ss, run_duration%100, [msdb].[dbo].[agent_datetime](run_date, run_time )) As stop_time
from [msdb].[dbo].[sysjobhistory] jh  join [msdb].[dbo].[sysjobs] sj on jh.job_id=sj.job_id
WHERE ([name] = 'RecurrJob' or [name] = 'AuditLog' or [name] = 'AuditlogArchieve' or [name] = 'AccessRequestRelatedJobs')
        and DATEDIFF(minute, dateadd(ss, run_duration%100, [msdb].[dbo].[agent_datetime](run_date, run_time )),GETDATE()) <= 90
order by [run_date],[run_time] desc

I ran the query successfully in SSMS


问:
style object in TextRun returning blank
I have a slide with two text boxes, one with 25 point font another with 18, and I want that style info returned from

```<code>const res = await slides.presentations.get({
presentationId: '12sx74Cfsssssj88idssggggtqYVkIiajOPk',
fields: "slides" // or"slides/pageElements/shape/text/textElements/textRun/style/fontSize"
});

</code>```

but the response contains blank style object:

```<code>"textRun": {
              "content": "Cool Header 25 point\n",
              "style": {}
            }

//or if masked used...

{"pageElements":[{"shape":{"text":{"textElements":[{},{"textRun":{"style":{}}}]}}},{"shape":{"text":{"textElements":[{},{"textRun":{"style":{}}}]}}},{"shape":{}},{}]}
</code>```

Am I misunderstanding the style api?

Title: style object in TextRun returning blank

Body:
I have a slide with two text boxes, one with 25 point font another with 18, and I want that style info returned from

const res = await slides.presentations.get({
presentationId: '12sx74Cfsssssj88idssggggtqYVkIiajOPk',
fields: "slides" // or"slides/pageElements/shape/text/textElements/textRun/style/fontSize"
});

but the response contains blank style object:

"textRun": {
              "content": "Cool Header 25 point\n",
              "style": {}
            }

//or if masked used...

{"pageElements":[{"shape":{"text":{"textElements":[{},{"textRun":{"style":{}}}]}}},{"shape":{"text":{"textElements":[{},{"textRun":{"style":{}}}]}}},{"shape":{}},{}]}

Am I misunderstanding the style api?


问:
Save a const value to text file on ReactJS
I'm new to coding so this maybe is an noob question, but here it is:

I have the code bellow running in NodeJS/React and need a const value to be stored in a txt file so i can use it on another app. I searched many ways to do it, but none seems to be what i really need.

Can it be done? Any help would be aprecciated as i need this for a personal stream project.
Thanks in advance to anyone that helped or at least read it.

```<code>function App() {

  const [lifeplayer1, setLifeplayer1] = useState(20);
  const [lifeplayer2, setLifeplayer2] = useState(20);

  function increaseLifepoints(player){
    if(player === 1){
      setLifeplayer1(lifeplayer1+1);
    }
    else if(player === 2){
      setLifeplayer2(lifeplayer2+1);
    }
    saveLife(player);
  }

  function decreaseLifepoints(player){
    if(player === 1){
      setLifeplayer1(lifeplayer1-1);
    }
    else if(player === 2){
      setLifeplayer2(lifeplayer2-1);
    }
    saveLife(player);
  }

  function resetLifepoints(){
    if (window.confirm("Reset Life Points ?")) {
      setLifeplayer1(20);
      setLifeplayer2(20);
      saveLife(1);
      saveLife(2);
    }
  }

  function saveLife(player){
    if(player === 1){
      //save lifeplayer1 into a txt file on my pc
    }
    else if(player === 2){
      //save lifeplayer2 into a txt file on my pc
    }
  }

  return (
    <main className="main">
      <button className="buttonLife" onClick={() => decreaseLifepoints(2)}
        >
        <RxMinus size={40} color="red"
        />
      </button>
      <label for="Player 2" className="Player2">Player 2</label>
      <div className="LifeCounterP2">
        <span>
          {lifeplayer2}
        </span>
      </div>
      <button className="buttonLife" onClick={() => increaseLifepoints(2)}
      >
        <RxPlus size={40} color="green"/>
      </button>
      <button className="buttonReset" onClick={() => resetLifepoints() }
      >
        Reset
      </button>

      <button className="buttonLife" onClick={() => increaseLifepoints(1)}
      >
        <RxPlus size={40} color="green"/>
      </button>
      <div className="LifeCounterP1">
        <span>
          {lifeplayer1}
        </span>
      </div>
      <label for="Player 1" className="Player1">Player 1</label>
      <button className="buttonLife" onClick={() => decreaseLifepoints(1)}
      >
        <RxMinus size={40} color="red"/>
      </button>
    </main>
  );
}

export default App;

</code>```

Body:
I'm new to coding so this maybe is an noob question, but here it is:

I have the code bellow running in NodeJS/React and need a const value to be stored in a txt file so i can use it on another app. I searched many ways to do it, but none seems to be what i really need.

Can it be done? Any help would be aprecciated as i need this for a personal stream project.
Thanks in advance to anyone that helped or at least read it.

function App() {

  const [lifeplayer1, setLifeplayer1] = useState(20);
  const [lifeplayer2, setLifeplayer2] = useState(20);

  function increaseLifepoints(player){
    if(player === 1){
      setLifeplayer1(lifeplayer1+1);
    }
    else if(player === 2){
      setLifeplayer2(lifeplayer2+1);
    }
    saveLife(player);
  }

  function decreaseLifepoints(player){
    if(player === 1){
      setLifeplayer1(lifeplayer1-1);
    }
    else if(player === 2){
      setLifeplayer2(lifeplayer2-1);
    }
    saveLife(player);
  }

  function resetLifepoints(){
    if (window.confirm("Reset Life Points ?")) {
      setLifeplayer1(20);
      setLifeplayer2(20);
      saveLife(1);
      saveLife(2);
    }
  }

  function saveLife(player){
    if(player === 1){
      //save lifeplayer1 into a txt file on my pc
    }
    else if(player === 2){
      //save lifeplayer2 into a txt file on my pc
    }
  }

  return (

      <button className="buttonLife" onClick={() => decreaseLifepoints(2)}
        >
        <RxMinus size={40} color="red"
        />
      </button>
      Player 2

          {lifeplayer2}

      <button className="buttonLife" onClick={() => increaseLifepoints(2)}
      >
        <RxPlus size={40} color="green"/>
      </button>
      <button className="buttonReset" onClick={() => resetLifepoints() }
      >
        Reset
      </button>

      <button className="buttonLife" onClick={() => increaseLifepoints(1)}
      >
        <RxPlus size={40} color="green"/>
      </button>

          {lifeplayer1}

      Player 1
      <button className="buttonLife" onClick={() => decreaseLifepoints(1)}
      >
        <RxMinus size={40} color="red"/>
      </button>

  );
}

export default App;


问:
Trying to manually execute BDD test case in Zypher Scale, but unable to do so. Can somebody help me with this?
This is what I see when I open the test case in test cycle:
https://i.stack.imgur.com/IDNzz.png
Once I click on start new test execution, this pop up comes and after I click on confirm, nothing happens (https://i.stack.imgur.com/vJk4p.png)

Does zypher scale support manually executing these BDD test cases?


问:
Converting a 2D boolean Array into a 2D int Array in Java
I have a few methods that fill a 8 by 8 2D boolean Array with possible Chess Figure Moves ("true" if possible, "false" as standard), depending on their current location.

My task is to take those boolean Arrays depending on a Case, And convert them into a 2D int Array that I can return, which should hold all those boolean Values as coordinates (x1: ; x2: ;...y1: ;y2: ;....

Is there an easy'ish  way to do this?

```<code>public static int[][] getPossibleMoves(int Current_X, int Current_Y, boolean Team, int Figure) {
    int[][] Chessboard = new int[8][8];

    switch(Figure) {
        case 0:
            // do nothing
            break;
        case 1:
            Chessboard = getPossibleMovesPawns(Current_X, Current_Y, Team);
            break;
        case 2:
            Chessboard = getPossibleMovesRooks(Current_X, Current_Y, Team);
            break;
        case 3:
            Chessboard = getPossibleMovesKnights(Current_X, Current_Y, Team);
            break;
        case 4:
            Chessboard = getPossibleMovesBishops(Current_X, Current_Y, Team);
            break;
        case 5:
            Chessboard = getPossibleMovesQueens(Current_X, Current_Y, Team);
            break;
        case 6:
            Chessboard = getPossibleMovesKings(Current_X, Current_Y, Team);
            break;
        default:
            System.out.println("Please choose a number that corresponds to a figure.");
            return null;
        }
        return getCoordinates(Chessboard ); //as a Placeholder for the converting Method
}
</code>```

Couldn't really find any Syntax to this

Body:
I have a few methods that fill a 8 by 8 2D boolean Array with possible Chess Figure Moves ("true" if possible, "false" as standard), depending on their current location.

My task is to take those boolean Arrays depending on a Case, And convert them into a 2D int Array that I can return, which should hold all those boolean Values as coordinates (x1: ; x2: ;...y1: ;y2: ;....

Is there an easy'ish  way to do this?

public static int[][] getPossibleMoves(int Current_X, int Current_Y, boolean Team, int Figure) {
    int[][] Chessboard = new int[8][8];

    switch(Figure) {
        case 0:
            // do nothing
            break;
        case 1:
            Chessboard = getPossibleMovesPawns(Current_X, Current_Y, Team);
            break;
        case 2:
            Chessboard = getPossibleMovesRooks(Current_X, Current_Y, Team);
            break;
        case 3:
            Chessboard = getPossibleMovesKnights(Current_X, Current_Y, Team);
            break;
        case 4:
            Chessboard = getPossibleMovesBishops(Current_X, Current_Y, Team);
            break;
        case 5:
            Chessboard = getPossibleMovesQueens(Current_X, Current_Y, Team);
            break;
        case 6:
            Chessboard = getPossibleMovesKings(Current_X, Current_Y, Team);
            break;
        default:
            System.out.println("Please choose a number that corresponds to a figure.");
            return null;
        }
        return getCoordinates(Chessboard ); //as a Placeholder for the converting Method
}

Couldn't really find any Syntax to this


问:
"creating the pipeline" error from a custom class, but only after saving the ps1 file
UPDATE:
While there are no apostrophes in the file path, there is a dash and a comma. I saved in C:\CleanPathForPS\TestClass.ps1, and it worked!

The error below occurs during runtime, after I save the .ps1 script file.
It does not occur in a new-unsaved file.

```<code>An error occurred while creating the pipeline.
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RuntimeException
</code>```

On other computers, this works fine. It works on my current one if I copy and paste it into a new file in the PowerShell ISE. If I save the file and run it, I get the error above.
For context, this is to display a table of data for a quarterly regulatory thing. The dummy data is just a sqrt of the unit number.

```<code>cls
class AppendixDQuarter{
    [byte]$Num;
    $Units;
        AppendixDQuarter([byte]$NumIn) {
            $this.Num = $NumIn;
            $this.Units = @{
                110 = 0
                111 = 0
                112 = 0
                113 = 0
                114 = 0
            }
        }
}
Class AppendixDDataset{
    [int]$Year;
    $Qtr = @{};
        AppendixDDataset([int]$YearIn) {
            $this.Year = $YearIn;
            For ($q = 1; $q -le 4; $q++) {
                $this.Qtr.Add($q,[AppendixDQuarter]::new($q))
          }
         }
}
$strPrettyTable = ""
$ads = [AppendixDDataset]::new(2022)
$ads.Year
For ($q = 0; $q -le 4; $q++) {
    If ($q -gt 0) {
        $strPrettyTable += "$q"
    } Else {
        $strPrettyTable += "Q"
    }
    For ($b = 110; $b -le 114; $b++) {
        If ($q -eq 0) {
            $strPrettyTable += "`tU$b"
        } Else {
            $ads.Qtr[$q].Units[$b] = [math]::sqrt($b)
            $strPrettyTable += "`t" + "{0:00.0}" -f $ads.Qtr[$q].Units[$b]
        }
        If ($b -eq 114) {
                $strPrettyTable += "`n"
            }
    }
}
Write-Host $strPrettyTable
</code>```

This is what results when it works, on other systems, or before I save the file on this one.

```<code>2022
Q   U110    U111    U112    U113    U114
1   10.5    10.5    10.6    10.6    10.7
2   10.5    10.5    10.6    10.6    10.7
3   10.5    10.5    10.6    10.6    10.7
4   10.5    10.5    10.6    10.6    10.7
</code>```

Body:
UPDATE:
While there are no apostrophes in the file path, there is a dash and a comma. I saved in C:\CleanPathForPS\TestClass.ps1, and it worked!

The error below occurs during runtime, after I save the .ps1 script file.
It does not occur in a new-unsaved file.

An error occurred while creating the pipeline.
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RuntimeException

On other computers, this works fine. It works on my current one if I copy and paste it into a new file in the PowerShell ISE. If I save the file and run it, I get the error above.
For context, this is to display a table of data for a quarterly regulatory thing. The dummy data is just a sqrt of the unit number.

cls
class AppendixDQuarter{
    [byte]$Num;
    $Units;
        AppendixDQuarter([byte]$NumIn) {
            $this.Num = $NumIn;
            $this.Units = @{
                110 = 0
                111 = 0
                112 = 0
                113 = 0
                114 = 0
            }
        }
}
Class AppendixDDataset{
    [int]$Year;
    $Qtr = @{};
        AppendixDDataset([int]$YearIn) {
            $this.Year = $YearIn;
            For ($q = 1; $q -le 4; $q++) {
                $this.Qtr.Add($q,[AppendixDQuarter]::new($q))
          }
         }
}
$strPrettyTable = ""
$ads = [AppendixDDataset]::new(2022)
$ads.Year
For ($q = 0; $q -le 4; $q++) {
    If ($q -gt 0) {
        $strPrettyTable += "$q"
    } Else {
        $strPrettyTable += "Q"
    }
    For ($b = 110; $b -le 114; $b++) {
        If ($q -eq 0) {
            $strPrettyTable += "`tU$b"
        } Else {
            $ads.Qtr[$q].Units[$b] = [math]::sqrt($b)
            $strPrettyTable += "`t" + "{0:00.0}" -f $ads.Qtr[$q].Units[$b]
        }
        If ($b -eq 114) {
                $strPrettyTable += "`n"
            }
    }
}
Write-Host $strPrettyTable

This is what results when it works, on other systems, or before I save the file on this one.

2022
Q   U110    U111    U112    U113    U114
1   10.5    10.5    10.6    10.6    10.7
2   10.5    10.5    10.6    10.6    10.7
3   10.5    10.5    10.6    10.6    10.7
4   10.5    10.5    10.6    10.6    10.7


问:
"WebSocketConnectionClosedException" error Python 3.7 randomly
In python, I try to do client application that is connect to server via websocket. Basicly, I can connect to server with websocket and I can send/receive several message with websocket, but ""websocket._exceptions.WebSocketConnectionClosedException"" error occurs  randomly. This error sometimes occurs when sending the first message and sometimes when several messages are sent.

Also, I have another web application that is connect to same server. The application works on browser (Chrome, Firefox) successfully. Is this case means is server keep-alive always? Can I say that the connection error caused by python client application.

Have you any idea about why "WebSocketConnectionClosedException" error occurs?

Using package:
websocket-client 1.4.2

python version 3.7


问:
Why is my solution to the Consensus Profile Rosalind Challenge wrong?
Given: A collection of at most 10 DNA strings of equal length (at most 1 kbp) in FASTA format.

Return: A consensus string and profile matrix for the collection. (If several possible consensus strings exist, then you may return any one of them.)

Sample Dataset

```<code>>Rosalind_1
ATCCAGCT
>Rosalind_2
GGGCAACT
>Rosalind_3
ATGGATCT
>Rosalind_4
AAGCAACC
>Rosalind_5
TTGGAACT
>Rosalind_6
ATGCCATT
>Rosalind_7
ATGGCACT
</code>```

Sample Output

```<code>ATGCAACT
A: 5 1 0 0 5 5 0 0
C: 0 0 1 4 2 0 6 1
G: 1 1 6 3 0 1 0 0
T: 1 5 0 0 0 1 1 6
</code>```

When I submit my answer into Rosalind I get it wrong.
I don't know if it is formatting or if it is a problem with the actual information I am submitting.

My Solution in R:

```<code>input <- readDNAStringSet("./Rosalind-Input/rosalind_cons.txt")
# Biostrings creates DNAStringset object of FASTA sequences
## already loaded Biostrings/Tidyverse in library

length <- width(input)
# finds length of DNA mol using biostrings width

consensus <- consensusMatrix(input)
# creates consensus matrix from biostring dnastring object

consensusAGCT <- consensus[1:4,]
#removes additional letters/bases that we aren't looking for

answer <- c()
for(i in 1:length[1]) {
  answer[i] <- which(consensusAGCT[, i] == max(consensusAGCT[, i]), arr.ind = TRUE) %>%
    names()
}
# gives the name of each letter that is the max of the column
  # to be added to answer vector

paste(answer, collapse = "")
# collapses answer into a character string instead of vector

cat("A: ", paste(consensusAGCT[1,], collapse = ""));
cat("C: ", paste(consensusAGCT[2,], collapse = ""));
cat("G: ", paste(consensusAGCT[3,], collapse = ""));
cat("T: ", paste(consensusAGCT[4,], collapse = ""))
</code>```

I am getting the following warnings when I run this code:

```<code>50: In answer[i] <- which(consensusAGCT[, i] == max(consensusAGCT[,  ... :
  number of items to replace is not a multiple of replacement length
</code>```

These warnings are because there are multiple maxes at specific vector lengths (i). Rosalind is fine with one of the many correct answers. I created a smaller dataset that verifies that this error is from this. It chooses the first max to add to the answer vector. The answer vector remains the correct length.

To verify the consensus matrix is correct, I reviewed the first few base pairs to see if the consensus matrix and they were correct. I couldn't check all the bases in my longer dataset because there's 998 bases.

This leads me to believe that the issue may be a formatting error? The code below is me trying to turn my answers into the format that Rosalind expects.

I'm not exactly sure how to create line breaks with R so the code prints on separate lines, I'm currently doing that by hand. I don't think that's specifically the issue though since I'm doing it by hand...

```<code>paste(answer, collapse = "")
# collapses answer into a character string instead of vector

cat("A: ", paste(consensusAGCT[1,], collapse = ""));
cat("C: ", paste(consensusAGCT[2,], collapse = ""));
cat("G: ", paste(consensusAGCT[3,], collapse = ""));
cat("T: ", paste(consensusAGCT[4,], collapse = ""))
</code>```

Any insights would be highly appreciated! I've not used stackoverflow before, so if there's anything I'm not formatting optimally please let me know. I'm very new to programming and I want to improve :)

Body:
Given: A collection of at most 10 DNA strings of equal length (at most 1 kbp) in FASTA format.

Return: A consensus string and profile matrix for the collection. (If several possible consensus strings exist, then you may return any one of them.)

Sample Dataset

>Rosalind_1
ATCCAGCT
>Rosalind_2
GGGCAACT
>Rosalind_3
ATGGATCT
>Rosalind_4
AAGCAACC
>Rosalind_5
TTGGAACT
>Rosalind_6
ATGCCATT
>Rosalind_7
ATGGCACT

Sample Output

ATGCAACT
A: 5 1 0 0 5 5 0 0
C: 0 0 1 4 2 0 6 1
G: 1 1 6 3 0 1 0 0
T: 1 5 0 0 0 1 1 6

When I submit my answer into Rosalind I get it wrong.
I don't know if it is formatting or if it is a problem with the actual information I am submitting.

My Solution in R:

input <- readDNAStringSet("./Rosalind-Input/rosalind_cons.txt")
# Biostrings creates DNAStringset object of FASTA sequences
## already loaded Biostrings/Tidyverse in library

length <- width(input)
# finds length of DNA mol using biostrings width

consensus <- consensusMatrix(input)
# creates consensus matrix from biostring dnastring object

consensusAGCT <- consensus[1:4,]
#removes additional letters/bases that we aren't looking for

answer <- c()
for(i in 1:length[1]) {
  answer[i] <- which(consensusAGCT[, i] == max(consensusAGCT[, i]), arr.ind = TRUE) %>%
    names()
}
# gives the name of each letter that is the max of the column
  # to be added to answer vector

paste(answer, collapse = "")
# collapses answer into a character string instead of vector

cat("A: ", paste(consensusAGCT[1,], collapse = ""));
cat("C: ", paste(consensusAGCT[2,], collapse = ""));
cat("G: ", paste(consensusAGCT[3,], collapse = ""));
cat("T: ", paste(consensusAGCT[4,], collapse = ""))

I am getting the following warnings when I run this code:

50: In answer[i] <- which(consensusAGCT[, i] == max(consensusAGCT[,  ... :
  number of items to replace is not a multiple of replacement length

These warnings are because there are multiple maxes at specific vector lengths (i). Rosalind is fine with one of the many correct answers. I created a smaller dataset that verifies that this error is from this. It chooses the first max to add to the answer vector. The answer vector remains the correct length.

To verify the consensus matrix is correct, I reviewed the first few base pairs to see if the consensus matrix and they were correct. I couldn't check all the bases in my longer dataset because there's 998 bases.

This leads me to believe that the issue may be a formatting error? The code below is me trying to turn my answers into the format that Rosalind expects.

I'm not exactly sure how to create line breaks with R so the code prints on separate lines, I'm currently doing that by hand. I don't think that's specifically the issue though since I'm doing it by hand...

paste(answer, collapse = "")
# collapses answer into a character string instead of vector

cat("A: ", paste(consensusAGCT[1,], collapse = ""));
cat("C: ", paste(consensusAGCT[2,], collapse = ""));
cat("G: ", paste(consensusAGCT[3,], collapse = ""));
cat("T: ", paste(consensusAGCT[4,], collapse = ""))

Any insights would be highly appreciated! I've not used stackoverflow before, so if there's anything I'm not formatting optimally please let me know. I'm very new to programming and I want to improve :)


问:
Hyperparameter-Search while adding Special tokens
```<code># define get_model function
    def get_model(params):
        db_config = config
        if params is not None:
            db_config.update({'attention_probs_dropout_prob': params['attention_drop_out'],
                            'hidden_dropout_prob': params['hidden_drop_out']
                            })
        model = AutoModelForSequenceClassification.from_pretrained(
            model_args.model_name_or_path,
            config=db_config,
            cache_dir=model_args.cache_dir,
            revision=model_args.model_revision,
            use_auth_token=True if model_args.use_auth_token else None,
            ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
        )

        if special_tokens is not None:
            model.resize_token_embeddings(len(tokenizer))

        # setup label_to_id
        model.config.label2id = label_to_id
        model.config.id2label = {
            id: label for label, id in config.label2id.items()}
        return model

def ray_hp_space(trial):

        return {
            "attention_drop_out": tune.uniform(0.1, 0.5),

            "hidden_drop_out": tune.uniform(0.1, 0.5),

            "learning_rate": tune.uniform(1e-5, 2e-5),

            "weight_decay": tune.uniform(0.005, 0.01),

            "gradient_accumulation_steps": tune.choice([1, 2, 4]),

            "label_smoothing_factor": tune.choice([.7,.8,.9,.91])

        }

        trainer = Trainer(
            model_init=get_model,
            args=training_args,
            train_dataset=train_dataset if training_args.do_train else None,
            eval_dataset=validation_dataset if training_args.do_eval else None,
            compute_metrics=compute_metrics,
            tokenizer=tokenizer,
            data_collator=data_collator,
            callbacks = [EarlyStoppingCallback(early_stopping_patience=7)]

scheduler = ASHAScheduler(
        metric="f1",
        mode="max",
        max_t=1,
        grace_period=1,
        reduction_factor=2)

    reporter = CLIReporter(
        parameter_columns={
            "weight_decay": "w_decay",
            "learning_rate": "lr",
            "gradient_accumulation_steps": "gradient_accum_steps",
            "label_smoothing_factor": "label_smooth",
            "hidden_drop_out": "hidden_drop_out",
            "attention_drop_out": "attention_drop_out"
        },
        metric_columns=[
            "eval_accuracy", "eval_f1", "eval_loss", "steps"
        ])

    best_trail = trainer.hyperparameter_search(direction="maximize",
                                                backend='ray',
                                                hp_space=ray_hp_space,
                                                n_trials=1,
                                                resources_per_trial={"cpu":2, "gpu":1},
                                                scheduler=scheduler,
                                                keep_checkpoints_num=1,
                                                checkpoint_score_attr="training_iteration",
                                                progress_reporter=reporter,
                                                local_dir="experiments/ray-tune-results/"
                                              )
</code>```

The problem is at some point in the training, create a new instance from the original config (without additional special tokens) and try to copy weights from the current instance which has additional special tokens) and it throws a mismatch errors ? It looks I have to force the model creating the first instance from the original config and after that he has to start use the current config (with additional special tokens). How to fix that ?

Body:
# define get_model function
    def get_model(params):
        db_config = config
        if params is not None:
            db_config.update({'attention_probs_dropout_prob': params['attention_drop_out'],
                            'hidden_dropout_prob': params['hidden_drop_out']
                            })
        model = AutoModelForSequenceClassification.from_pretrained(
            model_args.model_name_or_path,
            config=db_config,
            cache_dir=model_args.cache_dir,
            revision=model_args.model_revision,
            use_auth_token=True if model_args.use_auth_token else None,
            ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
        )

        if special_tokens is not None:
            model.resize_token_embeddings(len(tokenizer))

        # setup label_to_id
        model.config.label2id = label_to_id
        model.config.id2label = {
            id: label for label, id in config.label2id.items()}
        return model

def ray_hp_space(trial):

        return {
            "attention_drop_out": tune.uniform(0.1, 0.5),

            "hidden_drop_out": tune.uniform(0.1, 0.5),

            "learning_rate": tune.uniform(1e-5, 2e-5),

            "weight_decay": tune.uniform(0.005, 0.01),

            "gradient_accumulation_steps": tune.choice([1, 2, 4]),

            "label_smoothing_factor": tune.choice([.7,.8,.9,.91])

        }

        trainer = Trainer(
            model_init=get_model,
            args=training_args,
            train_dataset=train_dataset if training_args.do_train else None,
            eval_dataset=validation_dataset if training_args.do_eval else None,
            compute_metrics=compute_metrics,
            tokenizer=tokenizer,
            data_collator=data_collator,
            callbacks = [EarlyStoppingCallback(early_stopping_patience=7)]

scheduler = ASHAScheduler(
        metric="f1",
        mode="max",
        max_t=1,
        grace_period=1,
        reduction_factor=2)

    reporter = CLIReporter(
        parameter_columns={
            "weight_decay": "w_decay",
            "learning_rate": "lr",
            "gradient_accumulation_steps": "gradient_accum_steps",
            "label_smoothing_factor": "label_smooth",
            "hidden_drop_out": "hidden_drop_out",
            "attention_drop_out": "attention_drop_out"
        },
        metric_columns=[
            "eval_accuracy", "eval_f1", "eval_loss", "steps"
        ])

    best_trail = trainer.hyperparameter_search(direction="maximize",
                                                backend='ray',
                                                hp_space=ray_hp_space,
                                                n_trials=1,
                                                resources_per_trial={"cpu":2, "gpu":1},
                                                scheduler=scheduler,
                                                keep_checkpoints_num=1,
                                                checkpoint_score_attr="training_iteration",
                                                progress_reporter=reporter,
                                                local_dir="experiments/ray-tune-results/"
                                              )

The problem is at some point in the training, create a new instance from the original config (without additional special tokens) and try to copy weights from the current instance which has additional special tokens) and it throws a mismatch errors ? It looks I have to force the model creating the first instance from the original config and after that he has to start use the current config (with additional special tokens). How to fix that ?


问:
Drag and drop in Tauri + Yew
I am having issues with handling drag and drop. I prevent_default on my drop target for both the dragEnter and dragOver events, which I can verify are firing, but the drop event is never triggered. I have also tried setting the dataTransfer.dropEffect property, which has no effect.

use yew::prelude::*;
use web_sys::{DragEvent, console::log_1};

#[function_component(App)]
pub fn app() -> Html {
    let ondragenter = Callback::from(|e: DragEvent| {
        e.prevent_default();
        e.data_transfer().unwrap().set_drop_effect("move"); // optional
        log_1(&"enter".into());
    });

    let ondragover = Callback::from(|e: DragEvent| {
        e.prevent_default();
        log_1(&"over".into());
    });

    let ondrop = Callback::from(|e: DragEvent| {
        log_1(&"drop".into());
    });

    html! {

    }
}
```

with web_sys's DragEvent and DataTransfer features enabled.

I am running this using Tauri and have tried with Yew v. 0.19 and 0.20.

Title: Drag and drop in Tauri + Yew

Body:
I am having issues with handling drag and drop. I prevent_default on my drop target for both the dragEnter and dragOver events, which I can verify are firing, but the drop event is never triggered. I have also tried setting the dataTransfer.dropEffect property, which has no effect.

use yew::prelude::*;
use web_sys::{DragEvent, console::log_1};

#[function_component(App)]
pub fn app() -> Html {
    let ondragenter = Callback::from(|e: DragEvent| {
        e.prevent_default();
        e.data_transfer().unwrap().set_drop_effect("move"); // optional
        log_1(&"enter".into());
    });

    let ondragover = Callback::from(|e: DragEvent| {
        e.prevent_default();
        log_1(&"over".into());
    });

    let ondrop = Callback::from(|e: DragEvent| {
        log_1(&"drop".into());
    });

    html! {

    }
}

with web_sys's DragEvent and DataTransfer features enabled.

I am running this using Tauri and have tried with Yew v. 0.19 and 0.20.


问:
Show Json Node whose value is null Conditionally
I have a DTO which is returned as json  in a rest api which looks like

```<code>   public class Pojo{

    @JsonInclude(Include.NON_NULL)
    private String encryptedString;

    @JsonInclude(Include.NON_NULL)
    private String normalString;

    }
</code>```

In Some cases i may  get  both  encryptedString and  normalString   as null and by using  @JsonInclude(Include.NON_NULL),i wont get these two  json nodes from api.My Requirements is that based on a condition i need to return either of these String with value as null from the api. For Example,  Based on a boolean variable  isEncrypted which is coming from user input , i need to return either of one variable as json node i.e If isEncrypted is true,the expected output is
{"encryptedString" :null} . If isEncrypted is false,the expected output is
{"normalString" :null} .

Body:
I have a DTO which is returned as json  in a rest api which looks like

   public class Pojo{

    @JsonInclude(Include.NON_NULL)
    private String encryptedString;

    @JsonInclude(Include.NON_NULL)
    private String normalString;

    }

In Some cases i may  get  both  encryptedString and  normalString   as null and by using  @JsonInclude(Include.NON_NULL),i wont get these two  json nodes from api.My Requirements is that based on a condition i need to return either of these String with value as null from the api. For Example,  Based on a boolean variable  isEncrypted which is coming from user input , i need to return either of one variable as json node i.e If isEncrypted is true,the expected output is
{"encryptedString" :null} . If isEncrypted is false,the expected output is
{"normalString" :null} .


问:
ASP.NET Core API - Returning large data causes System.OutOfMemoryException - Do I need to use a stream?
I'm trying to return large amounts of data from a Web API without pagination in this controller method:

```<code>[HttpPost]
public async Task<IActionResult> GetFilteredLocations([FromBody] LocationReportQueryDto locationReportQuery, CancellationToken token = default)
{
    var result = await locationReportDataAccess.GetFilteredLocationsAsync(locationReportQuery, token);
    return Ok(result);
}
</code>```

results count can be 277,000+ items.

Client side:

```<code>public async Task<List<LocationDto>> GetFilteredLocationsAsync(LocationReportQueryDto locationReportQuery, CancellationToken token = default)
{
    var httpClient = httpClientFactory.CreateClient("Data");
    var response = await httpClient.PostAsJsonAsync("/reports/GetFilteredLocations", locationReportQuery, token);
    response.EnsureSuccessStatusCode();
    var list = await response.Content.ReadFromJsonAsync<List<LocationDto>>(cancellationToken: token);
    if (list == null) throw new HttpRequestException("HTTP Call - Response is null");
    return list;
}
</code>```

I'm getting this exception:

```<code>[2022-12-16T17:27:41.154Z] Error: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.IO.MemoryStream.set_Capacity(Int32 value)
   at System.IO.MemoryStream.EnsureCapacity(Int32 value)
   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Http.HttpContent.LimitMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.MemoryStream.WriteAsync(ReadOnlyMemory`1 buffer, CancellationToken cancellationToken)
--- End of stack trace from previous location ---
   at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.CopyToAsyncCore(Stream destination, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionResponseContent.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
   at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at...
 Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
log @ blazor.server.js:1
</code>```

In my case I can't use pagination because of the legacy database I'm using, which doesn't allow querying chunks of data, so do I have to return a stream for such large data?

Body:
I'm trying to return large amounts of data from a Web API without pagination in this controller method:

[HttpPost]
public async Task<IActionResult> GetFilteredLocations([FromBody] LocationReportQueryDto locationReportQuery, CancellationToken token = default)
{
    var result = await locationReportDataAccess.GetFilteredLocationsAsync(locationReportQuery, token);
    return Ok(result);
}

results count can be 277,000+ items.

Client side:

public async Task<List<LocationDto>> GetFilteredLocationsAsync(LocationReportQueryDto locationReportQuery, CancellationToken token = default)
{
    var httpClient = httpClientFactory.CreateClient("Data");
    var response = await httpClient.PostAsJsonAsync("/reports/GetFilteredLocations", locationReportQuery, token);
    response.EnsureSuccessStatusCode();
    var list = await response.Content.ReadFromJsonAsync<List<LocationDto>>(cancellationToken: token);
    if (list == null) throw new HttpRequestException("HTTP Call - Response is null");
    return list;
}

I'm getting this exception:

[2022-12-16T17:27:41.154Z] Error: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.IO.MemoryStream.set_Capacity(Int32 value)
   at System.IO.MemoryStream.EnsureCapacity(Int32 value)
   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Http.HttpContent.LimitMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.MemoryStream.WriteAsync(ReadOnlyMemory`1 buffer, CancellationToken cancellationToken)
--- End of stack trace from previous location ---
   at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.CopyToAsyncCore(Stream destination, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionResponseContent.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
   at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at...
 Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
log @ blazor.server.js:1

In my case I can't use pagination because of the legacy database I'm using, which doesn't allow querying chunks of data, so do I have to return a stream for such large data?


问:
How write testcase mouseover and mouseleave with both event.target.innerHTML and if condition
Write the testcase for both mouseover and mouseleave. If i try to pass the mouse event in the function parameter as "function($event)". I can't pass the if loop condition in the code coverage. Please help me out solve the problem.

HTML

```<code><li class="dropdown-item option-value" (mouseleave)="onMouseOut($event)"
                    (mouseover)="onMouseOver($event)" *ngFor="let value of pageDividerActionOption">
</code>```

Ts both mouse over and mouse out function is here.

```<code> onMouseOut(event): void {
    this.pageDividerActionOption.forEach(element => {
      if (event.target.innerText === element.option) {
        this.pageActionSubOption = [];
      }
    })
  }

  onMouseOver(event): void {

    this.pageDividerActionOption.forEach(element => {

      if (event.target.innerText === element.option) {
        this.pageActionSubOption = [];
        this.mouseOverValue = event.target.innerText;
        this.pageActionSubOptionValue = this.value.filter(action => action.optionList !== 0 && action.option === this.mouseOverValue);
       console.log(this.pageActionSubOptionValue);
        this.pageActionSubOption = this.pageActionSubOptionValue.reduce((acc, { optionList }) => (

          [...acc, ...optionList]

        ), []);
      }
    });

  }
</code>```

Test cases

```<code>it('On mouse over show the state change list', fakeAsync(() => {
    const data = { target: { innerText: 'Change State' }};
    const div = fixture.debugElement.query(By.css('.option-value'));
    let event = new MouseEvent('mouseover', {
        bubbles: true,
        cancelable: true,
        view: window,
    });
    div.nativeElement.dispatchEvent(event);
    tick();
    fixture.detectChanges();
    spyOn(component, 'onMouseOver') // spy first
    component.onMouseOver(data)
    expect(component.onMouseOver).toBeTruthy();;
}));
it(' mouse leave hide the suboption list', fakeAsync(() => {
  const data = { target: { innerText: 'Change State' }};
  const div = fixture.debugElement.query(By.css('.option-value'));
  let event = new MouseEvent('mouseleave', {
      bubbles: true,
      cancelable: true,
      view: window
  });
  div.nativeElement.dispatchEvent(event);
  tick();
  fixture.detectChanges();
  spyOn(component, 'onMouseOut') // spy first
component.onMouseOut(data)

  expect(component.onMouseOut).toBeTruthy();
}));
</code>```

Body:
Write the testcase for both mouseover and mouseleave. If i try to pass the mouse event in the function parameter as "function($event)". I can't pass the if loop condition in the code coverage. Please help me out solve the problem.

HTML

Ts both mouse over and mouse out function is here.

 onMouseOut(event): void {
    this.pageDividerActionOption.forEach(element => {
      if (event.target.innerText === element.option) {
        this.pageActionSubOption = [];
      }
    })
  }

  onMouseOver(event): void {

    this.pageDividerActionOption.forEach(element => {

      if (event.target.innerText === element.option) {
        this.pageActionSubOption = [];
        this.mouseOverValue = event.target.innerText;
        this.pageActionSubOptionValue = this.value.filter(action => action.optionList !== 0 && action.option === this.mouseOverValue);
       console.log(this.pageActionSubOptionValue);
        this.pageActionSubOption = this.pageActionSubOptionValue.reduce((acc, { optionList }) => (

          [...acc, ...optionList]

        ), []);
      }
    });

  }

Test cases

it('On mouse over show the state change list', fakeAsync(() => {
    const data = { target: { innerText: 'Change State' }};
    const div = fixture.debugElement.query(By.css('.option-value'));
    let event = new MouseEvent('mouseover', {
        bubbles: true,
        cancelable: true,
        view: window,
    });
    div.nativeElement.dispatchEvent(event);
    tick();
    fixture.detectChanges();
    spyOn(component, 'onMouseOver') // spy first
    component.onMouseOver(data)
    expect(component.onMouseOver).toBeTruthy();;
}));
it(' mouse leave hide the suboption list', fakeAsync(() => {
  const data = { target: { innerText: 'Change State' }};
  const div = fixture.debugElement.query(By.css('.option-value'));
  let event = new MouseEvent('mouseleave', {
      bubbles: true,
      cancelable: true,
      view: window
  });
  div.nativeElement.dispatchEvent(event);
  tick();
  fixture.detectChanges();
  spyOn(component, 'onMouseOut') // spy first
component.onMouseOut(data)

  expect(component.onMouseOut).toBeTruthy();
}));


问:
Node Worker thread is not working inside api call
I am using node version 16 and following all documented steps. Still worker thread is not working.

`

```<code>const addPaymentApi = async (req) => {
    const { payload, adminId } = req.body;
    logInfo(`Request to Create payment!`, {
        adminId
    });

    const createPaymentResponse = await composeResult(
        (response) => {
            const worker = new Worker("../workers/bulk-add-payment-api.worker.js");
            worker.on("message", (data) => {
                //update response table
            })
            return Result.Ok(response);
        },
        () => db.create(new CreateBulkUploadResponse(adminId))
    )({ payload, adminId });
    return respond(
        createPaymentResponse,
        `Payments processed Sucessfully!`,
        `Not Able to process payments!`,
    );
}
</code>```

Code inside worker file is not getting executed

I tried every possible solution. I want to create a worker thread and perform CPU extensive task.

Body:
I am using node version 16 and following all documented steps. Still worker thread is not working.

`

const addPaymentApi = async (req) => {
    const { payload, adminId } = req.body;
    logInfo(`Request to Create payment!`, {
        adminId
    });

    const createPaymentResponse = await composeResult(
        (response) => {
            const worker = new Worker("../workers/bulk-add-payment-api.worker.js");
            worker.on("message", (data) => {
                //update response table
            })
            return Result.Ok(response);
        },
        () => db.create(new CreateBulkUploadResponse(adminId))
    )({ payload, adminId });
    return respond(
        createPaymentResponse,
        `Payments processed Sucessfully!`,
        `Not Able to process payments!`,
    );
}

Code inside worker file is not getting executed

I tried every possible solution. I want to create a worker thread and perform CPU extensive task.


问:
Error "invalid_grant" after using msal token from msal-react
I need your help with an unreachable error when msal token expire, specifically an invalid_grant error. I have a exception but this error only is showing on console. Thanks you

```<code>const refreshToken = async () => {
    const request = {
      account: account,
      scopes: ["https://graph.microsoft.com/User.Read"],
    };
    try {
      const response = await instance.acquireTokenSilent(request);
      localStorage.setItem("accessToken", response.accessToken);
      setToken(response.accessToken);
    } catch (e) {
      console.log(e);
      const isServerError = e instanceof ServerError;
      const isInteractionRequiredError = e instanceof InteractionRequiredAuthError;
      const isInvalidGrantError = (e.errorCode === "invalid_grant");
      if (isInteractionRequiredError) {
        try {
          const response = await instance.acquireTokenRedirect(request);
          localStorage.setItem("accessToken", response.accessToken);
          setToken(response.accessToken);
          return;
        } catch (e) {
          console.log("InteractionRequiredAuthError:" + e);
          handleError(e);
        }
      }
      if (isServerError && isInvalidGrantError && !isInteractionRequiredError) {
        localStorage.clear();
        window.location.reload();
      }
    }
  };
</code>```

I tried to catch that error but it was not possible

Body:
I need your help with an unreachable error when msal token expire, specifically an invalid_grant error. I have a exception but this error only is showing on console. Thanks you

const refreshToken = async () => {
    const request = {
      account: account,
      scopes: ["https://graph.microsoft.com/User.Read"],
    };
    try {
      const response = await instance.acquireTokenSilent(request);
      localStorage.setItem("accessToken", response.accessToken);
      setToken(response.accessToken);
    } catch (e) {
      console.log(e);
      const isServerError = e instanceof ServerError;
      const isInteractionRequiredError = e instanceof InteractionRequiredAuthError;
      const isInvalidGrantError = (e.errorCode === "invalid_grant");
      if (isInteractionRequiredError) {
        try {
          const response = await instance.acquireTokenRedirect(request);
          localStorage.setItem("accessToken", response.accessToken);
          setToken(response.accessToken);
          return;
        } catch (e) {
          console.log("InteractionRequiredAuthError:" + e);
          handleError(e);
        }
      }
      if (isServerError && isInvalidGrantError && !isInteractionRequiredError) {
        localStorage.clear();
        window.location.reload();
      }
    }
  };

I tried to catch that error but it was not possible


问:
Data structure that shares nodes with an existing tree
Basically, if I remember correctly, it's a tree. Then, if you apply a transformation on the tree, the unchanged nodes are shared, and new ones are created.

However, due to the way it is made, one can still access the data before each transformation, and so with the least memory used.

I think this is applicable in a context like git, and I specifically remember that git was the example used for this structure, but I can't seem to remember its name. Anyone help?

I've tried searching for tree variants, and I just can't seem to find it.


问:
How to insert bidirectional many to many relationship after persisting data hibernate and springboot
i'm trying to insert a bidirectional relationship, after persisting data. I'm fighting with hibernate trying to solve this problem. What i'd like to happen is, after persisting the data, update, (when needed) adding an item to the relationship and update all the connected data. For example: i'm creating an activity, the activity is persisted to the database and it's ok. I'm creating a customer, the customer is persisted to the database and it's ok. After this, if the customer would like to partecipate in the activity i've to add this relationship in the database using a third table (activities_customers) and updating their lists (customersInThisActivity and bookedActivities (you can find them below)). I've tried many ways, always failing (hibernate gives me detached entity passed to persist, lazyinitializationexception ecc) So can someone please help me, with this problem? Thanks.. Here my classes and the test that should pass. I'm using H2 as DB

Activity.java

```<code>@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
public class Activity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "activity_id")
    @SequenceGenerator(name = "activity_id", sequenceName = "activity_id", allocationSize = 1)
    private Long id;

    @Column
    private String info;

    @Column
    private LocalDate activityBeginDate;

    @Column
    private LocalDate activityEndDate;

    @Column
    private int maxNumberOfPeople;

    @ManyToMany
    @JoinTable(
            name = "ACTIVITIES_CUSTOMERS",
            joinColumns = @JoinColumn(name = "ACTIVITY_ID"),
            inverseJoinColumns = @JoinColumn(name = "CUSTOMER_ID"))
    Set<Customer> customersInThisActivity = new HashSet<>();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Activity activity = (Activity) o;
        return maxNumberOfPeople == activity.maxNumberOfPeople && id.equals(activity.id) && info.equals(activity.info) && activityBeginDate.equals(activity.activityBeginDate) && activityEndDate.equals(activity.activityEndDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, info, activityBeginDate, activityEndDate, maxNumberOfPeople);
    }
</code>```

Customer.java

```<code>@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_id")
    @SequenceGenerator(name = "customer_id", sequenceName = "customer_id", allocationSize = 1)
    private Long id;

    @Column
    private String firstName;

    @Column
    private String lastName;

    @Column
    private String email;

    @ManyToMany(mappedBy = "customersInThisActivity")
    Set<Activity> bookedActivities = new HashSet<>();
</code>```

ActivityManager.java

```<code>@Service
public class ActivityManager {

    @PersistenceContext
    private EntityManager entityManager;

    public List<Activity> getActivities() {
        return this.entityManager.createQuery("SELECT a from Activity a", Activity.class).getResultList();
    }

    @Transactional
    public void saveActivity(Activity activity) {
        this.entityManager.persist(activity);
    }

    @Transactional
    public void addParticipant(Activity activity, Customer customer) {
        //ADD CUSTOMER TO ACTIVITY
        //ADD ACTIVITY TO CUSTOMER (TO HAVE CONSISTENT DATA)
        //PERSIST ALL THE ENTITIES
    }
}
</code>```

The test that should pass

```<code>@SpringBootTest
class CasottoApplicationTests {

   private final ActivityManager activityManager;

   private final CustomerManager customerManager;

   @Autowired
   public CasottoApplicationTests(ActivityManager activityManager, CustomerManager customerManager) {
      this.activityManager = activityManager;
      this.customerManager = customerManager;
   }

   @Test
   void testCasotto() {
      Activity a = new Activity();
      a.setInfo("INFO");
      a.setActivityBeginDate(LocalDate.now());
      a.setActivityEndDate(LocalDate.now());
      a.setMaxNumberOfPeople(-1);
      activityManager.saveActivity(a);
      Customer c = new Customer();
      c.setEmail("TEST@TEST.COM");
      c.setFirstName("TEST");
      c.setLastName("TEST");
      customerManager.saveCustomer(c);
      activityManager.addParticipant(a, c);
      Assertions.assertEquals(1, a.getCustomersInThisActivity().size());
      Assertions.assertEquals(1, c.getBookedActivities().size());
   }

}
</code>```

Thanks in advance.

Body:
i'm trying to insert a bidirectional relationship, after persisting data. I'm fighting with hibernate trying to solve this problem. What i'd like to happen is, after persisting the data, update, (when needed) adding an item to the relationship and update all the connected data. For example: i'm creating an activity, the activity is persisted to the database and it's ok. I'm creating a customer, the customer is persisted to the database and it's ok. After this, if the customer would like to partecipate in the activity i've to add this relationship in the database using a third table (activities_customers) and updating their lists (customersInThisActivity and bookedActivities (you can find them below)). I've tried many ways, always failing (hibernate gives me detached entity passed to persist, lazyinitializationexception ecc) So can someone please help me, with this problem? Thanks.. Here my classes and the test that should pass. I'm using H2 as DB

Activity.java

@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
public class Activity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "activity_id")
    @SequenceGenerator(name = "activity_id", sequenceName = "activity_id", allocationSize = 1)
    private Long id;

    @Column
    private String info;

    @Column
    private LocalDate activityBeginDate;

    @Column
    private LocalDate activityEndDate;

    @Column
    private int maxNumberOfPeople;

    @ManyToMany
    @JoinTable(
            name = "ACTIVITIES_CUSTOMERS",
            joinColumns = @JoinColumn(name = "ACTIVITY_ID"),
            inverseJoinColumns = @JoinColumn(name = "CUSTOMER_ID"))
    Set<Customer> customersInThisActivity = new HashSet<>();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Activity activity = (Activity) o;
        return maxNumberOfPeople == activity.maxNumberOfPeople && id.equals(activity.id) && info.equals(activity.info) && activityBeginDate.equals(activity.activityBeginDate) && activityEndDate.equals(activity.activityEndDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, info, activityBeginDate, activityEndDate, maxNumberOfPeople);
    }

Customer.java

@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_id")
    @SequenceGenerator(name = "customer_id", sequenceName = "customer_id", allocationSize = 1)
    private Long id;

    @Column
    private String firstName;

    @Column
    private String lastName;

    @Column
    private String email;

    @ManyToMany(mappedBy = "customersInThisActivity")
    Set<Activity> bookedActivities = new HashSet<>();

ActivityManager.java

@Service
public class ActivityManager {

    @PersistenceContext
    private EntityManager entityManager;

    public List<Activity> getActivities() {
        return this.entityManager.createQuery("SELECT a from Activity a", Activity.class).getResultList();
    }

    @Transactional
    public void saveActivity(Activity activity) {
        this.entityManager.persist(activity);
    }

    @Transactional
    public void addParticipant(Activity activity, Customer customer) {
        //ADD CUSTOMER TO ACTIVITY
        //ADD ACTIVITY TO CUSTOMER (TO HAVE CONSISTENT DATA)
        //PERSIST ALL THE ENTITIES
    }
}

The test that should pass

@SpringBootTest
class CasottoApplicationTests {

   private final ActivityManager activityManager;

   private final CustomerManager customerManager;

   @Autowired
   public CasottoApplicationTests(ActivityManager activityManager, CustomerManager customerManager) {
      this.activityManager = activityManager;
      this.customerManager = customerManager;
   }

   @Test
   void testCasotto() {
      Activity a = new Activity();
      a.setInfo("INFO");
      a.setActivityBeginDate(LocalDate.now());
      a.setActivityEndDate(LocalDate.now());
      a.setMaxNumberOfPeople(-1);
      activityManager.saveActivity(a);
      Customer c = new Customer();
      c.setEmail("TEST@TEST.COM");
      c.setFirstName("TEST");
      c.setLastName("TEST");
      customerManager.saveCustomer(c);
      activityManager.addParticipant(a, c);
      Assertions.assertEquals(1, a.getCustomersInThisActivity().size());
      Assertions.assertEquals(1, c.getBookedActivities().size());
   }

}

Thanks in advance.


问:
Laravel - Yajra Datatables - Ordering on custom columns
So I am using Yajra Datatables and I have a few custom columns based on relationships or the existence of work orders etc. However, because of the customization of these columns there is no way to order these columns by the query as these columns don't actually exist.

Controller:

```<code>$model = Meter::withIssues()->with(['sensor', 'utilityAccounts', 'workOrders']);
        return DataTables::of($model)
            ->addColumn('status', function (Meter $meter) {
                if (is_null($meter->failures)) {
                    return "<i class='fa fa-warning fa-lg text-yellow' style='padding-left: 4rem'>";
                } else {
                    return "<i class='fa fa-times-circle-o fa-lg text-red' style='padding-left: 4rem'>";
                }
            })
            ->addColumn('platform', function (Meter $meter) {
                return $meter->type === "Virtual" ? "Multi" : $meter->sensor->platform;
            })
            ->addColumn('utility_accounts', function (Meter $meter) {
                return $meter->utilityAccounts->pluck('utility_account')->implode('<br>');
            })
            ->addColumn('market', function (Meter $meter) {
                if ($meter->type === "Virtual") {
                    $meter = $meter->childMeters->first();
                }
                if (!isset($meter->sensor->device_data['marketRef'])) {
                    return 'Unknown';
                }
                $marketRef = explode(' ', $meter->sensor->device_data['marketRef']);
                $marketRef = array_pop($marketRef);
                return $marketRef;
            })
            ->addColumn('account_status', function (Meter $meter) {
                return $meter->crmAccount->customFields->acct_status_c ?? 'Unknown';
            })
            ->addColumn('has_open_work_order', function (Meter $meter) {
                return [
                    'display' => $meter->has_open_work_orders ? '<span data-order="1">Yes</span>' : '<span data-order="0">No</span>',
                    'sort_by' => $meter->has_open_work_orders ? 1 : 0
                 ];
            })
            ->rawColumns(['status', 'utility_accounts', 'has_open_work_order.display'])
            ->toJson();
</code>```

JavaScript:

```<code>{
                    data: 'id',
                    render: function ( data, type, row ) {
                        var button = `
                        <button
                            type="button"
                            class="btn btn-default btn-sm dtMeterHealthCheckIssues-modal"
                            dt-record="`+data+`"
                            data-toggle="modal"
                            data-target="#modalClearIssues"
                            data-url="{{ url('meter-health/meter-health-check-issues/edit/`+data+`') }}">

                            <span class="text-primary" data-toggle="tooltip" data-title="View/Clear Issues" data-original-title="" title="">
                                <i class="fa fa-wrench fa-lg fa-fw" style="margin-top:5px; margin-bottom:5px"></i>
                            </span>

                        </button>`
                        return button;
                    },
                },
                { data: 'id' },
                { data: 'status' },
                { data: 'type'},
                { data: 'platform' },
                { data: 'account_name' },
                { data: 'facility_id' },
                { data: 'utility_accounts' },
                { data: 'market' },
                { data: 'account_status' },
                {
                    data: 'has_open_work_order',
                    render: {
                        _: 'display',
                        sort: 'sort_by'
                    }
                }
</code>```

As you can see I already tried a solution where i gave two responses back for "has_open_work_order" and sort by the easier number. No luck. It's doing the sorting on the backend and the only thing Yajra lets me do is customze the Eloquent query to add order by which doesn't work. I have seen a few questions elsewhere but with no answers. Let me know if you need any other information. Thanks!

Body:
So I am using Yajra Datatables and I have a few custom columns based on relationships or the existence of work orders etc. However, because of the customization of these columns there is no way to order these columns by the query as these columns don't actually exist.

Controller:

$model = Meter::withIssues()->with(['sensor', 'utilityAccounts', 'workOrders']);
        return DataTables::of($model)
            ->addColumn('status', function (Meter $meter) {
                if (is_null($meter->failures)) {
                    return "";
                } else {
                    return "";
                }
            })
            ->addColumn('platform', function (Meter $meter) {
                return $meter->type === "Virtual" ? "Multi" : $meter->sensor->platform;
            })
            ->addColumn('utility_accounts', function (Meter $meter) {
                return $meter->utilityAccounts->pluck('utility_account')->implode('
');
            })
            ->addColumn('market', function (Meter $meter) {
                if ($meter->type === "Virtual") {
                    $meter = $meter->childMeters->first();
                }
                if (!isset($meter->sensor->device_data['marketRef'])) {
                    return 'Unknown';
                }
                $marketRef = explode(' ', $meter->sensor->device_data['marketRef']);
                $marketRef = array_pop($marketRef);
                return $marketRef;
            })
            ->addColumn('account_status', function (Meter $meter) {
                return $meter->crmAccount->customFields->acct_status_c ?? 'Unknown';
            })
            ->addColumn('has_open_work_order', function (Meter $meter) {
                return [
                    'display' => $meter->has_open_work_orders ? 'Yes' : 'No',
                    'sort_by' => $meter->has_open_work_orders ? 1 : 0
                 ];
            })
            ->rawColumns(['status', 'utility_accounts', 'has_open_work_order.display'])
            ->toJson();

JavaScript:

{
                    data: 'id',
                    render: function ( data, type, row ) {
                        var button = `
                        <button
                            type="button"
                            class="btn btn-default btn-sm dtMeterHealthCheckIssues-modal"
                            dt-record="`+data+`"
                            data-toggle="modal"
                            data-target="#modalClearIssues"
                            data-url="{{ url('meter-health/meter-health-check-issues/edit/`+data+`') }}">

                        </button>`
                        return button;
                    },
                },
                { data: 'id' },
                { data: 'status' },
                { data: 'type'},
                { data: 'platform' },
                { data: 'account_name' },
                { data: 'facility_id' },
                { data: 'utility_accounts' },
                { data: 'market' },
                { data: 'account_status' },
                {
                    data: 'has_open_work_order',
                    render: {
                        _: 'display',
                        sort: 'sort_by'
                    }
                }

As you can see I already tried a solution where i gave two responses back for "has_open_work_order" and sort by the easier number. No luck. It's doing the sorting on the backend and the only thing Yajra lets me do is customze the Eloquent query to add order by which doesn't work. I have seen a few questions elsewhere but with no answers. Let me know if you need any other information. Thanks!