问:
C++ File (Ifstream) will not open
When file is checked if its open, it will not open.

The file doesn't open when ran, as it says "Unable to open file" based on my test cases. Is there anyway to fix this?

Is there something I need to fix with the file io function (which I created at the bottom) or something to do inside of the if statement (checking if its open)

```<code>#include "header.hpp"
int main() {
  string infile, outfile;
  print();
  readFilenames(infile, outfile);
  ifstream fin(infile.c_str());
  // check if file can be opened
  fin.open(infile);
  if (fin.is_open())
  {
    string name, smallName = "", largeName = "";
    int id, numPeople = 0, smallId, largeId;
    double balance, totalBalance = 0, largeBalance, smallBalance;
    cout << "\n\nReading records from input file " << infile << endl;
    cout << "Output records to output file " << outfile << endl;
    ofstream fout(outfile.c_str());
    print(fout);
    fout << "List of Entries : " << endl;
    printHeading(fout);
    // read till the end of file
    while (!fin.eof())
    {
      numPeople++;
      getline(fin, name); // read name
      name = name.substr(0, name.length() - 1); // remove '\n' from the end of name
      // read id and balance
      fin >> id >> balance;
      }
  } else
    cout << "Unable to open file : " << infile << endl;
  cout << "\nThank you for using my program";
  return 0;
}

void readFilenames(string &infile, string &outfile)
{
  cout << "What input file would you like to use? ";
  getline(cin, infile);
  infile = infile.substr(0, infile.length() - 1);
  cout << "What output file would you like to use? ";
  getline(cin, outfile);
  outfile = outfile.substr(0, outfile.length() - 1);
}
</code>```

Title: C++ File (Ifstream) will not open

Body:
When file is checked if its open, it will not open.

The file doesn't open when ran, as it says "Unable to open file" based on my test cases. Is there anyway to fix this?

Is there something I need to fix with the file io function (which I created at the bottom) or something to do inside of the if statement (checking if its open)

#include "header.hpp"
int main() {
  string infile, outfile;
  print();
  readFilenames(infile, outfile);
  ifstream fin(infile.c_str());
  // check if file can be opened
  fin.open(infile);
  if (fin.is_open())
  {
    string name, smallName = "", largeName = "";
    int id, numPeople = 0, smallId, largeId;
    double balance, totalBalance = 0, largeBalance, smallBalance;
    cout << "\n\nReading records from input file " << infile << endl;
    cout << "Output records to output file " << outfile << endl;
    ofstream fout(outfile.c_str());
    print(fout);
    fout << "List of Entries : " << endl;
    printHeading(fout);
    // read till the end of file
    while (!fin.eof())
    {
      numPeople++;
      getline(fin, name); // read name
      name = name.substr(0, name.length() - 1); // remove '\n' from the end of name
      // read id and balance
      fin >> id >> balance;
      }
  } else
    cout << "Unable to open file : " << infile << endl;
  cout << "\nThank you for using my program";
  return 0;
}

void readFilenames(string &infile, string &outfile)
{
  cout << "What input file would you like to use? ";
  getline(cin, infile);
  infile = infile.substr(0, infile.length() - 1);
  cout << "What output file would you like to use? ";
  getline(cin, outfile);
  outfile = outfile.substr(0, outfile.length() - 1);
}


来源: stackexchange

问:
Angular: Property matCellDefOf is not provided by any applicable directive on an embedded template
I'm trying to use Mat table from Angular Material, so the console shows an error as you see in this picture:

Error

The codes are:

```<code><ng-container matColumnDef="actions">
                    <th mat-header-cell *matHeaderCellDef>{{ "PROD_REPORT.ACTIONS" | translate }}</th>
                    <td
                        mat-cell
                        *matCellDef="let row of element; index as i"
                        style="padding-right: 0"
                        [class.active-tr]="lastClickedProduct?.uuid == row.uuid"
                    >
                        <button (click)="onClickProduct(row)" mat-icon-button>
                            <mat-icon>remove_red_eye</mat-icon>
                        </button>
                        <a class="org-description" (click)="onClickPdf(row.uuid)" ariaCurrentWhenActive="page">
                            <button mat-icon-button>
                                <mat-icon>picture_as_pdf</mat-icon>
                            </button>
                        </a>
                    </td>
                </ng-container>
</code>```

Here are the image of the codes:

Codes

!Also:
Although it stated that there was an error in the element part, I could not find how the solution was.

```<code>                   <td
                        mat-cell
                        *matCellDef="let row of element; index as i"
                        style="padding-right: 0"
                        [class.active-tr]="lastClickedProduct?.uuid == row.uuid"
                    >
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use Mat table from Angular Material, so the console shows an error as you see in this picture:

Error

The codes are:

<ng-container matColumnDef="actions">
                    {{ "PROD_REPORT.ACTIONS" | translate }}

                        <button (click)="onClickProduct(row)" mat-icon-button>
                            <mat-icon>remove_red_eye</mat-icon>
                        </button>

                            <button mat-icon-button>
                                <mat-icon>picture_as_pdf</mat-icon>
                            </button>

                </ng-container>

Here are the image of the codes:

Codes

!Also:
Although it stated that there was an error in the element part, I could not find how the solution was.


问:
SizeAndTimeBasedRollingPolicy not honoring maxFileSize
I am working on a spring boot application and I have the following settings

```<code>    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
        <fileNamePattern>${LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}</fileNamePattern>
        <cleanHistoryOnStart>${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}</cleanHistoryOnStart>
        <maxFileSize>${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE:-10MB}</maxFileSize>
        <totalSizeCap>${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP:-0}</totalSizeCap>
        <maxHistory>${LOGBACK_ROLLINGPOLICY_MAX_HISTORY:-7}</maxHistory>
    </rollingPolicy>
</code>```

When I try to add the following to my application.yaml,

```<code>logging:
  logback:
    rollingpolicy:
      max-file-size: 5MB
</code>```

these settings are not picked up. It still uses the default 10MB

Body:
I am working on a spring boot application and I have the following settings

    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
        <fileNamePattern>${LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}</fileNamePattern>
        <cleanHistoryOnStart>${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}</cleanHistoryOnStart>
        <maxFileSize>${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE:-10MB}</maxFileSize>
        <totalSizeCap>${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP:-0}</totalSizeCap>
        <maxHistory>${LOGBACK_ROLLINGPOLICY_MAX_HISTORY:-7}</maxHistory>
    </rollingPolicy>

When I try to add the following to my application.yaml,

logging:
  logback:
    rollingpolicy:
      max-file-size: 5MB

these settings are not picked up. It still uses the default 10MB


问:
Hi, I have a question regarding classes and constructors
```<code>class Stack {
    private:
    int stackstore[100];
    int SP;
    public:
        Stack(void) { SP = 0; }
    void push(int value);
    int pop(void) {
         return stackstore[--SP];
     }
};

void Stack::push(int value) {
    stackstore[SP++] = value;
}
</code>```

In this case I want to understand what difference it makes initializing SP in the constructor to  doing it directly when declaring the variable. Why is it a better practice to do it the way depicted above rather than this way (without the constructor) ->:

```<code>class Stack {
    private:
    int stackstore[100];
    int SP = 0;
    public:

    void push(int value);
    int pop(void) {
         return stackstore[--SP];
     }
};

void Stack::push(int value) {
    stackstore[SP++] = value;
}
</code>```

Thank you in advance for any help :)

Body:
class Stack {
    private:
    int stackstore[100];
    int SP;
    public:
        Stack(void) { SP = 0; }
    void push(int value);
    int pop(void) {
         return stackstore[--SP];
     }
};

void Stack::push(int value) {
    stackstore[SP++] = value;
}

In this case I want to understand what difference it makes initializing SP in the constructor to  doing it directly when declaring the variable. Why is it a better practice to do it the way depicted above rather than this way (without the constructor) ->:

class Stack {
    private:
    int stackstore[100];
    int SP = 0;
    public:

    void push(int value);
    int pop(void) {
         return stackstore[--SP];
     }
};

void Stack::push(int value) {
    stackstore[SP++] = value;
}

Thank you in advance for any help :)


问:
Google Cloud Speech-to-Text Api - Convert json format in plain text w/o variables
I used the Google Cloud Speech-to-Text API to convert audio files (interviews) to text. This worked quite well, though I struggle with the json output.

Since I only need the transcript result ("Okay, I'm going to read you, the opening question."), I wonder if there is an easy way to delete the variables: "words", "endTime", "startTime" and "word"?

Does anyone know an easy way to do it? Maybe in python?

"results": [ {
    "alternatives": [ {
      "transcript": "Okay, I'm going to read you, the opening question.",
      "words": [ {
        "endTime": "1.800s",
        "startTime": "1.300s",
        "word": "Okay,"
      }, {
        "endTime": "2.800s",
        "startTime": "1.800s",
        "word": "I'm"
      }, {
        "endTime": "3s",
        "startTime": "2.800s",
        "word": "going"
      }, {
        "endTime": "3.100s",
        "startTime": "3s",
        "word": "to"
      }, {
        "endTime": "3.300s",
        "startTime": "3.100s",
        "word": "read"
      }, {
        "endTime": "4.300s",
        "startTime": "3.300s",
        "word": "you"
      }, {
        "endTime": "4.400s",
        "startTime": "4.300s",
        "word": "the"
      }, {
        "endTime": "6s",
        "startTime": "4.400s",
        "word": "opening"
      }, {
        "endTime": "6.200s",
        "startTime": "6s",
        "word": "question."

```

Thanks in advance,
Matt

I did not find any solution, since I have very less experience in data formatting.

Body:
I used the Google Cloud Speech-to-Text API to convert audio files (interviews) to text. This worked quite well, though I struggle with the json output.

Since I only need the transcript result ("Okay, I'm going to read you, the opening question."), I wonder if there is an easy way to delete the variables: "words", "endTime", "startTime" and "word"?

Does anyone know an easy way to do it? Maybe in python?

"results": [ {
    "alternatives": [ {
      "transcript": "Okay, I'm going to read you, the opening question.",
      "words": [ {
        "endTime": "1.800s",
        "startTime": "1.300s",
        "word": "Okay,"
      }, {
        "endTime": "2.800s",
        "startTime": "1.800s",
        "word": "I'm"
      }, {
        "endTime": "3s",
        "startTime": "2.800s",
        "word": "going"
      }, {
        "endTime": "3.100s",
        "startTime": "3s",
        "word": "to"
      }, {
        "endTime": "3.300s",
        "startTime": "3.100s",
        "word": "read"
      }, {
        "endTime": "4.300s",
        "startTime": "3.300s",
        "word": "you"
      }, {
        "endTime": "4.400s",
        "startTime": "4.300s",
        "word": "the"
      }, {
        "endTime": "6s",
        "startTime": "4.400s",
        "word": "opening"
      }, {
        "endTime": "6.200s",
        "startTime": "6s",
        "word": "question."

Thanks in advance,
Matt

I did not find any solution, since I have very less experience in data formatting.


问:
cancel booking option in laravel-8 booking system
I need help adding Cancel Option for an existing booking,
I have $service, booking_code, min_before_cancel, start_date, and status.
I want to have the button active ONLY if min_before_cancel !=0 otherwise booking is non-refundable.
and the button cancel should be active still time limit (min_before_cancel) if the start_date and today = or less than min_before_cancel the button should disappear.

I have added this in the View

```<code>@if ($service =booking->service->time_before_cancel != 0 && \Carbon\Carbon::now() >$booking->start_date->subDays($service->min_before_cancel))
<button class="btn btn-danger">Cancel</button>
@endif
</code>```

and in the BookingController the following function:

```<code>public function cancel($code)
{
// Retrieve the booking from the database
$booking = Booking::find($code);

 // Update the booking status
$booking->status = 'cancelled';
$booking->save();

 // Return a success message to the user
return redirect()->back()->with('success', 'Your booking has been canceled.');
}
public function showCancelOption($bookingCode)
{
// Retrieve the booking from the database
$booking = Booking::where('booking_code', $bookingCode)->first();

// Retrieve the service associated with the booking
$service = $booking->service;

// Calculate the difference in days between the start date and today
$startDate = new Carbon($booking->start_date);
$today = Carbon::now();
$diffInDays = $startDate->diffInDays($today);

}
}
</code>```

in the Route:

```<code> Route::post('/booking/{code}/cancel', 'BookingController@cancel')->name('booking.cancel');
</code>```

and new cancel.blade under the booking folder.

Booking Modl

```<code>class Boat extends Bookable
{
use Notifiable;
use SoftDeletes;
use CapturesService;

protected $table = 'bravo_boats';
public $type = 'boat';
public $checkout_booking_detail_file       = 'Boat::frontend/booking/detail';
public $checkout_booking_detail_modal_file = 'Boat::frontend/booking/detail-modal';
public $set_paid_modal_file                = 'Boat::frontend/booking/set-paid-modal';
public $email_new_booking_file             = 'Boat::emails.new_booking_detail';
public $availabilityClass = BoatDate::class;

protected $fillable = [
    'title',
    'content',
    'category_id',
    'cancellation_id',
    'style_id',
    'capt_id',
    'health_id',
    'status',
    'manufacturer',
    'reference',
    'crew',
    'model',
    'faqs'
];
protected $slugField     = 'slug';
protected $slugFromField = 'title';
protected $seo_type = 'boat';

protected $casts = [
    'faqs'  => 'array',
    'specs'  => 'array',
    'category'=>'array',
    'cancellation'=>'array',
    'style'=>'array',
    'capt'=>'array',
    'health'=>'array',
    'extra_price'  => 'array',
    'service_fee'  => 'array',
    'price'=>'float',
    'sale_price'=>'float',
];
</code>```

Appreciate your help

Body:
I need help adding Cancel Option for an existing booking,
I have $service, booking_code, min_before_cancel, start_date, and status.
I want to have the button active ONLY if min_before_cancel !=0 otherwise booking is non-refundable.
and the button cancel should be active still time limit (min_before_cancel) if the start_date and today = or less than min_before_cancel the button should disappear.

I have added this in the View

@if ($service =booking->service->time_before_cancel != 0 && \Carbon\Carbon::now() >$booking->start_date->subDays($service->min_before_cancel))
<button class="btn btn-danger">Cancel</button>
@endif

and in the BookingController the following function:

public function cancel($code)
{
// Retrieve the booking from the database
$booking = Booking::find($code);

 // Update the booking status
$booking->status = 'cancelled';
$booking->save();

 // Return a success message to the user
return redirect()->back()->with('success', 'Your booking has been canceled.');
}
public function showCancelOption($bookingCode)
{
// Retrieve the booking from the database
$booking = Booking::where('booking_code', $bookingCode)->first();

// Retrieve the service associated with the booking
$service = $booking->service;

// Calculate the difference in days between the start date and today
$startDate = new Carbon($booking->start_date);
$today = Carbon::now();
$diffInDays = $startDate->diffInDays($today);

}
}

in the Route:

 Route::post('/booking/{code}/cancel', 'BookingController@cancel')->name('booking.cancel');

and new cancel.blade under the booking folder.

Booking Modl

class Boat extends Bookable
{
use Notifiable;
use SoftDeletes;
use CapturesService;

protected $table = 'bravo_boats';
public $type = 'boat';
public $checkout_booking_detail_file       = 'Boat::frontend/booking/detail';
public $checkout_booking_detail_modal_file = 'Boat::frontend/booking/detail-modal';
public $set_paid_modal_file                = 'Boat::frontend/booking/set-paid-modal';
public $email_new_booking_file             = 'Boat::emails.new_booking_detail';
public $availabilityClass = BoatDate::class;

protected $fillable = [
    'title',
    'content',
    'category_id',
    'cancellation_id',
    'style_id',
    'capt_id',
    'health_id',
    'status',
    'manufacturer',
    'reference',
    'crew',
    'model',
    'faqs'
];
protected $slugField     = 'slug';
protected $slugFromField = 'title';
protected $seo_type = 'boat';

protected $casts = [
    'faqs'  => 'array',
    'specs'  => 'array',
    'category'=>'array',
    'cancellation'=>'array',
    'style'=>'array',
    'capt'=>'array',
    'health'=>'array',
    'extra_price'  => 'array',
    'service_fee'  => 'array',
    'price'=>'float',
    'sale_price'=>'float',
];

Appreciate your help


问:
How to encrypt data using a key obtained from BCryptDeriveKeyPBKDF2
As I understand it, to encrypt data, you need to use the BCyptEncrypt function, but it takes BCRYPT_KEY_HANDLE hKey as a parameter, which can only be obtained from the BCryptGenerateSymmetricKey, BCryptGenerateKeyPair, or BCryptImportKey functions.
The question is how to use the BCyptEncrypt function having a key obtained through BCryptDeriveKeyPBKDF2 that does not create BCRYPT_KEY_HANDLE hKey

OwnerDisplayName: Arthur Akopiants


问:
How to handle 429 errors with fetch
I am trying to retrieve data from my own rest api. On the backend side I have express-rate-limit in use. Now I am trying to handle 429 error when it occurs. I want to display something to the user like "

```<code>Too many requests, please try again later.
</code>```

How can I read the statusText of the error?

```<code>    try {
        const data = await fetch("http://localhost:5000/login", {
            method: "POST",
            body: JSON.stringify(
                {
                    email
                    password
                }
            ),
            headers: {
                "Accept": "application/json",
                'Content-Type': 'application/json'
            }
        })

        const result = await data.json()

        if (data.status !== 200) {
            throw new Error(result.detail.message)
        }

        console.log(result)
    } catch (e) {
        console.log(e) //shows: There was an error SyntaxError
    }
</code>```

Title: How to handle 429 errors with fetch

Body:
I am trying to retrieve data from my own rest api. On the backend side I have express-rate-limit in use. Now I am trying to handle 429 error when it occurs. I want to display something to the user like "

Too many requests, please try again later.

How can I read the statusText of the error?

    try {
        const data = await fetch("http://localhost:5000/login", {
            method: "POST",
            body: JSON.stringify(
                {
                    email
                    password
                }
            ),
            headers: {
                "Accept": "application/json",
                'Content-Type': 'application/json'
            }
        })

        const result = await data.json()

        if (data.status !== 200) {
            throw new Error(result.detail.message)
        }

        console.log(result)
    } catch (e) {
        console.log(e) //shows: There was an error SyntaxError
    }


问:
Discord bot making queue run into voice_client being a static global tuple
So I wrote the code for a queue and it refuses to work tells me 'tuple' object has no atrribute 'play' I asked around and someone told me

"voice_client is just a static global tuple that never gets changed. Consider using a botvar here if you want something shared between function" sorry if i'm being dumb but what is a botvar how do I use it and is there any other way I can make a queue that won't need me all this hassle?

Here's my code

```<code>import discord
from discord.ext import commands as disect
import asyncio
from youtube_dl import YoutubeDL
import random

Prefix = "-"
bot = disect.Bot(command_prefix=Prefix, intents=discord.Intents.all(), case_insensitive=True, self_bot=False)
voice_clients = {}
queue = []
voice_client = ()

def Convert(string):
    li = list(string.split(" "))
    return li

ytdl_options = {
    'format': 'bestaudio/best',
    'extractaudio': True,
    'audioformat': 'mp3',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0',
}

ffmpeg_options = {'options': "-vn"}
ytdl = YoutubeDL(ytdl_options)

@bot.command()
async def play(ctx, *, url=None):
    if url == None:
        await ctx.channel.send('Send a youtube url you mongol')

    url1 = url.startswith('https://www.youtube')
    if url1 is False:
        await ctx.channel.send('Ever heard of a Youtube url? yeah send that maybe')

    if url != None:
        if url1 is True:
            try:
                voice_client = await ctx.author.voice.channel.connect()

            except:
                await ctx.channel.send('Get in a voice chat bitch')

        loop = asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))

        song = data['url']
        player = discord.FFmpegPCMAudio(song, **ffmpeg_options,executable=r'C:\Users\rikki\Documents\code2\musicbot\ffmpeg\bin\ffmpeg.exe')
        print('playing')
        voice_client.play(player, after=que())

@bot.command()
async def stop(ctx):
    await ctx.voice_client.disconnect()
    await ctx.send('Disconnected')

@bot.command()
async def pause(ctx):
    await ctx.voice_client.pause()
    await ctx.send('Paused')

@bot.command()
async def resume(ctx):
    await ctx.voice_client.resume()
    await ctx.send('Resumed')

@bot.command()
async def add(ctx, *, url=None):
    global queue
    if url == None:
        await ctx.channel.send('Send a youtube url you mongol')

    url1 = url.startswith('https://www.youtube')
    if url1 is False:
        await ctx.channel.send('Ever heard of a Youtube url? yeah send that maybe')

    if url != None:
        if url1 is True:
            voice_state = ctx.author.voice
            if voice_state != None:
                if queue is None:
                    queue = Convert(url)

                else:
                    queue.append(url)

                print(queue)

            else:
                await ctx.channel.send('Get in a voice chat bitch')

@bot.command()
async def quee(ctx):
    for i in queue:
        await ctx.channel.send('``` %s ```' % queue[0])
    print(queue)

def que():
    try:
        tempvar = queue[0]
        song = tempvar
        player = discord.FFmpegPCMAudio(song, **ffmpeg_options,
                                        executable=r'C:\Users\rikki\Documents\code2\musicbot\ffmpeg\bin\ffmpeg.exe')
        print('playing')
        clint.play(player)

    except Exception as err:
        print('no queue added I am assuming')
        print(err)

bot.run("token")

</code>```

Body:
So I wrote the code for a queue and it refuses to work tells me 'tuple' object has no atrribute 'play' I asked around and someone told me

"voice_client is just a static global tuple that never gets changed. Consider using a botvar here if you want something shared between function" sorry if i'm being dumb but what is a botvar how do I use it and is there any other way I can make a queue that won't need me all this hassle?

Here's my code

import discord
from discord.ext import commands as disect
import asyncio
from youtube_dl import YoutubeDL
import random

Prefix = "-"
bot = disect.Bot(command_prefix=Prefix, intents=discord.Intents.all(), case_insensitive=True, self_bot=False)
voice_clients = {}
queue = []
voice_client = ()

def Convert(string):
    li = list(string.split(" "))
    return li

ytdl_options = {
    'format': 'bestaudio/best',
    'extractaudio': True,
    'audioformat': 'mp3',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0',
}

ffmpeg_options = {'options': "-vn"}
ytdl = YoutubeDL(ytdl_options)

@bot.command()
async def play(ctx, *, url=None):
    if url == None:
        await ctx.channel.send('Send a youtube url you mongol')

    url1 = url.startswith('https://www.youtube')
    if url1 is False:
        await ctx.channel.send('Ever heard of a Youtube url? yeah send that maybe')

    if url != None:
        if url1 is True:
            try:
                voice_client = await ctx.author.voice.channel.connect()

            except:
                await ctx.channel.send('Get in a voice chat bitch')

        loop = asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))

        song = data['url']
        player = discord.FFmpegPCMAudio(song, **ffmpeg_options,executable=r'C:\Users\rikki\Documents\code2\musicbot\ffmpeg\bin\ffmpeg.exe')
        print('playing')
        voice_client.play(player, after=que())

@bot.command()
async def stop(ctx):
    await ctx.voice_client.disconnect()
    await ctx.send('Disconnected')

@bot.command()
async def pause(ctx):
    await ctx.voice_client.pause()
    await ctx.send('Paused')

@bot.command()
async def resume(ctx):
    await ctx.voice_client.resume()
    await ctx.send('Resumed')

@bot.command()
async def add(ctx, *, url=None):
    global queue
    if url == None:
        await ctx.channel.send('Send a youtube url you mongol')

    url1 = url.startswith('https://www.youtube')
    if url1 is False:
        await ctx.channel.send('Ever heard of a Youtube url? yeah send that maybe')

    if url != None:
        if url1 is True:
            voice_state = ctx.author.voice
            if voice_state != None:
                if queue is None:
                    queue = Convert(url)

                else:
                    queue.append(url)

                print(queue)

            else:
                await ctx.channel.send('Get in a voice chat bitch')

@bot.command()
async def quee(ctx):
    for i in queue:
        await ctx.channel.send('``` %s ```' % queue[0])
    print(queue)

def que():
    try:
        tempvar = queue[0]
        song = tempvar
        player = discord.FFmpegPCMAudio(song, **ffmpeg_options,
                                        executable=r'C:\Users\rikki\Documents\code2\musicbot\ffmpeg\bin\ffmpeg.exe')
        print('playing')
        clint.play(player)

    except Exception as err:
        print('no queue added I am assuming')
        print(err)

bot.run("token")


问:
Swift UITests Presetup shared between multiple Parallel XCTestsCase
-1

Could someone help me. I have a hard time to implement UITests and store the result for future upload to TestRail (when all tests is completed.

I have testRailmanager with two method

```<code>createRun() (this method make api call returning testRunID used by second endpoint)
sendResults([TestResult]]
</code>```

Everything is working if I have only one XCTestCase with multiple test methods for example: RegistrationUITests: XCTestcase)

Unfortunately if I add multiple files with multiple XCTestCase like this and run parallel tests

TestLoginUITests.swift

TestDashboardUITests.swift

TestEventsUITests.swift etc. the manager is not shared between test.

I tried singleton TestRailManager.shared, I tried have a manager as global constant. But nothing

What is the easiest way to share the data between multiple XCTests classes running parralel? Thank you

Body:
-1

Could someone help me. I have a hard time to implement UITests and store the result for future upload to TestRail (when all tests is completed.

I have testRailmanager with two method

createRun() (this method make api call returning testRunID used by second endpoint)
sendResults([TestResult]]

Everything is working if I have only one XCTestCase with multiple test methods for example: RegistrationUITests: XCTestcase)

Unfortunately if I add multiple files with multiple XCTestCase like this and run parallel tests

TestLoginUITests.swift

TestDashboardUITests.swift

TestEventsUITests.swift etc. the manager is not shared between test.

I tried singleton TestRailManager.shared, I tried have a manager as global constant. But nothing

What is the easiest way to share the data between multiple XCTests classes running parralel? Thank you


问:
How do I use Sanity Studio v3 in a PnPM monorepo?
I am testing out Sanity Studio v3 for the first time.  In the past (v2), I was able to get Sanity and my frontend (Sveltekit or Next) set up in a simple PNPM monorepo so I only need to run one command to start everything and do other common tasks.

The monorepo I am using is here.  This is a demo, but is will show you the basic inter workings.

The problem I am having is that I do not seem to have the ablity to start sanity sudio in dev mode from the root packack.json.  Here are my scripts:

```<code>"scripts": {
  "start:sveltekit": "pnpm -F @sanity-3-playground/sveltekit dev",
  "start:sanity": "pnpm -F @sanity-3-playground/sanity pnpm dev",
  "start": "pnpm -r start",
  "update:all": "pnpm -r update -i -L",
  "clean": "find ./ -name node_modules -type d -exec rm -rf {} +"
},
</code>```

Here are the scripts in the Sanity package.json:

```<code>"dev": "sanity dev",
  "start": "sanity start",
  "build": "sanity build",
  "deploy": "sanity deploy",
  "deploy-graphql": "sanity graphql deploy"
</code>```

When I pnpm start from the sanity dir every this is great,  but when I run pnpm start:sanity in the root folder, I get

```<code>  IMPORTANT: You're running Sanity Studio v3, and in this version
  the [start] command is used to preview static builds. To
  run a development server, use the [npm run dev] command instead.

  For more information go to https://www.sanity.io/help/studio-v2-vs-v3
</code>```

I can see that it wants me to hit enter to enter dev mode, but it does not work.

Body:
I am testing out Sanity Studio v3 for the first time.  In the past (v2), I was able to get Sanity and my frontend (Sveltekit or Next) set up in a simple PNPM monorepo so I only need to run one command to start everything and do other common tasks.

The monorepo I am using is here.  This is a demo, but is will show you the basic inter workings.

The problem I am having is that I do not seem to have the ablity to start sanity sudio in dev mode from the root packack.json.  Here are my scripts:

"scripts": {
  "start:sveltekit": "pnpm -F @sanity-3-playground/sveltekit dev",
  "start:sanity": "pnpm -F @sanity-3-playground/sanity pnpm dev",
  "start": "pnpm -r start",
  "update:all": "pnpm -r update -i -L",
  "clean": "find ./ -name node_modules -type d -exec rm -rf {} +"
},

Here are the scripts in the Sanity package.json:

"dev": "sanity dev",
  "start": "sanity start",
  "build": "sanity build",
  "deploy": "sanity deploy",
  "deploy-graphql": "sanity graphql deploy"

When I pnpm start from the sanity dir every this is great,  but when I run pnpm start:sanity in the root folder, I get

  IMPORTANT: You're running Sanity Studio v3, and in this version
  the [start] command is used to preview static builds. To
  run a development server, use the [npm run dev] command instead.

  For more information go to https://www.sanity.io/help/studio-v2-vs-v3

I can see that it wants me to hit enter to enter dev mode, but it does not work.


问:
React Js . When canceling modal i'm trying to check if inputs have any value or not before canceling
I have this modal with some inputs inside , in this modal i want to check if nothing is typed or selected in any of the fields , when the user clicks cancel no popup modal will show to tell them if 'they are sure they want to cancel' .

If they write something in any of the fields or select something in any of the fields i want to show the modal , but i made it work only for the Name input for the rest i couldn't figure it out

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import DialogModal from '../../../components/Dialog';
import DestinationGroupInput from '../../../components/Input/DestinationGroupInput';
import ChipSelect from '../../../components/selectWithChip/ChipSelect';
import IpRange from './IpRange/IpRange';

import {
  DestinationGroup,
  // TIpInputProps,
  // TUrlProps,
} from '../../../types/Policies';
import Url from './Url/Url';

import PoliciesServices from '../../../services/policies';

const CreateModal = () => {
  const [groupName, setGroupName] = useState<string>('');
  const [description, setDescription] = useState<string>('');
  const [list, setList] = useState<any[]>([
    // const [list, setList] = useState<TIpInputProps[]>([
    { select: 'ip/cidr', value: '' },
  ]);
  const [url, setUrl] = useState<any[]>([
    // const [url, setUrl] = useState<TUrlProps[]>([
    { select: 'wildcard', value: '' },
  ]);
  const [classification, setClassification] = useState<string[]>([]);

  const [classificationsOptions, setClassificationsOptions] = useState<
    string[]
  >([]);

  console.log(list, 'list');
  console.log(classification, 'class');
  console.log(url, 'url');

  const editingMode = useMemo(() => Boolean(editingModal), [editingModal]);

  const handleCreate = useCallback(async () => {
    setLoading(true);
    const payload = {
      name: groupName,
      description,
      ips: list.map((item) => ({
        type: item.select,
        ip: item.value,
        range_from: item.from || '',
        range_to: item.to || '',
      })),
      domains: url.map((item) => ({
        type: item.select,
        value: item.value,
      })),
      classification: classification.map((item) => item),
    };

    try {
      await PoliciesServices.createDestinationGroup(payload);

      Toast({
        type: 'success',
        message: `Successfully created destination`,
      });
      await afterSubmit();
    } catch (err) {
      Toast({
        type: 'error',
        message: `Failed to create destination`,
      });
    } finally {
      setLoading(false);
    }
  }, [list, url, groupName, classification]);

  const handleEdit = useCallback(async () => {
    setLoading(true);
    const payload = {
      name: groupName,
      description,
      ips: list.map((item) => ({
        type: item.select,
        ip: item.value,
        range_from: item.from || '',
        range_to: item.to || '',
      })),
      domains: url.map((item) => ({
        type: item.select,
        value: item.value,
      })),
      classification: classification.map((item) => item),
    };

    try {
      await PoliciesServices.editDestinationGroup(
        editingModal?.id || '',
        payload
      );
      Toast({
        type: 'success',
        message: `Successfully edited`,
      });
      await afterSubmit();
    } catch (err) {
      Toast({
        type: 'error',
        message: `Failed to edit`,
      });
    } finally {
      setLoading(false);
    }
  }, [list, url, groupName, classification, description]);

  const getClassificationsOptions = useCallback(async () => {
    try {
      const classificationsList = await PoliciesServices.getClassifications();

      if (classificationsList) {
        setClassificationsOptions(classificationsList.data);
      }
    } catch (err) {
      Toast({
        type: 'error',
        message: `Failed to get classifications`,
      });
    }
  }, []);

  const isValid = !!groupName.length && isOneItemSelected;

  const onModalCancel = () => {
    if (
      groupName.trim().length === 0 ||
      classification.length === 0 ||
      (url[0].value && url[0].value === '') ||
      (list[0].from && list[0].from === '') ||
      (list[0].to && list[0].to === '')
    ) {
      setVisibleModal(false);
    }
    // eslint-disable-next-line no-unused-expressions
    groupName.trim().length > 0 ||
      (classification.length > 0 && setCancelModal(true));
  };

  return (
    <>
      {/* Create Modal when clicking Create Group */}
      <DialogModal
        className={styles.modal}
        dontCloseOnBackdropClick
        visible={visibleModal}
        setVisible={setVisibleModal}
        title="Create Group"
        onCancel={onModalCancel}
        actions={[
          {
            title: 'Cancel',
            onClick: onModalCancel,
            theme: 'light',
          },
          {
            title: 'Save',
            onClick: () => {
              handleSubmit();
              setVisibleModal(false);
            },
            theme: 'primary',
            disabled: !isValid,
          },
        ]}
      >

          <DestinationGroupInput
            value={groupName}
            label="Group Name"
            onChange={(e) => setGroupName(e.target.value)}
          />

          <DestinationGroupInput
            value={description}
            label="Description"
            onChange={(e) => setDescription(e.target.value)}
          />

          <IpRange list={list} setList={setList} />

          <Url url={url} setUrl={setUrl} />

          <ChipSelect
            label="Classification"
            classification={classification}
            setClassification={setClassification}
            setClassificationsOptions={setClassificationsOptions}
            classificationsOptions={classificationsOptions}
          />

      </DialogModal>
    </>
  );
};

export default CreateModal;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```


问:
MIPS MARS ASSEMBLY CODE operand is of incorrect type
```<code>

.data
prompt: .asciiz "Please enter an integer: "
x: .double 2.0
tolerance: .double 1e-6

.text
main:
# Prompt user for initial value of x
li $v0, 4
la $a0, prompt
syscall

# Read in user input
li $v0, 7
syscall

# Convert user input to double and store in x
mtc1 $v0, $f12
cvt.d.w $f0, $f12
sdc1 $f0, x

# Initialize counter and F(x) value
li $t0, 0
ldc1 $f12, x
add.d $f14, $f12, $f12
mul.d $f14, $f12, $f14
add.d $f14, $f14, 1

# Loop until F(x) is within tolerance
loop:
    # Calculate x{n+1}
    ldc1 $f12, x
    add.d $f13, $f12, $f12
    mul.d $f13, $f12, $f13
    mul.d $f13, $f13, $f12
    add.d $f13, $f13, -8
    mul.d $f13, $f13, $f12
    div.d $f12, $f14, $f13

    # Calculate F(x)
    ldc1 $f12, x
    add.d $f14, $f12, $f12
    mul.d $f14, $f12, $f14
    add.d $f14, $f14, 1

    # Print current x and F(x) values
    li $v0, 3
    ldc1 $f12, x
    syscall
    li $v0, 11
    li $a0, ','
    syscall
    li $v0, 3
    ldc1 $f14, $f14
    syscall
    li $v0, 11
    li $a0, '\n'
    syscall

    # Check if F(x) is within tolerance
    ldc1 $f12, x
    ldc1 $f14, tolerance
    c.lt.d $f12, $f14
    beq $0, $0, done

    # Increment counter and repeat loop
    addi $t0, $t0, 1
    b loop

done:
    # Print root found
    li $v0, 4
    la $a0, "Root found: "
    syscall
    li $v0, 3
    ldc1 $f12, x
    syscall

    # End program
    li $v0, 10
    syscall

</code>```

line 29 column 19: "1": operand is of incorrect type
line 46 column 23: "1": operand is of incorrect type
line 56 column 5: "ldc1": Too few or incorrectly formatted operands. Expected: ldc$f2,-100($t2)
line 75 column 5: "la": Too few or incorrectly formatted operands. Expected: la $t1,($t2)

Does anyone know what I'm doing wrong here? My goal is to write a MIPS program which will find a value of xn such that F(xn)=0, to a tolerance of 10-6 with the given formula +1 =  − (()/′()).

For example consider a continuous function F(x)=x3-4x2+1 with its derivative F’(x)=3x2-8x. Thus, by calculating successive values of x, the value of F(xn) will approach 0, and hence be a root of F.

I am fairly new to MIPS and I'm having trouble.

Body:
.data
prompt: .asciiz "Please enter an integer: "
x: .double 2.0
tolerance: .double 1e-6

.text
main:
# Prompt user for initial value of x
li $v0, 4
la $a0, prompt
syscall

# Read in user input
li $v0, 7
syscall

# Convert user input to double and store in x
mtc1 $v0, $f12
cvt.d.w $f0, $f12
sdc1 $f0, x

# Initialize counter and F(x) value
li $t0, 0
ldc1 $f12, x
add.d $f14, $f12, $f12
mul.d $f14, $f12, $f14
add.d $f14, $f14, 1

# Loop until F(x) is within tolerance
loop:
    # Calculate x{n+1}
    ldc1 $f12, x
    add.d $f13, $f12, $f12
    mul.d $f13, $f12, $f13
    mul.d $f13, $f13, $f12
    add.d $f13, $f13, -8
    mul.d $f13, $f13, $f12
    div.d $f12, $f14, $f13

    # Calculate F(x)
    ldc1 $f12, x
    add.d $f14, $f12, $f12
    mul.d $f14, $f12, $f14
    add.d $f14, $f14, 1

    # Print current x and F(x) values
    li $v0, 3
    ldc1 $f12, x
    syscall
    li $v0, 11
    li $a0, ','
    syscall
    li $v0, 3
    ldc1 $f14, $f14
    syscall
    li $v0, 11
    li $a0, '\n'
    syscall

    # Check if F(x) is within tolerance
    ldc1 $f12, x
    ldc1 $f14, tolerance
    c.lt.d $f12, $f14
    beq $0, $0, done

    # Increment counter and repeat loop
    addi $t0, $t0, 1
    b loop

done:
    # Print root found
    li $v0, 4
    la $a0, "Root found: "
    syscall
    li $v0, 3
    ldc1 $f12, x
    syscall

    # End program
    li $v0, 10
    syscall

line 29 column 19: "1": operand is of incorrect type
line 46 column 23: "1": operand is of incorrect type
line 56 column 5: "ldc1": Too few or incorrectly formatted operands. Expected: ldc$f2,-100($t2)
line 75 column 5: "la": Too few or incorrectly formatted operands. Expected: la $t1,($t2)

Does anyone know what I'm doing wrong here? My goal is to write a MIPS program which will find a value of xn such that F(xn)=0, to a tolerance of 10-6 with the given formula +1 =  − (()/′()).

For example consider a continuous function F(x)=x3-4x2+1 with its derivative F’(x)=3x2-8x. Thus, by calculating successive values of x, the value of F(xn) will approach 0, and hence be a root of F.

I am fairly new to MIPS and I'm having trouble.


问:
why do i get this compile error: " error: cannot bind non-const lvalue reference of type ‘Matrix&’ to an rvalue of type ‘Matrix’ "?
Ok so i'am writting this code for an exercise we have to write a class for matrices and then to check it we use a code that the teacher wrote to check if it performes the normal operations.

And i don't get exactly where i am wrong  it seems to bother the compiler that i return a type Matrix but really i dont get what is a lvalue or rvalue .
But i get this when i try to compile

```<code>anthony@anthony-linux:~/Documents/CS/Ex6$ g++ -Wall simplematrixtest.cc Matrix.cc -o simplematrixtest
simplematrixtest.cc: In function ‘int main()’:
simplematrixtest.cc:70:24: error: cannot bind non-const lvalue reference of type ‘Matrix&’ to an rvalue of type ‘Matrix’
   70 |   Matrix g = f.multiply(a);
      |              ~~~~~~~~~~^~~
In file included from simplematrixtest.cc:4:
Matrix.hh:13:18: note:   initializing argument 1 of ‘Matrix::Matrix(Matrix&)’
   13 |   Matrix(Matrix &m);
      |          ~~~~~~~~^

</code>```

this is my class Matrix:

```<code>
</code>```
```<code>#include "Matrix.hh"
#include <cmath>
#include <iostream>
using namespace std;
// Default constructor:  initializes the Matrix.
Matrix::Matrix() {
  nrows=0;
  ncols=0;
  values=0;

}

// Initializes the Matrix with rows and cols.
Matrix::Matrix(int numberOfRows,int numberOfCols) {
  nrows=numberOfRows;
  ncols=numberOfCols;
  values = new double[nrows*ncols] ;
    for (int i = 0; i < nrows*ncols; i++) {
 values[i] = 0;
 }
}
// Copy constructor
Matrix::Matrix(Matrix &m)
{
nrows=m.getRows();
ncols=m.getCols();
int sizeOfM=m.getRows()*m.getCols();
values = new double[sizeOfM];
for (int i = 0; i < sizeOfM; ++i) {
values[i] = m.values[i];
}
}

// Destructor - Matrix allocates no dynamic resources.
Matrix::~Matrix() {
delete[] values;
  // no-op
}

// Mutators:
 void Matrix::setElem(int rowIndex,int colIndex,double val){
values[rowIndex*ncols+colIndex]=val;            /*See Jasper i listen to what you say ! No return for a void function :) */
}
  void Matrix::subtract(Matrix &m) {
      for (int i = 0; i < nrows*ncols; i++) {
        values[i] -=m.values[i];
      }
  }
  void Matrix::add(Matrix &m) {
      for (int i = 0; i < nrows*ncols; i++) {
        values[i] +=m.values[i];
      }
  }
    Matrix Matrix::multiply(Matrix &m) {

    if(ncols!=m.getRows()){
    cout << " Error :invalid matrix multiplication"<< endl;
    Matrix ret(0,0);
    return ret;
    }
    else{

    Matrix ret(nrows,m.getCols());

      for (int rowIndex = 0; rowIndex < ret.nrows; rowIndex++) {
         for (int colIndex = 0; colIndex < ret.ncols; colIndex++) {
            for(int count=0; count <= ncols; count++) {

        ret.values[rowIndex*ncols+colIndex] +=(values[rowIndex*ncols+(count)]*m.values[count*ncols+colIndex]);
            }
        }
      }
       return ret;
      }

  }

// Accessors:

  int Matrix::getRows() {
  return nrows;
  }
  int Matrix::getCols() {
  return ncols;
  }
  double Matrix::getElem(int rowIndex,int colIndex){

  return values[rowIndex*ncols+colIndex];
  }
   bool Matrix::equals(Matrix &m) {
   if(m.getRows()!=nrows||m.getCols()!=ncols){return false;}
      for (int i = 0; i < nrows*ncols; i++) {
        if(values[i] !=m.values[i]){return false;}
      }
      return true;
   }
</code>```
```<code>
Apparently the problem is in multiply here is the test code

</code>```
```<code>#include <iostream>
using namespace std;

#include "Matrix.hh"

// Have some fun playing with a Matrix!
int main(void) {

  // Create a new matrix with two rows and three columns
  Matrix a(2, 3);

  // Print out some information about the size of this matrix:
  cout << "Matrix a is " << a.getRows() << " rows tall." << endl;
  cout << "Matrix a is " << a.getCols() << " columns wide." << endl;

  // Print out the contents of this matrix (should be all zeroes!):
  for(int r = 0; r < a.getRows(); r++) {
    for(int c = 0; c < a.getCols(); c++) {
      cout << "Element (" << r << ", " << c << ") = " << a.getElem(r,c) << endl;
    }
  }

  // Fill in a few values
  a.setElem(1, 2, -5280);  // bottom right element is now -5280
  a.setElem(0, 1, 123);    // top center element is now 123

  // Create an identical copy of this matrix
  Matrix b = a;

  // Change the original matrix some more
  a.setElem(1, 2, 555);  // bottom right element is now 555

  // Examine some elements of each matrix
  cout << "(1,2) of a = " << a.getElem(1,2) << " [should be 555]" << endl;
  cout << "(1,2) of b = " << b.getElem(1,2) << " [should be -5280]" << endl;

  // So if a and b are different, let's copy a into a new matrix and add b to it:
  Matrix c = a;
  c.add(b);

  // Now let's copy c into another new matrix, d, and subtract a from it:
  Matrix d = c;
  d.subtract(a);

  // Hmm...  that means d should be b, no?
  if (d.equals(b)) {
    cout << "Yay!  d = b!" << endl;
  } else {
    cout << "Uh-oh!  Something went wrong, d isn't b!" << endl;
  }

  // Let's create a tiny 0 by 0 matrix using the default constructor:
  Matrix e;
  cout << "0x0 matrix e is " << e.getRows() << " by " << e.getCols() << endl;

  // Of course, e and d are different, since they have different sizes!
  if(!e.equals(d)) {
    cout << "e and d are indeed different!" << endl;
  } else {
    cout << "Oh well, back to the drawing board...." << endl;
  }

  Matrix f(2,2);

  f.setElem(0, 0, 2.0);
  f.setElem(1, 0, 3.0);
  f.setElem(0, 1, 5.0);
  f.setElem(1, 1, 7.0);

  Matrix g = f.multiply(a);

  if (g.getElem(1, 2) == 3885.0) {
    cout << "Multiply seems to work!" << endl;
  } else {
    cout << "Error in multiply() !" << endl;
  }

  // Okay, enough of this; destroy all those matrices and end the program:
  return 0;
}

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

If i write

</code>```

Matrix g = a ;
f.multiply(a);

```<code>The code compiles without any problem so it is a problem with this line:  Matrix g =f.multiply(a);
</code>```

Body:
Ok so i'am writting this code for an exercise we have to write a class for matrices and then to check it we use a code that the teacher wrote to check if it performes the normal operations.

And i don't get exactly where i am wrong  it seems to bother the compiler that i return a type Matrix but really i dont get what is a lvalue or rvalue .
But i get this when i try to compile

anthony@anthony-linux:~/Documents/CS/Ex6$ g++ -Wall simplematrixtest.cc Matrix.cc -o simplematrixtest
simplematrixtest.cc: In function ‘int main()’:
simplematrixtest.cc:70:24: error: cannot bind non-const lvalue reference of type ‘Matrix&’ to an rvalue of type ‘Matrix’
   70 |   Matrix g = f.multiply(a);
      |              ~~~~~~~~~~^~~
In file included from simplematrixtest.cc:4:
Matrix.hh:13:18: note:   initializing argument 1 of ‘Matrix::Matrix(Matrix&)’
   13 |   Matrix(Matrix &m);
      |          ~~~~~~~~^

this is my class Matrix:

#include "Matrix.hh"
#include <cmath>
#include <iostream>
using namespace std;
// Default constructor:  initializes the Matrix.
Matrix::Matrix() {
  nrows=0;
  ncols=0;
  values=0;

}

// Initializes the Matrix with rows and cols.
Matrix::Matrix(int numberOfRows,int numberOfCols) {
  nrows=numberOfRows;
  ncols=numberOfCols;
  values = new double[nrows*ncols] ;
    for (int i = 0; i < nrows*ncols; i++) {
 values[i] = 0;
 }
}
// Copy constructor
Matrix::Matrix(Matrix &m)
{
nrows=m.getRows();
ncols=m.getCols();
int sizeOfM=m.getRows()*m.getCols();
values = new double[sizeOfM];
for (int i = 0; i < sizeOfM; ++i) {
values[i] = m.values[i];
}
}

// Destructor - Matrix allocates no dynamic resources.
Matrix::~Matrix() {
delete[] values;
  // no-op
}

// Mutators:
 void Matrix::setElem(int rowIndex,int colIndex,double val){
values[rowIndex*ncols+colIndex]=val;            /*See Jasper i listen to what you say ! No return for a void function :) */
}
  void Matrix::subtract(Matrix &m) {
      for (int i = 0; i < nrows*ncols; i++) {
        values[i] -=m.values[i];
      }
  }
  void Matrix::add(Matrix &m) {
      for (int i = 0; i < nrows*ncols; i++) {
        values[i] +=m.values[i];
      }
  }
    Matrix Matrix::multiply(Matrix &m) {

    if(ncols!=m.getRows()){
    cout << " Error :invalid matrix multiplication"<< endl;
    Matrix ret(0,0);
    return ret;
    }
    else{

    Matrix ret(nrows,m.getCols());

      for (int rowIndex = 0; rowIndex < ret.nrows; rowIndex++) {
         for (int colIndex = 0; colIndex < ret.ncols; colIndex++) {
            for(int count=0; count <= ncols; count++) {

        ret.values[rowIndex*ncols+colIndex] +=(values[rowIndex*ncols+(count)]*m.values[count*ncols+colIndex]);
            }
        }
      }
       return ret;
      }

  }

// Accessors:

  int Matrix::getRows() {
  return nrows;
  }
  int Matrix::getCols() {
  return ncols;
  }
  double Matrix::getElem(int rowIndex,int colIndex){

  return values[rowIndex*ncols+colIndex];
  }
   bool Matrix::equals(Matrix &m) {
   if(m.getRows()!=nrows||m.getCols()!=ncols){return false;}
      for (int i = 0; i < nrows*ncols; i++) {
        if(values[i] !=m.values[i]){return false;}
      }
      return true;
   }

Apparently the problem is in multiply here is the test code

#include <iostream>
using namespace std;

#include "Matrix.hh"

// Have some fun playing with a Matrix!
int main(void) {

  // Create a new matrix with two rows and three columns
  Matrix a(2, 3);

  // Print out some information about the size of this matrix:
  cout << "Matrix a is " << a.getRows() << " rows tall." << endl;
  cout << "Matrix a is " << a.getCols() << " columns wide." << endl;

  // Print out the contents of this matrix (should be all zeroes!):
  for(int r = 0; r < a.getRows(); r++) {
    for(int c = 0; c < a.getCols(); c++) {
      cout << "Element (" << r << ", " << c << ") = " << a.getElem(r,c) << endl;
    }
  }

  // Fill in a few values
  a.setElem(1, 2, -5280);  // bottom right element is now -5280
  a.setElem(0, 1, 123);    // top center element is now 123

  // Create an identical copy of this matrix
  Matrix b = a;

  // Change the original matrix some more
  a.setElem(1, 2, 555);  // bottom right element is now 555

  // Examine some elements of each matrix
  cout << "(1,2) of a = " << a.getElem(1,2) << " [should be 555]" << endl;
  cout << "(1,2) of b = " << b.getElem(1,2) << " [should be -5280]" << endl;

  // So if a and b are different, let's copy a into a new matrix and add b to it:
  Matrix c = a;
  c.add(b);

  // Now let's copy c into another new matrix, d, and subtract a from it:
  Matrix d = c;
  d.subtract(a);

  // Hmm...  that means d should be b, no?
  if (d.equals(b)) {
    cout << "Yay!  d = b!" << endl;
  } else {
    cout << "Uh-oh!  Something went wrong, d isn't b!" << endl;
  }

  // Let's create a tiny 0 by 0 matrix using the default constructor:
  Matrix e;
  cout << "0x0 matrix e is " << e.getRows() << " by " << e.getCols() << endl;

  // Of course, e and d are different, since they have different sizes!
  if(!e.equals(d)) {
    cout << "e and d are indeed different!" << endl;
  } else {
    cout << "Oh well, back to the drawing board...." << endl;
  }

  Matrix f(2,2);

  f.setElem(0, 0, 2.0);
  f.setElem(1, 0, 3.0);
  f.setElem(0, 1, 5.0);
  f.setElem(1, 1, 7.0);

  Matrix g = f.multiply(a);

  if (g.getElem(1, 2) == 3885.0) {
    cout << "Multiply seems to work!" << endl;
  } else {
    cout << "Error in multiply() !" << endl;
  }

  // Okay, enough of this; destroy all those matrices and end the program:
  return 0;
}

If i write

Matrix g = a ;
f.multiply(a);

The code compiles without any problem so it is a problem with this line:  Matrix g =f.multiply(a);


问:
Get maximum value of y value within a specified range of x value
I am using Python 3 in jupyter notebook and I data that looks like this:

```<code>x = [5100.   5100.05 5100.1  ... 5399.85 5399.9  5399.95] Angstrom
y = [1.83400998 1.26499399 0.85423358 ... 0.78314406 0.76861344 0.77460277]
</code>```

Is there a way in Python 3 to grab the maximum y value for x between 5120 and 5250?

Body:
I am using Python 3 in jupyter notebook and I data that looks like this:

x = [5100.   5100.05 5100.1  ... 5399.85 5399.9  5399.95] Angstrom
y = [1.83400998 1.26499399 0.85423358 ... 0.78314406 0.76861344 0.77460277]

Is there a way in Python 3 to grab the maximum y value for x between 5120 and 5250?


问:
Javascript parent function context
When defining functions like this:

```<code>appName.Test = {
  init: function() {
    (...)
    .then(function(param1) {
      this.parameter1 = param1; // does NOT work ??
      appName.Test.parameter1 = param1; // does work
      this.foo();
    });
  }
}
</code>```

How to define param1 at the "Test" level (context)? (this/parent.parameter1 do not work).

Method that does work "looks wrong" to me, is this correct way?.
I need to define this variable at the Test context because it is used in other Test's methods..

Title: Javascript parent function context

Body:
When defining functions like this:

appName.Test = {
  init: function() {
    (...)
    .then(function(param1) {
      this.parameter1 = param1; // does NOT work ??
      appName.Test.parameter1 = param1; // does work
      this.foo();
    });
  }
}

How to define param1 at the "Test" level (context)? (this/parent.parameter1 do not work).

Method that does work "looks wrong" to me, is this correct way?.
I need to define this variable at the Test context because it is used in other Test's methods..


问:
Inconsistent Results from Cross-Server Query
I have a query that yields inconsistent results.  I receive a different number of rows almost every time I run the query.  I receive no errors.  I have tried running the query from all of the servers in the query.  I also tried running the query from a fourth unrelated server that is linked to both servers in the query.  I tried running each of the CTEs on its own and always get consistent results.  Only the last part of the query yields inconsistent results.

Does anyone know what could be causing these inconsistent results?  Thanks!

```<code> with customerOrderMatches as (
  select
 SAPOX.docentry
,SAPO.cardcode as 'O CC'
,SAPCMS.CardCode+'-'+SAPCMS.Address as 'OrigShipToID'
,SAPCMB.CardCode+'-'+SAPCMB.Address as 'OrigCustID'
from [Server1].[BowDB].[dbo].ORDR SAPO
join [Server1].[BowDB].[dbo].RDR12 SAPOX
on SAPO.docentry=SAPOX.docentry
left outer join [Server1].[BowDB].[dbo].CRD1 SAPCMS --ship to match
on SAPCMS.cardcode=SAPO.cardcode
and SAPCMS.Address=SAPO.Shiptocode
and SAPCMS.AdresType='S'
and SAPCMS.Street=SAPOX.StreetS
left outer join [Server1].[BowDB].[dbo].CRD1 SAPCMB --bill to match
on SAPCMB.cardcode=SAPO.cardcode
and SAPCMB.Address=SAPO.PayToCode
and SAPCMB.AdresType='B'
and SAPCMB.Street=SAPOX.StreetB
where
SAPO.cardcode NOT IN (
'1001', '1002', '1003'
)
AND SAPO.canceled = 'N'
),

customerRank as (
SELECT
    rtrim(C.custid) AS 'custid'
    ,COUNT(SLShipper.ShipperID) as 'totalShippers'
    ,Row_number() OVER (ORDER BY COUNT(SLShipper.ShipperID) DESC) AS 'customerRank'
FROM [MLSQL12].[SLapplication15].dbo.customer C
left outer join [MLSQL12].[SLapplication15].dbo.SOShipHeader SLShipper
    on SLShipper.custid=C.custid
GROUP BY C.CustID
),

customerShipToRank as (
SELECT
rtrim(SOA.CustID) AS 'custid'
,rtrim(SOA.ShiptoID) as 'shiptoid'
,COUNT(SLShipper.ShipperID) as 'totalShippers'
,cast(Row_number() OVER(Partition by SOA.custid ORDER BY COUNT(SLShipper.ShipperID) DESC) as int) AS 'ShipToRank'
,customerRank
FROM [MLSQL12].[SLapplication15].dbo.soaddress SOA
left outer join [MLSQL12].[SLapplication15].dbo.SOShipHeader SLShipper
on SLShipper.CustID=SOA.CustId
and SLShipper.ShiptoID=SOA.shiptoid
join customerRank CR
on CR.custid=SOA.CustID
GROUP BY
SOA.CustID
,SOA.ShiptoID
,customerRank
),

combinedData as (
select
COM.Docentry
,CXR.*
,CSTR.*
from customerOrderMatches COM
join MLSQL15.HistoricalData.Hist.CustomerXRef CXR
on CXR.OrigShipToID=COM.OrigShipToID collate SQL_Latin1_General_CP850_CI_AS
and CXR.OrigCustID=COM.OrigCustID collate SQL_Latin1_General_CP850_CI_AS
left outer join customerShipToRank CSTR
on CSTR.shiptoid =CXR.BKShiptoId
and CSTR.custid =CXR.BKCustId
)

select
*
from combinedData CD
where CONCAT(customerRank,ShipToRank) in (
select MIN(CONCAT(customerRank,ShipToRank))
from combinedData
group by docentry)
order by docentry
</code>```

Other random facts about the situation:
-I realize that there are probably inefficiencies in my query that could be optimized.  However, this should not result in inconsistent results.
-One database is an SAP DB.
-One DB is a Microsoft Dynamics SL DB.
-One DB is our own DB we created for acquisition data.

Update (12/12/2022)
One of the columns returned is a basic primary key of an order in an order table.  I ran the query six times and got the following results:

Query Run Number
Total Rows
Lowest DocEntry
Highest DocEntry

1
14509
9
31412

2
14509
9
31412

3
5455
105
31408

4
5448
108
31411

5
14509
9
31412

6
5181
105
31411

Body:
I have a query that yields inconsistent results.  I receive a different number of rows almost every time I run the query.  I receive no errors.  I have tried running the query from all of the servers in the query.  I also tried running the query from a fourth unrelated server that is linked to both servers in the query.  I tried running each of the CTEs on its own and always get consistent results.  Only the last part of the query yields inconsistent results.

Does anyone know what could be causing these inconsistent results?  Thanks!

 with customerOrderMatches as (
  select
 SAPOX.docentry
,SAPO.cardcode as 'O CC'
,SAPCMS.CardCode+'-'+SAPCMS.Address as 'OrigShipToID'
,SAPCMB.CardCode+'-'+SAPCMB.Address as 'OrigCustID'
from [Server1].[BowDB].[dbo].ORDR SAPO
join [Server1].[BowDB].[dbo].RDR12 SAPOX
on SAPO.docentry=SAPOX.docentry
left outer join [Server1].[BowDB].[dbo].CRD1 SAPCMS --ship to match
on SAPCMS.cardcode=SAPO.cardcode
and SAPCMS.Address=SAPO.Shiptocode
and SAPCMS.AdresType='S'
and SAPCMS.Street=SAPOX.StreetS
left outer join [Server1].[BowDB].[dbo].CRD1 SAPCMB --bill to match
on SAPCMB.cardcode=SAPO.cardcode
and SAPCMB.Address=SAPO.PayToCode
and SAPCMB.AdresType='B'
and SAPCMB.Street=SAPOX.StreetB
where
SAPO.cardcode NOT IN (
'1001', '1002', '1003'
)
AND SAPO.canceled = 'N'
),

customerRank as (
SELECT
    rtrim(C.custid) AS 'custid'
    ,COUNT(SLShipper.ShipperID) as 'totalShippers'
    ,Row_number() OVER (ORDER BY COUNT(SLShipper.ShipperID) DESC) AS 'customerRank'
FROM [MLSQL12].[SLapplication15].dbo.customer C
left outer join [MLSQL12].[SLapplication15].dbo.SOShipHeader SLShipper
    on SLShipper.custid=C.custid
GROUP BY C.CustID
),

customerShipToRank as (
SELECT
rtrim(SOA.CustID) AS 'custid'
,rtrim(SOA.ShiptoID) as 'shiptoid'
,COUNT(SLShipper.ShipperID) as 'totalShippers'
,cast(Row_number() OVER(Partition by SOA.custid ORDER BY COUNT(SLShipper.ShipperID) DESC) as int) AS 'ShipToRank'
,customerRank
FROM [MLSQL12].[SLapplication15].dbo.soaddress SOA
left outer join [MLSQL12].[SLapplication15].dbo.SOShipHeader SLShipper
on SLShipper.CustID=SOA.CustId
and SLShipper.ShiptoID=SOA.shiptoid
join customerRank CR
on CR.custid=SOA.CustID
GROUP BY
SOA.CustID
,SOA.ShiptoID
,customerRank
),

combinedData as (
select
COM.Docentry
,CXR.*
,CSTR.*
from customerOrderMatches COM
join MLSQL15.HistoricalData.Hist.CustomerXRef CXR
on CXR.OrigShipToID=COM.OrigShipToID collate SQL_Latin1_General_CP850_CI_AS
and CXR.OrigCustID=COM.OrigCustID collate SQL_Latin1_General_CP850_CI_AS
left outer join customerShipToRank CSTR
on CSTR.shiptoid =CXR.BKShiptoId
and CSTR.custid =CXR.BKCustId
)

select
*
from combinedData CD
where CONCAT(customerRank,ShipToRank) in (
select MIN(CONCAT(customerRank,ShipToRank))
from combinedData
group by docentry)
order by docentry

Other random facts about the situation:
-I realize that there are probably inefficiencies in my query that could be optimized.  However, this should not result in inconsistent results.
-One database is an SAP DB.
-One DB is a Microsoft Dynamics SL DB.
-One DB is our own DB we created for acquisition data.

Update (12/12/2022)
One of the columns returned is a basic primary key of an order in an order table.  I ran the query six times and got the following results:

Query Run Number
Total Rows
Lowest DocEntry
Highest DocEntry

1
14509
9
31412

2
14509
9
31412

3
5455
105
31408

4
5448
108
31411

5
14509
9
31412

6
5181
105
31411


问:
n_splits=10 cannot be greater than the number of members in each class error
I'm trying to build validation curve that relying on max_depth but keep getting an error:

```<code>n_splits=10 cannot be greater than the number of members in each class.
</code>```

I tried to put n_splits with different values, error doesnt change. I got data from .cvs file with numeric data

Here is code fragment that gets error:

```<code>from sklearn.tree import DecisionTreeClassifier
    model = DecisionTreeClassifier(random_state=123)
    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=132)
    train_scores, valid_scores = validation_curve(model, X, y, param_name="max_depth", n_jobs=-1,
       param_range=np.arange(1, 20), cv=10, scoring="accuracy")
</code>```

Im working in Jupiter Lite.

Body:
I'm trying to build validation curve that relying on max_depth but keep getting an error:

n_splits=10 cannot be greater than the number of members in each class.

I tried to put n_splits with different values, error doesnt change. I got data from .cvs file with numeric data

Here is code fragment that gets error:

from sklearn.tree import DecisionTreeClassifier
    model = DecisionTreeClassifier(random_state=123)
    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=132)
    train_scores, valid_scores = validation_curve(model, X, y, param_name="max_depth", n_jobs=-1,
       param_range=np.arange(1, 20), cv=10, scoring="accuracy")

Im working in Jupiter Lite.


问:
Pip error with requirements while deployng Django to Digital Ocean
I am trying to Deploy my Django API to a droplet in Digital Ocean, with ubuntu. I freezed my environment with pip freeze > requirements.txt command, and pulled it into the server. When I ask to install dependencies, into the activated virtual environment, with pip install -r requirements.txt it says that ERROR: Could not find a version that satisfies the requirement apturl (from versions: none) ERROR: No matching distribution found for apturl

If id does matter, here is the actual requirements file:

```<code>apturl
beautifulsoup4==4.11.1
blinker==1.4
Brlapi
certifi==2020.6.20
chardet==4.0.0
charset-normalizer==2.1.1
cliapp==1.20180812.1
click==8.0.3
colorama==0.4.4
command-not-found==0.3
cryptography==3.4.8
cupshelpers==1.0
dbus-python==1.2.18
defer==1.0.6
distlib==0.3.4
distro==1.7.0
distro-info===1.1build1
filelock==3.6.0
Flask==2.2.2
Flask-Login==0.6.2
Flask-SQLAlchemy==3.0.1
git-filter-repo==2.38.0
greenlet==1.1.3.post0
gunicorn==20.1.0
httplib2==0.20.2
idna==3.3
importlib-metadata==4.6.4
itsdangerous==2.1.2
jeepney==0.7.1
Jinja2==3.1.2
keyring==23.5.0
language-selector==0.1
launchpadlib==1.10.16
lazr.restfulclient==0.14.4
lazr.uri==1.0.6
llfuse==1.3.8
louis==3.20.0
macaroonbakery==1.3.1
Markdown==3.3.6
MarkupSafe==2.1.1
more-itertools==8.10.0
netifaces==0.11.0
oauthlib==3.2.0
olefile==0.46
pexpect==4.8.0
Pillow==9.0.1
pipenv==11.9.0
platformdirs==2.5.1
protobuf==3.12.4
psycopg2-binary==2.9.5
ptyprocess==0.7.0
pycairo==1.20.1
pycups==2.0.1
Pygments==2.11.2
PyGObject==3.42.1
PyJWT==2.3.0
pymacaroons==0.13.0
PyNaCl==1.5.0
pyparsing==2.4.7
pyRFC3339==1.1
python-apt==2.3.0+ubuntu2.1
python-dateutil==2.8.1
python-debian===0.1.43ubuntu1
python-dotenv==0.21.0
pytz==2022.1
pyxdg==0.27
PyYAML==5.4.1
reportlab==3.6.8
requests==2.28.1
SecretStorage==3.3.1
six==1.16.0
soupsieve==2.3.2.post1
SQLAlchemy==1.4.41
systemd-python==234
ttystatus==0.38
typing_extensions==4.4.0
ubuntu-advantage-tools==27.12
ubuntu-drivers-common==0.0.0
ufw==0.36.1
unattended-upgrades==0.1
urllib3==1.26.5
virtualenv==20.13.0+ds
virtualenv-clone==0.3.0
wadllib==1.3.6
Werkzeug==2.2.2
xdg==5
xkit==0.0.0
zipp==1.0.0
</code>```

I tried to install dependencies by hand, update pip and Python ( version 3.10 ), and build-essentials, but nothing worked. I deleted the versions from the file, and it didn't worked. I don't really know how to deal with these problem. Can someone please help me?

Body:
I am trying to Deploy my Django API to a droplet in Digital Ocean, with ubuntu. I freezed my environment with pip freeze > requirements.txt command, and pulled it into the server. When I ask to install dependencies, into the activated virtual environment, with pip install -r requirements.txt it says that ERROR: Could not find a version that satisfies the requirement apturl (from versions: none) ERROR: No matching distribution found for apturl

If id does matter, here is the actual requirements file:

apturl
beautifulsoup4==4.11.1
blinker==1.4
Brlapi
certifi==2020.6.20
chardet==4.0.0
charset-normalizer==2.1.1
cliapp==1.20180812.1
click==8.0.3
colorama==0.4.4
command-not-found==0.3
cryptography==3.4.8
cupshelpers==1.0
dbus-python==1.2.18
defer==1.0.6
distlib==0.3.4
distro==1.7.0
distro-info===1.1build1
filelock==3.6.0
Flask==2.2.2
Flask-Login==0.6.2
Flask-SQLAlchemy==3.0.1
git-filter-repo==2.38.0
greenlet==1.1.3.post0
gunicorn==20.1.0
httplib2==0.20.2
idna==3.3
importlib-metadata==4.6.4
itsdangerous==2.1.2
jeepney==0.7.1
Jinja2==3.1.2
keyring==23.5.0
language-selector==0.1
launchpadlib==1.10.16
lazr.restfulclient==0.14.4
lazr.uri==1.0.6
llfuse==1.3.8
louis==3.20.0
macaroonbakery==1.3.1
Markdown==3.3.6
MarkupSafe==2.1.1
more-itertools==8.10.0
netifaces==0.11.0
oauthlib==3.2.0
olefile==0.46
pexpect==4.8.0
Pillow==9.0.1
pipenv==11.9.0
platformdirs==2.5.1
protobuf==3.12.4
psycopg2-binary==2.9.5
ptyprocess==0.7.0
pycairo==1.20.1
pycups==2.0.1
Pygments==2.11.2
PyGObject==3.42.1
PyJWT==2.3.0
pymacaroons==0.13.0
PyNaCl==1.5.0
pyparsing==2.4.7
pyRFC3339==1.1
python-apt==2.3.0+ubuntu2.1
python-dateutil==2.8.1
python-debian===0.1.43ubuntu1
python-dotenv==0.21.0
pytz==2022.1
pyxdg==0.27
PyYAML==5.4.1
reportlab==3.6.8
requests==2.28.1
SecretStorage==3.3.1
six==1.16.0
soupsieve==2.3.2.post1
SQLAlchemy==1.4.41
systemd-python==234
ttystatus==0.38
typing_extensions==4.4.0
ubuntu-advantage-tools==27.12
ubuntu-drivers-common==0.0.0
ufw==0.36.1
unattended-upgrades==0.1
urllib3==1.26.5
virtualenv==20.13.0+ds
virtualenv-clone==0.3.0
wadllib==1.3.6
Werkzeug==2.2.2
xdg==5
xkit==0.0.0
zipp==1.0.0

I tried to install dependencies by hand, update pip and Python ( version 3.10 ), and build-essentials, but nothing worked. I deleted the versions from the file, and it didn't worked. I don't really know how to deal with these problem. Can someone please help me?


问:
Is there a fix to this BrokenProcessPool error with the Intel scikit-learn extension?
In order to perform a grid search with SVC using the Intel Extension for Scikit-Learn, I have tried this:

```<code>from sklearnex import patch_sklearn

patch_sklearn()

from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV, RandomizedSearchCV

## Prepare Train and Test datasets ##
print("Preparing Train and Test datasets")

X_train, X_test, y_train, y_test = prepare_train_test_data(data=data,
                                                            target_col='Asset_Label',
                                                            test_size=.25)

## Initialize SVC model ##
parameters = {
    'class_weight': 'balanced',
    'probability': True,
    'random_state': 21}

svc = SVC(**parameters)

## Tune Hyperparameters ##
strat_kfold = StratifiedKFold(n_splits=3, shuffle=True, random_state=21)
# print("\nTuning hyperparameters..")
grid = {
    'C': np.logspace(-1, 1, 5),
    'kernel': ['linear', 'poly', 'rbf', 'sigmoid']
    }

grid_search = RandomizedSearchCV(svc, param_distributions=grid,
                                    cv=strat_kfold, n_iter=5, scoring='roc_auc',
                                    verbose=1, n_jobs=-1, random_state=21)

grid_search.fit(X_train, y_train)
</code>```

Error:

```<code>...
BrokenProcessPool: A result has failed to un-serialize. Please ensure that the objects returned by the function are always picklable.
</code>```

Body:
In order to perform a grid search with SVC using the Intel Extension for Scikit-Learn, I have tried this:

from sklearnex import patch_sklearn

patch_sklearn()

from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV, RandomizedSearchCV

## Prepare Train and Test datasets ##
print("Preparing Train and Test datasets")

X_train, X_test, y_train, y_test = prepare_train_test_data(data=data,
                                                            target_col='Asset_Label',
                                                            test_size=.25)

## Initialize SVC model ##
parameters = {
    'class_weight': 'balanced',
    'probability': True,
    'random_state': 21}

svc = SVC(**parameters)

## Tune Hyperparameters ##
strat_kfold = StratifiedKFold(n_splits=3, shuffle=True, random_state=21)
# print("\nTuning hyperparameters..")
grid = {
    'C': np.logspace(-1, 1, 5),
    'kernel': ['linear', 'poly', 'rbf', 'sigmoid']
    }

grid_search = RandomizedSearchCV(svc, param_distributions=grid,
                                    cv=strat_kfold, n_iter=5, scoring='roc_auc',
                                    verbose=1, n_jobs=-1, random_state=21)

grid_search.fit(X_train, y_train)

Error:

...
BrokenProcessPool: A result has failed to un-serialize. Please ensure that the objects returned by the function are always picklable.


问:
Apache Spark Cluster\Windows: Getting Connection refused: no further information from worker node
I need help please getting spark working in windows cluster of 3 nodes. I am able to download and configure and run the master node and worker nodes. the worker nodes are registered successfully with the master. Im able to see both worker nodes in the Master UI. When I try to submit a job using:

spark-submit --master spark://IP:7077 hello_world.py

Spark continuously try to start multiple executors but the all failed with code exit 1 and it doesnt stop until I kill it. when I check the log in the UI for each worker Im seeing the following error:

```<code>

Using Spark's default log4j profile: org/apache/spark/log4j2-defaults.properties
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1894)
    at org.apache.spark.deploy.SparkHadoopUtil.runAsSparkUser(SparkHadoopUtil.scala:61)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend$.run(CoarseGrainedExecutorBackend.scala:424)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend$.main(CoarseGrainedExecutorBackend.scala:413)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend.main(CoarseGrainedExecutorBackend.scala)
Caused by: org.apache.spark.SparkException: Exception thrown in awaitResult:
    at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:301)
    at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:75)
    at org.apache.spark.rpc.RpcEnv.setupEndpointRefByURI(RpcEnv.scala:102)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend$.$anonfun$run$9(CoarseGrainedExecutorBackend.scala:444)
    at scala.runtime.java8.JFunction1$mcVI$sp.apply(JFunction1$mcVI$sp.java:23)
    at scala.collection.TraversableLike$WithFilter.$anonfun$foreach$1(TraversableLike.scala:985)
    at scala.collection.immutable.Range.foreach(Range.scala:158)
    at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:984)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend$.$anonfun$run$7(CoarseGrainedExecutorBackend.scala:442)
    at org.apache.spark.deploy.SparkHadoopUtil$$anon$1.run(SparkHadoopUtil.scala:62)
    at org.apache.spark.deploy.SparkHadoopUtil$$anon$1.run(SparkHadoopUtil.scala:61)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1878)
    ... 4 more
**Caused by: java.io.IOException: Failed to connect to <Master DNS>/<Master IP>:56785
    at **org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:288)
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:218)
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:230)
    at org.apache.spark.rpc.netty.NettyRpcEnv.createClient(NettyRpcEnv.scala:204)
    at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:202)
    at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:198)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: <Master DNS>/<Master IP>:56785
Caused by: java.net.ConnectException: Connection refused: no further information
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:715)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:330)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:710)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Im using Spark: spark-3.3.1-bin-hadoop3
Please help.
Thanks

The application to run

Body:
I need help please getting spark working in windows cluster of 3 nodes. I am able to download and configure and run the master node and worker nodes. the worker nodes are registered successfully with the master. Im able to see both worker nodes in the Master UI. When I try to submit a job using:

spark-submit --master spark://IP:7077 hello_world.py

Spark continuously try to start multiple executors but the all failed with code exit 1 and it doesnt stop until I kill it. when I check the log in the UI for each worker Im seeing the following error:

Using Spark's default log4j profile: org/apache/spark/log4j2-defaults.properties
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1894)
    at org.apache.spark.deploy.SparkHadoopUtil.runAsSparkUser(SparkHadoopUtil.scala:61)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend$.run(CoarseGrainedExecutorBackend.scala:424)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend$.main(CoarseGrainedExecutorBackend.scala:413)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend.main(CoarseGrainedExecutorBackend.scala)
Caused by: org.apache.spark.SparkException: Exception thrown in awaitResult:
    at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:301)
    at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:75)
    at org.apache.spark.rpc.RpcEnv.setupEndpointRefByURI(RpcEnv.scala:102)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend$.$anonfun$run$9(CoarseGrainedExecutorBackend.scala:444)
    at scala.runtime.java8.JFunction1$mcVI$sp.apply(JFunction1$mcVI$sp.java:23)
    at scala.collection.TraversableLike$WithFilter.$anonfun$foreach$1(TraversableLike.scala:985)
    at scala.collection.immutable.Range.foreach(Range.scala:158)
    at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:984)
    at org.apache.spark.executor.CoarseGrainedExecutorBackend$.$anonfun$run$7(CoarseGrainedExecutorBackend.scala:442)
    at org.apache.spark.deploy.SparkHadoopUtil$$anon$1.run(SparkHadoopUtil.scala:62)
    at org.apache.spark.deploy.SparkHadoopUtil$$anon$1.run(SparkHadoopUtil.scala:61)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1878)
    ... 4 more
**Caused by: java.io.IOException: Failed to connect to <Master DNS>/<Master IP>:56785
    at **org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:288)
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:218)
    at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:230)
    at org.apache.spark.rpc.netty.NettyRpcEnv.createClient(NettyRpcEnv.scala:204)
    at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:202)
    at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:198)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: <Master DNS>/<Master IP>:56785
Caused by: java.net.ConnectException: Connection refused: no further information
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:715)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:330)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:710)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:748)

Im using Spark: spark-3.3.1-bin-hadoop3
Please help.
Thanks

The application to run


问:
MERN - store user in backend after successful google login
I am pretty new to Programming and have some questions regarding the MERN stack.
I am building an app and trying to realize the log in via google. I was successful with integrating the google auth to my frontend and now I want to store the user after a successful login in the backend.

The first question I have is do I need a database to store the user, or is it common to just store them on the express backend?

In the auth process I do get the JWT from google and try sending it to the backend, but it does not work.
I do get the following error: "SyntaxError: Unexpected token o in JSON at position 1".

How can I send the JWT to the backend and check, if the user already exists in MongoDB and if he does not exist, make a new entry for the user. And when he is logged in, make a session so he does not have to log in again after every refresh.

At the moment I got the following code for the frontend:

```<code>import './App.css';
import { useEffect, useState } from 'react'
import jwt_decode from 'jwt-decode';
import Survey from './components/survey';

function App() {
  const [ user, setUser] = useState({});
  const [backendData, setBackendData] = useState([{}]);

  // fetch backend API, we can define relative route, as proxy is defined in package.json
  useEffect(() => {
    fetch("http://localhost:5000/api").then(
      response => response.json()
    ).then(
      data => {
        setBackendData(data)
      }
    )
  }, [])

  // store the JWT and decode it
  function handleCallBackResponse(response){
    console.log("Encoded JWT ID token: " + response.credential);
    var userObject = jwt_decode(response.credential);

    console.log(userObject);
    setUser(userObject);
    document.getElementById("signInDiv").hidden = true;

    fetch("http://localhost:5000/user", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },

      body: userObject,
    })
  }

// logout the user and show sign in button, google.accounts.id.disableAutoSelect is recording the status in cookies. This prevents a UX dead loop.
function handleSignOut(event){
 setUser({});
 document.getElementById("signInDiv").hidden = false;
 google.accounts.id.disableAutoSelect();
}

  useEffect(() => {
    /* global google */
    // The google.accounts.id.initialize method initializes the Sign In With Google client based on the configuration object.
    google.accounts.id.initialize({
      client_id: "CLIENT_ID",
      callback: handleCallBackResponse
    });

    // The google.accounts.id.renderButton method renders a Sign In With Google button in your web pages
    google.accounts.id.renderButton(
    document.getElementById("signInDiv"),
    // if only want to display icon
    //{theme: "outline", size: "medium", type: "icon"}
    {theme: "outline", size: "medium", text: "signin", shape: "square"}
  );
  // The google.accounts.id.prompt method displays the One Tap prompt or the browser native credential manager after the initialize() method is invoked.
  google.accounts.id.prompt();
  }, [])

  // If we have no user: show sign in button
  // if we have a user: show the log out button
  return (
    <div className="App">
      <div id = "signInDiv"/>
      { Object.keys(user).length !== 0 &&
        <button className ='signout' onClick={ (e) => handleSignOut(e)}>
          { user &&
          <img className='logout' alt="googleprofile" src={user.picture} width='30px' height='30px'></img>
          }
          </button>
      }
      <Survey></Survey>
      {(typeof backendData.users === 'undefined') ? (
        <p>Loading</p>
      ) : (
        backendData.users.map((user, i) => (
          <p key={i}>{user}</p>

        ))
      )}
    </div>
  );
}

export default App;

</code>```

Backend:

```<code>const express = require('express')
const morgan  = require('morgan')
const cors = require("cors")
const mongoose = require("mongoose")
const { OAuth2Client } = require("google-auth-library");
const jwt = require("jsonwebtoken");

const app = express()

const uri = "MONGODBURL"

// connect to mongoDB
async function connect() {
    try {
        await mongoose.connect(uri)
        console.log("Connected to MongoDB")
    } catch (error) {
        console.error(error)
    }
    }

connect()

// setup view engine, file in "views" folder needs to have ending .ejs
app.set('view engine', 'ejs')

// log requests in the terminal for troubleshooting
app.use(morgan('combined'))

// allow cors URLs
app.use(cors({
    origin: ['http://localhost:3000', 'https://play.google.com', 'https://accounts.google.com'],
    methods: ["GET", "POST", "PUT", "DELETE"],
    credentials: true
}))

app.use(express.json());

// start app on port 5000 and give an log message
app.listen(5000, () => {console.log("Server started on port 5000")  })
</code>```

Hope this make clear what I want to achieve. I really appreciate any help.

Kind Regards

Body:
I am pretty new to Programming and have some questions regarding the MERN stack.
I am building an app and trying to realize the log in via google. I was successful with integrating the google auth to my frontend and now I want to store the user after a successful login in the backend.

The first question I have is do I need a database to store the user, or is it common to just store them on the express backend?

In the auth process I do get the JWT from google and try sending it to the backend, but it does not work.
I do get the following error: "SyntaxError: Unexpected token o in JSON at position 1".

How can I send the JWT to the backend and check, if the user already exists in MongoDB and if he does not exist, make a new entry for the user. And when he is logged in, make a session so he does not have to log in again after every refresh.

At the moment I got the following code for the frontend:

import './App.css';
import { useEffect, useState } from 'react'
import jwt_decode from 'jwt-decode';
import Survey from './components/survey';

function App() {
  const [ user, setUser] = useState({});
  const [backendData, setBackendData] = useState([{}]);

  // fetch backend API, we can define relative route, as proxy is defined in package.json
  useEffect(() => {
    fetch("http://localhost:5000/api").then(
      response => response.json()
    ).then(
      data => {
        setBackendData(data)
      }
    )
  }, [])

  // store the JWT and decode it
  function handleCallBackResponse(response){
    console.log("Encoded JWT ID token: " + response.credential);
    var userObject = jwt_decode(response.credential);

    console.log(userObject);
    setUser(userObject);
    document.getElementById("signInDiv").hidden = true;

    fetch("http://localhost:5000/user", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },

      body: userObject,
    })
  }

// logout the user and show sign in button, google.accounts.id.disableAutoSelect is recording the status in cookies. This prevents a UX dead loop.
function handleSignOut(event){
 setUser({});
 document.getElementById("signInDiv").hidden = false;
 google.accounts.id.disableAutoSelect();
}

  useEffect(() => {
    /* global google */
    // The google.accounts.id.initialize method initializes the Sign In With Google client based on the configuration object.
    google.accounts.id.initialize({
      client_id: "CLIENT_ID",
      callback: handleCallBackResponse
    });

    // The google.accounts.id.renderButton method renders a Sign In With Google button in your web pages
    google.accounts.id.renderButton(
    document.getElementById("signInDiv"),
    // if only want to display icon
    //{theme: "outline", size: "medium", type: "icon"}
    {theme: "outline", size: "medium", text: "signin", shape: "square"}
  );
  // The google.accounts.id.prompt method displays the One Tap prompt or the browser native credential manager after the initialize() method is invoked.
  google.accounts.id.prompt();
  }, [])

  // If we have no user: show sign in button
  // if we have a user: show the log out button
  return (

      { Object.keys(user).length !== 0 &&
        <button className ='signout' onClick={ (e) => handleSignOut(e)}>
          { user &&

          }
          </button>
      }
      <Survey></Survey>
      {(typeof backendData.users === 'undefined') ? (

Loading

      ) : (
        backendData.users.map((user, i) => (

{user}

        ))
      )}

  );
}

export default App;

Backend:

const express = require('express')
const morgan  = require('morgan')
const cors = require("cors")
const mongoose = require("mongoose")
const { OAuth2Client } = require("google-auth-library");
const jwt = require("jsonwebtoken");

const app = express()

const uri = "MONGODBURL"

// connect to mongoDB
async function connect() {
    try {
        await mongoose.connect(uri)
        console.log("Connected to MongoDB")
    } catch (error) {
        console.error(error)
    }
    }

connect()

// setup view engine, file in "views" folder needs to have ending .ejs
app.set('view engine', 'ejs')

// log requests in the terminal for troubleshooting
app.use(morgan('combined'))

// allow cors URLs
app.use(cors({
    origin: ['http://localhost:3000', 'https://play.google.com', 'https://accounts.google.com'],
    methods: ["GET", "POST", "PUT", "DELETE"],
    credentials: true
}))

app.use(express.json());

// start app on port 5000 and give an log message
app.listen(5000, () => {console.log("Server started on port 5000")  })

Hope this make clear what I want to achieve. I really appreciate any help.

Kind Regards


问:
Facebook Graph API - Cannot GET appassets edge for my Instant Game App
I'm sending request to appassets edge endpoint, using user access token (I'm the owner ``of the app):

```<code>curl -i -X GET \
 "https://graph.fb.gg/v15.0/1172368406965046/appassets?access_token=USER_ACCESS_TOKEN"
</code>```

Instead of a list of assets I'm getting following error:

```<code>{
  "error": {
    "message": "Tried accessing nonexisting field (appassets) on node type (Application)",
    "type": "FacebookApiException",
    "code": 100,
    "fbtrace_id": "AaJwxbXg7TKHb0EE53NLr0K"
  }
}
</code>```

How can I reach my app assets?

Body:
I'm sending request to appassets edge endpoint, using user access token (I'm the owner ``of the app):

curl -i -X GET \
 "https://graph.fb.gg/v15.0/1172368406965046/appassets?access_token=USER_ACCESS_TOKEN"

Instead of a list of assets I'm getting following error:

{
  "error": {
    "message": "Tried accessing nonexisting field (appassets) on node type (Application)",
    "type": "FacebookApiException",
    "code": 100,
    "fbtrace_id": "AaJwxbXg7TKHb0EE53NLr0K"
  }
}

How can I reach my app assets?


问:
How do you change the source list of a customlist field in SuiteScript
I am trying to change the source list of one customlist field for an item, when a value on another list is selected. For example if list one is selected as "dairy", I want the options in list two to be "milk, yogurt, etc.", but if I chose "protein", I want the options in list two to be "eggs, steak, etc.".

```<code>/**
 * @NApiVersion 2.0
 * @NScriptType ClientScript
 * @NModuleScope Public
 */

define(['N/record'], function (r){
    function configureRecyclingDropDownLists(context) {
        var curRecord = context.currentRecord;
        var ddl1Value = curRecord.getValue({
            fieldid: "custitem_recycling_categories"
        });
        var custListRec;
        switch (ddl1Value) {
            case 'Ferrous (steel)':
                var custListRecId = "customlist_ferrous_child_category";
                //custListRec = r.load({type: r.Type.customlist, id: customlist_ferrous_child_category});
                break;
            case 'Non-Ferrous (aluminum)':
                var custListRecId = "customlist_non_ferrous_child_category";
                //custListRec = r.load({type: r.Type.customlist, id: customlist_non_ferrous_child_category});
                break;
        }
        curRecord.setValue({
            fieldid: "custitem_recycling_sub_category",
            sublistId: custListRecId,
            ignoreFieldChange: true
        });
    }

    return{
        fieldChanged: configureRecyclingDropDownLists
    };

});
</code>```

This is my current attempt. I think that "setValue" should maybe be "setSublist", but when trying that did not work either. The commented out lines for each case was my first attempt where I was setting the value (curRecord field value) equal to the custListRec.value, but that did not seem correct either.

Any direction in how I could progress would be greatly appreciated. Thank you.

Body:
I am trying to change the source list of one customlist field for an item, when a value on another list is selected. For example if list one is selected as "dairy", I want the options in list two to be "milk, yogurt, etc.", but if I chose "protein", I want the options in list two to be "eggs, steak, etc.".

/**
 * @NApiVersion 2.0
 * @NScriptType ClientScript
 * @NModuleScope Public
 */

define(['N/record'], function (r){
    function configureRecyclingDropDownLists(context) {
        var curRecord = context.currentRecord;
        var ddl1Value = curRecord.getValue({
            fieldid: "custitem_recycling_categories"
        });
        var custListRec;
        switch (ddl1Value) {
            case 'Ferrous (steel)':
                var custListRecId = "customlist_ferrous_child_category";
                //custListRec = r.load({type: r.Type.customlist, id: customlist_ferrous_child_category});
                break;
            case 'Non-Ferrous (aluminum)':
                var custListRecId = "customlist_non_ferrous_child_category";
                //custListRec = r.load({type: r.Type.customlist, id: customlist_non_ferrous_child_category});
                break;
        }
        curRecord.setValue({
            fieldid: "custitem_recycling_sub_category",
            sublistId: custListRecId,
            ignoreFieldChange: true
        });
    }

    return{
        fieldChanged: configureRecyclingDropDownLists
    };

});

This is my current attempt. I think that "setValue" should maybe be "setSublist", but when trying that did not work either. The commented out lines for each case was my first attempt where I was setting the value (curRecord field value) equal to the custListRec.value, but that did not seem correct either.

Any direction in how I could progress would be greatly appreciated. Thank you.


问:
Sqlalchemy - Can flushed data be shared bewteen transactions using read uncommited isolation level?
I am trying to read data from a table, but this data was not commited only flushed. How can I read this record?

This read is important to my integration test to work, I already set the engine isolation level to read uncommited, but is not working.

from __future__ import absolute_import
import os

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine(
    "url",
    pool_size=os.getenv('POOL_SIZE', 20),
    max_overflow=10,
    isolation_level="READ UNCOMMITTED")

def get_engine():
    Session = sessionmaker(bind=engine)
    return Session()

```

Read the flushed data.

Body:
I am trying to read data from a table, but this data was not commited only flushed. How can I read this record?

This read is important to my integration test to work, I already set the engine isolation level to read uncommited, but is not working.

from __future__ import absolute_import
import os

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine(
    "url",
    pool_size=os.getenv('POOL_SIZE', 20),
    max_overflow=10,
    isolation_level="READ UNCOMMITTED")

def get_engine():
    Session = sessionmaker(bind=engine)
    return Session()

Read the flushed data.