2022-04-30

How to make one dropdown menu dependent on another

I have a dropdown menu showing states and counties. I want the county one to be dependent on the state one. I am using react, javascript, prisma to access the database. I made it work separated, so I can get the states to show and the counties, but I don't know how to make them dependent. What I think I need is a way to change my function that bring the county data. I can group by the state that was selected. So what I need is after getting the state that was selected to send that to my "byCounty" function. Is that possible?

menu.js

export default function DropDownMenu(props){
    if(!props.states) return
    return(
        <table>
            <body>
            <select onChange={(e) => { console.log(e.target.value) }}>
                {props.states.map(states=>
                    <option>{states.state}</option>
                )}
            </select>
            <select >
                {props.byCounty.map(byCounty=>
                    <option>{byCounty.county}</option>
                )}
            </select>
            </body>
        </table>
    )
}

functions.js

const states = await prisma.county.groupBy({
        by:["state"],
        where: {
            date: dateTime,
        },
        _sum:{
            cases:true,
        },
    });

 const byCounty = await prisma.county.groupBy({
        by:["county"],
        where: {
            date: dateTime,
            state: 'THIS SHOULD BE THE STATE NAME SELECTED BY USER'
        },
        _sum:{
            cases:true,
        },
    });

const result =JSON.stringify(
        {states:states, byCounty:byCounty},
        (key, value) => (typeof value === 'bigint' ? parseInt(value) : value) // return everything else unchanged
      )
    res.json(result);

index.js

<div className={styles.table_container}>
                    <h2>Teste</h2>
                    <DropDownMenu states={myData?myData.states:[]} byCounty={myData?myData.byCounty:[]}></DropDownMenu>
              </div>

What I have:

enter image description here



How to use Ray with sklearn?

I have a hard time using Ray with sklearn, what is the best practices for using it with Ray? And bonus question, how do you integrate that with MLFlow?



How to set substring statement as valid column name in SQL Server

I have a code like the following:

INSERT INTO [TranslateValidate]..[Policy] ([BirthDate],[FirstName],[LastName])
  SELECT
    [Table2309].[DOB],
    SUBSTRING(Full_Name, CHARINDEX(',', Full_Name) + 2, LEN(Full_Name)),
    SUBSTRING(Full_Name, 0, CHARINDEX(',', Full_Name))  
  FROM [Table2309] AS [Table2309]
  WHERE [Table2309].[clientid] = (SELECT
    MIN(clientid)
  FROM Table2309 T
  WHERE T.Date_of_Birth = Table2309.Date_of_Birth
  AND T.Substring(Full_Name, CHARINDEX(',', Full_Name) + 2, LEN(Full_Name)) = Table2309.Substring(Full_Name, CHARINDEX(',', Full_Name) + 2, LEN(Full_Name))
  AND T.Substring(Full_Name, 0, CHARINDEX(',', Full_Name)) = Table2309.Substring(Full_Name, 0, CHARINDEX(',', Full_Name))

This would have an error message

Cannot find either column "c" or the user-defined function or aggregate "c.Substring", or the name is ambiguous.

If I add [] for Substring part, this would should error message

Invalid column name 'Substring(Full_Name,...

How do I resolve this problem?



How to get text from the DOM element in cypress

I am new in cypress, I want to create a dynamic method that returns the text of whatever DOM element pass on it, so I have created one but it returns some unexpected result please see the below code and suggest to me where I am doing wrong or what is the best option for achieving this task.

login_objrepo.json

{
  "Signin_lbl":".login100-form-title.p-b-10"  //Locator
}

Login.sepc.js

import commonUtility from "../../support/commonUtility";
const util = new commonUtility();
const objLogin = require('../../fixtures/login_objrepo');

    describe('Login Page', function () {
        it('Verify Page', () => {
            util.openUrl(objLogin.URL);
            const exp = 'Sign In';
            const act = util.getText(objLogin.Signin_lbl);
            cy.log("Exp title=" + exp + " and Act=" + act)
            cy.get(objLogin.Signin_lbl).should('have.text',exp);
        })
    })

commonUtility.js

 class commonUtility
    {
     getText(locator)
        {
            cy.wait(3000);
            
            cy.get(locator).then(($attribute)=> {
                let txt=$attribute.text();
                cy.log("Retun Text is = "+ txt);
            })
            return this;
        }
    }

here (txt variable) got the valid text but, in the above file(Login.sepc.js) were to call it there showing ([object Object])... how to get the same here also?

========================== OUTPUT

enter image description here



Having trouble using winapi to read input from a device

I followed the steps here to try and read some input from a device. I've been trying for a couple hours now to figure out why GetMessage doesn't return anything. Originally I was trying to read from a certain device, but seeing as that wasn't working, I wanted to just try reading keyboard or mouse inputs. However, I've had no luck in doing so.

Edit: Some more info. I'm on Windows 10. I'm running the code in cmder (not sure if that makes any difference) with python main.py. There are no error messages and the output is Successfully registered input device! before the program just waits to receive a message from GetMessage.

Here's the running code:

main.py:

from ctypes import windll, sizeof, WinDLL, pointer, c_uint, create_string_buffer, POINTER
from ctypes.wintypes import *
from structures import *
from constants import *  # I put a comment specifying the value for each variable used from here


k32 = WinDLL('kernel32')
GetRawInputDeviceInfo = windll.user32.GetRawInputDeviceInfoA
GetRawInputDeviceInfo.argtypes = HANDLE, UINT, LPVOID, PUINT
RegisterRawInputDevices = windll.user32.RegisterRawInputDevices
RegisterRawInputDevices.argtypes = (RawInputDevice * 7), UINT, UINT
GetMessage = windll.user32.GetMessageA
GetMessage.argtypes = POINTER(Message), HWND, UINT, UINT


def print_error(code=None):
    print(f"Error code {k32.GetLastError() if code is None else code}")


def register_devices(hwnd_target=None):
    # Here I added all usages just to try and get any kind of response from GetMessage
    page = 0x01
    # DW_FLAGS is 0
    devices = (RawInputDevice * 7)(
        RawInputDevice(page, 0x01, DW_FLAGS, hwnd_target),
        RawInputDevice(page, 0x02, DW_FLAGS, hwnd_target),
        RawInputDevice(page, 0x04, DW_FLAGS, hwnd_target),
        RawInputDevice(page, 0x05, DW_FLAGS, hwnd_target),
        RawInputDevice(page, 0x06, DW_FLAGS, hwnd_target),
        RawInputDevice(page, 0x07, DW_FLAGS, hwnd_target),
        RawInputDevice(page, 0x08, DW_FLAGS, hwnd_target),
    )
    if not RegisterRawInputDevices(devices, len(devices), sizeof(devices[0])):
        print_error()
    else:
        print("Successfully registered input device!")


def get_message(h_wnd=None):
    msg = pointer(Message())
    # WM_INPUT is 0
    return_value = GetMessage(msg, h_wnd, WM_INPUT, WM_INPUT)
    if return_value == -1:
        print_error()
    elif return_value == 0:
        print("WM_QUIT message received.")
    else:
        print("Successfully got message!")
        return msg


register_devices()
print(get_message().contents.message)

structures.py:

from ctypes import Structure
from ctypes.wintypes import *


class RawInputDevice(Structure):
    _fields_ = [
        ("usUsagePage", USHORT),
        ("usUsage", USHORT),
        ("dwFlags", DWORD),
        ("hwndTarget", HWND),
    ]


class Message(Structure):
    _fields_ = [
        ("hwnd", HWND),
        ("message", UINT),
        ("wParam", WPARAM),
        ("lParam", LPARAM),
        ("time", DWORD),
        ("pt", POINT),
        ("lPrivate", DWORD)
    ]

I'd appreciate it if anyone helped me figure out what's going wrong, or I'd also be fine if someone can point out an alternative to reading input from an HID device on Windows.



IIS Express w/ VS 2022 crashes when debugging web app and selecting file via file html input on page w/ ExtJs

Here are the details:

  • OS: Windows 2016 server accessed over RD
  • Dev tools: VS 2022 17.1.6 & VS 2019 16.11.11. I run VS in Admin mode (both)
  • IIS Express version: 10.0.22489.1000, 64 bit
  • Browser Chrome: 100.0.4896.127 (Official Build) (64-bit)
  • App:.net 4 webforms application that uses ExtJs 6.6.0 classic as front end
  • Antivirus: CrowdStrike, version 6.36.15005.0.

I have a form with a file field. This link has more information on how the upload works, it basically uses an iframe under the hood.

Now, in VS 2019 the upload works. In VS 2022 the upload doesn't work anymore and it returns the error: "Blocked a frame with origin "http://localhost:38991" from accessing a cross-origin frame." (the error is returned in the client JavaScript code). Just to be clear, I open exactly the same project in VS 2019 and it works, then I open the project in VS 2022 and the uploads don't work anymore.

Both use the same IIS Express process (64 bit). And one minor detail, the upload operation when run from VS 2022 kills IIS Express, it basically evaporates.

Any idea on how to fix this in VS 2022? For now, I have to use VS 2019 in order to be able to test uploads.

Thanks in advance.

Update: I installed VS 2022 version 17.1.6.

Initially I thought IIS express evaporates upon uploading the file. It actually exits when I select the file in the Open dialog.

The program '[19000] iisexpress.exe' has exited with code 4294967295 (0xffffffff).

When I run the project without debugging, it works fine!

I changed the title of the post from:

ExtJs file upload getting: "Blocked a frame with origin "http://localhost:38991" from accessing a cross-origin frame." when run w/ VS 2022 IIS Express

to

IIS Express w/ VS 2022 crashes when debugging web app and selecting file via file html input on page w/ ExtJs



Openpyxl - Merge same cells in column

I'm having trouble making a function that looks through a column (or each column) in the dataframe I'm writing and merging consecutive cells ie.

enter image description here

Would appreciate the help if anyone has done something like this. I've seen one response that uses pandas ExcelWriter, but don't think this is what I'm looking for.



2022-04-29

How to change default time of tkTimePicker analog clock

I am using the Analog Picker from tkTimePicker. The default time (the time that it shows initially) is 12:59 AM. I want to be able to change the default time to what the user saved it previously.

My current code for showing the time picker is:

from tkinter import *
from tktimepicker import AnalogPicker, AnalogThemes, constants
def editTime():
    editTimeWindow = Toplevel(window)
    time_picker = AnalogPicker(editTimeWindow, type=constants.HOURS12)
    time_picker.pack(expand=True, fill="both")
    theme = AnalogThemes(time_picker)
    theme.setNavyBlue()
    editTimeWindow.mainloop()

editTime()

image from https://github.com/PaulleDemon/tkTimePicker/blob/master/Readme.md

Is there a way to change the default time?



Reading comma-separated words from a file

FILE* inp;
inp = fopen("wordlist.txt","r");        //filename of your data file
char arr[100][5];           //max word length 5
int i = 0;
while(1){
    char r = (char)fgetc(inp);
    int k = 0;
    while(r!=',' && !feof(inp)){    //read till , or EOF
        arr[i][k++] = r;            //store in array
        r = (char)fgetc(inp);
    }
    arr[i][k]=0;        //make last character of string null
    if(feof(inp)){      //check again for EOF
        break;
    }
    i++;
}

I am reading the file words and storing them in the array. My question is: how can I randomly select 7 of these words and store them in the array?

The input file has the following content:

https://ibb.co/LkSJ1SV

meal
cheek
lady
debt
lab
math
basis
beer
bird
thing
mall
exam
user
news
poet
scene
truth
tea
way
tooth
cell
oven


Android Studio "Intent" not working even after importing "android.content.Intent"

I am trying out a very simple intent example follow this youtube video. However, i facing a very weird error where this particular line cannot work:

Intent myIntent = new Intent(this, DisplayActivity.class)

It provide me error as shown in the picture: Error

I also had tried out the "bulb" button in AS to debug it but it didn't show me a valid solution. The suggested action is as shown in the picture Original AS code editor image

The full code is shown below:

package com.example.parcelsort_ar

import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.budiyev.android.codescanner.*
import com.example.parcelsort_ar.databinding.ActivityMainBinding
import android.content.Intent

private const val CAMERA_REQUEST_CODE = 101

class MainActivity : AppCompatActivity() {
    private lateinit var codeScanner: CodeScanner
    private lateinit var binding: ActivityMainBinding 
    val btn_click_me = findViewById(R.id.idBtnPost) as Button

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

            //View binding
            binding = ActivityMainBinding.inflate(layoutInflater)
            val view = binding.root
            setContentView(view)

            binding.idBtnPost.setOnClickListener {
                openActivity2();
            }

  
            setupPermission()
            codeScanner()
    }

    public fun openActivity2() {
        Intent myIntent = new Intent(this, DisplayActivity.class);
        startActivity(intent);
    }
}

I had spending almost a day searching online but couldn't found any issue that meet my problem. Any help is aprreciated.



How to Get web data based on link in excel cell?

I'd like to create an Excel sheet, where in one column there is a link to a website like this: enter image description here

Link in column A where there is a MAC add in that url that changes from line to line rest of link is geraric. and it takes the info in the 2 lines marked with arrows and put into another cell. This should be possible for multiple links in different rows from websites with the same structure.

How can I make the web query to be based on the link in the adjacent cell?



How do i copy the all worksheets using xlwings module in python?

I have a macro excel file, it's having 3 worksheets. I need to saveas or copy all worksheets to new excel sheet. How to do in python using xlwing module?



How to reduce processing time of a code in R

Can you help me think of some way to reduce the computational time of a code that generates a certain value, which in this case I call coef, which will depend on id/date/category? Better explanations below.

I made two functions that generate the same result. As you can see in benchmark, the first function (return_values) takes twice as long as the second function (return_valuesX) to generate the same results. See that in the second function, I make some brief changes when calculating the coef variable. However, I strongly believe that there is a possibility of improving the code, as you can see in the second function, I managed to improve 50% of processing time compared to the first just with brief changes. But I'm out of ideas for new adjustments, so I would like your valuable opinion.

Code Explanations:

In general, the purpose of the code is to calculate a value, which I call a coef for each group of id, date and category. For this, the median of the values ​​resulting from the subtraction between DR1 and the values ​​of the DRM0 columns of the df1 database is first calculated. After obtaining the median (med variable), I add the values ​​found with the values ​​of the DRM0 columns of my df1 database. This calculation is my SPV variable. In both cases, I used the data.table function, which I believe is faster than using dplyr. After I get SPV, I need to calculate the coef variable for each id/date/category.

Below I will insert an example real easy to understand of the coef calculation. If for example I want to calculate coef of idd<-"3", dmda<-"2021-12-03", CategoryChosse<-"ABC", and I have the following:

> SPV %>% filter(Id==idd, date2 == ymd(dmda), Category == CategoryChosse)

 Id      date1      date2   Week Category DRM001_PV DRM002_PV DRM003_PV DRM004_PV DRM005_PV DRM006_PV DRM007_PV DRM008_PV DRM009_PV DRM010_PV DRM011_PV DRM012_PV
1:  3 2021-12-01 2021-12-03 Monday      ABC        -3       374       198        17       537       -54       330      -136      -116       534        18      -199
   DRM013_PV DRM014_PV DRM015_PV DRM016_PV DRM017_PV DRM018_PV DRM019_PV DRM020_PV DRM021_PV DRM022_PV DRM023_PV DRM024_PV DRM025_PV DRM026_PV DRM027_PV DRM028_PV
1:       106       106       349        76       684       390       218       146       141        20       435       218       372       321       218       218
   DRM029_PV DRM030_PV DRM031_PV DRM032_PV DRM033_PV DRM034_PV DRM035_PV DRM036_PV DRM037_PV DRM038_PV DRM039_PV DRM040_PV DRM041_PV DRM042_PV DRM043_PV DRM044_PV
1:        55       455        46       411       262       449       325       467        43      -114       191       167        63      -123       252       218
   DRM045_PV DRM046_PV DRM047_PV DRM048_PV DRM049_PV DRM050_PV DRM051_PV DRM052_PV DRM053_PV DRM054_PV DRM055_PV DRM056_PV DRM057_PV DRM058_PV DRM059_PV DRM060_PV
1:       305       420      -296       596       200       218       190       203       607       218       442       -72       463       129       -39       333
   DRM061_PV DRM062_PV DRM063_PV DRM064_PV DRM065_PV DRM066_PV DRM067_PV DRM068_PV DRM069_PV DRM070_PV DRM071_PV DRM072_PV DRM073_PV DRM074_PV DRM075_PV DRM076_PV
1:       -26       160       -91       326       218       369       317       476       224        61       195       613       342       218       204       521
   DRM077_PV DRM078_PV DRM079_PV DRM080_PV DRM081_PV DRM082_PV DRM083_PV DRM084_PV DRM085_PV DRM086_PV DRM087_PV DRM088_PV DRM089_PV DRM090_PV DRM091_PV DRM092_PV
1:       588       218       449       340        51       508       -72        42       492       510       328       818      -132      -105       210      -102
   DRM093_PV DRM094_PV DRM095_PV DRM096_PV DRM097_PV DRM098_PV DRM099_PV DRM0100_PV DRM0101_PV DRM0102_PV DRM0103_PV DRM0104_PV DRM0105_PV DRM0106_PV DRM0107_PV
1:      -137        94       639       265       -64       512        32        -53        414        340        -16        471        434        150        267
   DRM0108_PV DRM0109_PV DRM0110_PV DRM0111_PV DRM0112_PV DRM0113_PV DRM0114_PV DRM0115_PV DRM0116_PV DRM0117_PV DRM0118_PV DRM0119_PV DRM0120_PV DRM0121_PV DRM0122_PV
1:        383       -162        434       -134        -39        450        212        146        -26          8        222        341        601        239         57
   DRM0123_PV DRM0124_PV DRM0125_PV DRM0126_PV DRM0127_PV DRM0128_PV DRM0129_PV DRM0130_PV DRM0131_PV DRM0132_PV DRM0133_PV DRM0134_PV DRM0135_PV DRM0136_PV DRM0137_PV
1:        484        239        502        415        504         62        487        168        101        319        365         37        218        -50        230
   DRM0138_PV DRM0139_PV DRM0140_PV DRM0141_PV DRM0142_PV DRM0143_PV DRM0144_PV DRM0145_PV DRM0146_PV DRM0147_PV DRM0148_PV DRM0149_PV DRM0150_PV DRM0151_PV DRM0152_PV
1:        493        159        150        132         58         21        468        -81         27        345        107        148        -66       -146       -185
   DRM0153_PV DRM0154_PV DRM0155_PV DRM0156_PV DRM0157_PV DRM0158_PV DRM0159_PV DRM0160_PV DRM0161_PV DRM0162_PV DRM0163_PV DRM0164_PV DRM0165_PV DRM0166_PV DRM0167_PV
1:        -14        562         68        140        353        120        130        301         76        441        218        370        218        378        -22
   DRM0168_PV DRM0169_PV DRM0170_PV DRM0171_PV DRM0172_PV DRM0173_PV DRM0174_PV DRM0175_PV DRM0176_PV DRM0177_PV DRM0178_PV DRM0179_PV DRM0180_PV DRM0181_PV DRM0182_PV
1:       -279        563        628        600        152        218        445        246        420         94        495        509        356        183        326
   DRM0183_PV DRM0184_PV DRM0185_PV DRM0186_PV DRM0187_PV DRM0188_PV DRM0189_PV DRM0190_PV DRM0191_PV DRM0192_PV DRM0193_PV DRM0194_PV DRM0195_PV DRM0196_PV DRM0197_PV
1:        493       -190        -65       -123        376        357        473        112        -69        471        452        221        165        -44         87
   DRM0198_PV DRM0199_PV DRM0200_PV DRM0201_PV DRM0202_PV DRM0203_PV DRM0204_PV DRM0205_PV DRM0206_PV DRM0207_PV DRM0208_PV DRM0209_PV DRM0210_PV DRM0211_PV DRM0212_PV
1:        239        285        521        -65        158        223        160        223        269         57        218        218        102        329        218
   DRM0213_PV DRM0214_PV DRM0215_PV DRM0216_PV DRM0217_PV DRM0218_PV DRM0219_PV DRM0220_PV DRM0221_PV DRM0222_PV DRM0223_PV DRM0224_PV DRM0225_PV DRM0226_PV DRM0227_PV
1:        769        215        -68        218        347         18        218        547        759        278        -80        -37        629        -16        774
   DRM0228_PV DRM0229_PV DRM0230_PV DRM0231_PV DRM0232_PV DRM0233_PV DRM0234_PV DRM0235_PV DRM0236_PV DRM0237_PV DRM0238_PV DRM0239_PV DRM0240_PV DRM0241_PV DRM0242_PV
1:        364        113       -132         31        536        118        248        385        218        202        218         41         23        218        379
   DRM0243_PV DRM0244_PV DRM0245_PV DRM0246_PV DRM0247_PV DRM0248_PV DRM0249_PV DRM0250_PV DRM0251_PV DRM0252_PV DRM0253_PV DRM0254_PV DRM0255_PV DRM0256_PV DRM0257_PV
1:       -158        462        600        221        218        221        442        218         53        218        176        504        -61         78         68
   DRM0258_PV DRM0259_PV DRM0260_PV DRM0261_PV DRM0262_PV DRM0263_PV DRM0264_PV DRM0265_PV DRM0266_PV DRM0267_PV DRM0268_PV DRM0269_PV DRM0270_PV DRM0271_PV DRM0272_PV
1:        493        403        218        339        299        749        -18        465        686       -215        579        307        366        279         94
   DRM0273_PV DRM0274_PV DRM0275_PV DRM0276_PV DRM0277_PV DRM0278_PV DRM0279_PV DRM0280_PV DRM0281_PV DRM0282_PV DRM0283_PV DRM0284_PV DRM0285_PV DRM0286_PV DRM0287_PV
1:        138         56        459        613        219        400         35        -74        516        218        -80        317        310       -231        229
   DRM0288_PV DRM0289_PV DRM0290_PV DRM0291_PV DRM0292_PV DRM0293_PV DRM0294_PV DRM0295_PV DRM0296_PV DRM0297_PV DRM0298_PV DRM0299_PV DRM0300_PV DRM0301_PV DRM0302_PV
1:        345        -70        619        235        122         61        337       -163        210        586        127       -112        368        365        476
   DRM0303_PV DRM0304_PV DRM0305_PV DRM0306_PV DRM0307_PV DRM0308_PV DRM0309_PV DRM0310_PV DRM0311_PV DRM0312_PV DRM0313_PV DRM0314_PV DRM0315_PV DRM0316_PV DRM0317_PV
1:        240        270        497         97        420       -184        212        -28        151        527        186        -32         60         96        -86
   DRM0318_PV DRM0319_PV DRM0320_PV DRM0321_PV DRM0322_PV DRM0323_PV DRM0324_PV DRM0325_PV DRM0326_PV DRM0327_PV DRM0328_PV DRM0329_PV DRM0330_PV DRM0331_PV DRM0332_PV
1:        454        321        300        552        319        134        -63        622        441        297        507        578        198        360        542
   DRM0333_PV DRM0334_PV DRM0335_PV DRM0336_PV DRM0337_PV DRM0338_PV DRM0339_PV DRM0340_PV DRM0341_PV DRM0342_PV DRM0343_PV DRM0344_PV DRM0345_PV DRM0346_PV DRM0347_PV
1:        153        318         68        763        370        337        633        469        453        146        428        418        169        468        526
   DRM0348_PV DRM0349_PV DRM0350_PV DRM0351_PV DRM0352_PV DRM0353_PV DRM0354_PV DRM0355_PV DRM0356_PV DRM0357_PV DRM0358_PV DRM0359_PV DRM0360_PV DRM0361_PV DRM0362_PV
1:        441        674         21       -182        174        153       -158        268        191        460         10         82        543       -193        218
   DRM0363_PV DRM0364_PV DRM0365_PV
1:       -203        269        479
> SPV %>% filter(Id==idd, date2 == ymd(dmda), Category == CategoryChosse)
   Id      date1      date2   Week Category DRM001_PV DRM002_PV DRM003_PV DRM004_PV DRM005_PV DRM006_PV DRM007_PV DRM008_PV DRM009_PV DRM010_PV DRM011_PV DRM012_PV
1:  3 2021-12-01 2021-12-03 Monday      ABC        -3       374       198        17       537       -54       330      -136      -116       534        18      -199
   DRM013_PV DRM014_PV DRM015_PV DRM016_PV DRM017_PV DRM018_PV DRM019_PV DRM020_PV DRM021_PV DRM022_PV DRM023_PV DRM024_PV DRM025_PV DRM026_PV DRM027_PV DRM028_PV
1:       106       106       349        76       684       390       218       146       141        20       435       218       372       321       218       218
   DRM029_PV DRM030_PV DRM031_PV DRM032_PV DRM033_PV DRM034_PV DRM035_PV DRM036_PV DRM037_PV DRM038_PV DRM039_PV DRM040_PV DRM041_PV DRM042_PV DRM043_PV DRM044_PV
1:        55       455        46       411       262       449       325       467        43      -114       191       167        63      -123       252       218
   DRM045_PV DRM046_PV DRM047_PV DRM048_PV DRM049_PV DRM050_PV DRM051_PV DRM052_PV DRM053_PV DRM054_PV DRM055_PV DRM056_PV DRM057_PV DRM058_PV DRM059_PV DRM060_PV
1:       305       420      -296       596       200       218       190       203       607       218       442       -72       463       129       -39       333
   DRM061_PV DRM062_PV DRM063_PV DRM064_PV DRM065_PV DRM066_PV DRM067_PV DRM068_PV DRM069_PV DRM070_PV DRM071_PV DRM072_PV DRM073_PV DRM074_PV DRM075_PV DRM076_PV
1:       -26       160       -91       326       218       369       317       476       224        61       195       613       342       218       204       521
   DRM077_PV DRM078_PV DRM079_PV DRM080_PV DRM081_PV DRM082_PV DRM083_PV DRM084_PV DRM085_PV DRM086_PV DRM087_PV DRM088_PV DRM089_PV DRM090_PV DRM091_PV DRM092_PV
1:       588       218       449       340        51       508       -72        42       492       510       328       818      -132      -105       210      -102
   DRM093_PV DRM094_PV DRM095_PV DRM096_PV DRM097_PV DRM098_PV DRM099_PV DRM0100_PV DRM0101_PV DRM0102_PV DRM0103_PV DRM0104_PV DRM0105_PV DRM0106_PV DRM0107_PV
1:      -137        94       639       265       -64       512        32        -53        414        340        -16        471        434        150        267
   DRM0108_PV DRM0109_PV DRM0110_PV DRM0111_PV DRM0112_PV DRM0113_PV DRM0114_PV DRM0115_PV DRM0116_PV DRM0117_PV DRM0118_PV DRM0119_PV DRM0120_PV DRM0121_PV DRM0122_PV
1:        383       -162        434       -134        -39        450        212        146        -26          8        222        341        601        239         57
   DRM0123_PV DRM0124_PV DRM0125_PV DRM0126_PV DRM0127_PV DRM0128_PV DRM0129_PV DRM0130_PV DRM0131_PV DRM0132_PV DRM0133_PV DRM0134_PV DRM0135_PV DRM0136_PV DRM0137_PV
1:        484        239        502        415        504         62        487        168        101        319        365         37        218        -50        230
   DRM0138_PV DRM0139_PV DRM0140_PV DRM0141_PV DRM0142_PV DRM0143_PV DRM0144_PV DRM0145_PV DRM0146_PV DRM0147_PV DRM0148_PV DRM0149_PV DRM0150_PV DRM0151_PV DRM0152_PV
1:        493        159        150        132         58         21        468        -81         27        345        107        148        -66       -146       -185
   DRM0153_PV DRM0154_PV DRM0155_PV DRM0156_PV DRM0157_PV DRM0158_PV DRM0159_PV DRM0160_PV DRM0161_PV DRM0162_PV DRM0163_PV DRM0164_PV DRM0165_PV DRM0166_PV DRM0167_PV
1:        -14        562         68        140        353        120        130        301         76        441        218        370        218        378        -22
   DRM0168_PV DRM0169_PV DRM0170_PV DRM0171_PV DRM0172_PV DRM0173_PV DRM0174_PV DRM0175_PV DRM0176_PV DRM0177_PV DRM0178_PV DRM0179_PV DRM0180_PV DRM0181_PV DRM0182_PV
1:       -279        563        628        600        152        218        445        246        420         94        495        509        356        183        326
   DRM0183_PV DRM0184_PV DRM0185_PV DRM0186_PV DRM0187_PV DRM0188_PV DRM0189_PV DRM0190_PV DRM0191_PV DRM0192_PV DRM0193_PV DRM0194_PV DRM0195_PV DRM0196_PV DRM0197_PV
1:        493       -190        -65       -123        376        357        473        112        -69        471        452        221        165        -44         87
   DRM0198_PV DRM0199_PV DRM0200_PV DRM0201_PV DRM0202_PV DRM0203_PV DRM0204_PV DRM0205_PV DRM0206_PV DRM0207_PV DRM0208_PV DRM0209_PV DRM0210_PV DRM0211_PV DRM0212_PV
1:        239        285        521        -65        158        223        160        223        269         57        218        218        102        329        218
   DRM0213_PV DRM0214_PV DRM0215_PV DRM0216_PV DRM0217_PV DRM0218_PV DRM0219_PV DRM0220_PV DRM0221_PV DRM0222_PV DRM0223_PV DRM0224_PV DRM0225_PV DRM0226_PV DRM0227_PV
1:        769        215        -68        218        347         18        218        547        759        278        -80        -37        629        -16        774
   DRM0228_PV DRM0229_PV DRM0230_PV DRM0231_PV DRM0232_PV DRM0233_PV DRM0234_PV DRM0235_PV DRM0236_PV DRM0237_PV DRM0238_PV DRM0239_PV DRM0240_PV DRM0241_PV DRM0242_PV
1:        364        113       -132         31        536        118        248        385        218        202        218         41         23        218        379
   DRM0243_PV DRM0244_PV DRM0245_PV DRM0246_PV DRM0247_PV DRM0248_PV DRM0249_PV DRM0250_PV DRM0251_PV DRM0252_PV DRM0253_PV DRM0254_PV DRM0255_PV DRM0256_PV DRM0257_PV
1:       -158        462        600        221        218        221        442        218         53        218        176        504        -61         78         68
   DRM0258_PV DRM0259_PV DRM0260_PV DRM0261_PV DRM0262_PV DRM0263_PV DRM0264_PV DRM0265_PV DRM0266_PV DRM0267_PV DRM0268_PV DRM0269_PV DRM0270_PV DRM0271_PV DRM0272_PV
1:        493        403        218        339        299        749        -18        465        686       -215        579        307        366        279         94
   DRM0273_PV DRM0274_PV DRM0275_PV DRM0276_PV DRM0277_PV DRM0278_PV DRM0279_PV DRM0280_PV DRM0281_PV DRM0282_PV DRM0283_PV DRM0284_PV DRM0285_PV DRM0286_PV DRM0287_PV
1:        138         56        459        613        219        400         35        -74        516        218        -80        317        310       -231        229
   DRM0288_PV DRM0289_PV DRM0290_PV DRM0291_PV DRM0292_PV DRM0293_PV DRM0294_PV DRM0295_PV DRM0296_PV DRM0297_PV DRM0298_PV DRM0299_PV DRM0300_PV DRM0301_PV DRM0302_PV
1:        345        -70        619        235        122         61        337       -163        210        586        127       -112        368        365        476
   DRM0303_PV DRM0304_PV DRM0305_PV DRM0306_PV DRM0307_PV DRM0308_PV DRM0309_PV DRM0310_PV DRM0311_PV DRM0312_PV DRM0313_PV DRM0314_PV DRM0315_PV DRM0316_PV DRM0317_PV
1:        240        270        497         97        420       -184        212        -28        151        527        186        -32         60         96        -86
   DRM0318_PV DRM0319_PV DRM0320_PV DRM0321_PV DRM0322_PV DRM0323_PV DRM0324_PV DRM0325_PV DRM0326_PV DRM0327_PV DRM0328_PV DRM0329_PV DRM0330_PV DRM0331_PV DRM0332_PV
1:        454        321        300        552        319        134        -63        622        441        297        507        578        198        360        542
   DRM0333_PV DRM0334_PV DRM0335_PV DRM0336_PV DRM0337_PV DRM0338_PV DRM0339_PV DRM0340_PV DRM0341_PV DRM0342_PV DRM0343_PV DRM0344_PV DRM0345_PV DRM0346_PV DRM0347_PV
1:        153        318         68        763        370        337        633        469        453        146        428        418        169        468        526
   DRM0348_PV DRM0349_PV DRM0350_PV DRM0351_PV DRM0352_PV DRM0353_PV DRM0354_PV DRM0355_PV DRM0356_PV DRM0357_PV DRM0358_PV DRM0359_PV DRM0360_PV DRM0361_PV DRM0362_PV
1:        441        674         21       -182        174        153       -158        268        191        460         10         82        543       -193        218
   DRM0363_PV DRM0364_PV DRM0365_PV
1:       -203        269        479
 
        

So coef will be ymd(dmda) - ymd(min(df1$date1)). That is, if I do to this id/date/category that I mentioned I get a difference of 2 days, so the value I want is the DRM003_PV . So the value for this case is 198. Therefore, I made:

coef<-SPV %>%
    filter(Id==idd, date2 == ymd(dmda), Category == CategoryChosse) %>%
    pull(as.numeric(ymd(dmda)-ymd(min(df1$date1)))+6)
> coef
[1] 198

This issue has been resolved here: Adjust code to choose a specific column depending on the difference between dates

Libraries and database

library(tidyverse)
library(lubridate)
library(data.table)
library(bench)

set.seed(123)

df1 <- data.frame( Id = rep(1:5, length=800),
                   date1 =  as.Date( "2021-12-01"),
                   date2= rep(seq( as.Date("2021-01-01"), length.out=400, by=1), each = 2),
                   Category = rep(c("ABC", "EFG"), length.out = 800),
                   Week = rep(c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
                                "Saturday", "Sunday"), length.out = 800),
                   DR1 = sample( 200:250, 800, repl=TRUE),  
                   setNames( replicate(365, { sample(0:800, 800)}, simplify=FALSE),
                             paste0("DRM0", formatC(1:365, width = 2, format = "d", flag = "0"))))

First function

return_values <- function (df1,idd,dmda, CategoryChosse) {
  
  # First idea: Calculate the median of the values resulting from the subtraction between DR1 and the values of the DRM0 columns
  
  dt1 <- as.data.table(df1)
  
  cols <- grep("^DRM0", colnames(dt1), value = TRUE)
  
  med <- 
    dt1[, (paste0(cols, "_PV")) := DR1 - .SD, .SDcols = cols
    ][, lapply(.SD, median), by = .(Id, Category, Week), .SDcols = paste0(cols, "_PV") ]
  
  # Second idea: After obtaining the median, I add the values found with the values of the DRM columns of my df1 database.
  
  f2 <- function(nm, pat) grep(pat, nm, value = TRUE)
  nm1 <- f2(names(df1), "^DRM0\\d+$")
  nm2 <- f2(names(med), "_PV")
  nm3 <- paste0("i.", nm2)
  setDT(df1)[med,(nm2) := Map(`+`, mget(nm1), mget(nm3)), on = .(Id, Category, Week)]
  SPV <- df1[, c('Id','date1', 'date2', 'Week','Category', nm2), with = FALSE]#%>%data.frame
  
  # Third idea: Calculate the coef values
  
  coef<-SPV %>%
    filter(Id==idd, date2 == ymd(dmda), Category == CategoryChosse) %>%
    pull(as.numeric(ymd(dmda)-ymd(min(df1$date1)))+6)
  
  return(coef)
  
}

Results using first function

subset_df1 <- subset(df1, date2 > date1)

a<-subset_df1 %>%
  rowwise %>%
  select(-c(Week,starts_with('DR')))%>%
  mutate(Result=return_values(df1,Id, date2, Category)) %>%
  data.frame()  
    > a
    Id      date1      date2 Category Result
1    1 2021-12-01 2021-12-02      ABC    4.0
2    2 2021-12-01 2021-12-02      EFG  238.0
3    3 2021-12-01 2021-12-03      ABC  198.0
4    4 2021-12-01 2021-12-03      EFG  163.0
5    5 2021-12-01 2021-12-04      ABC  462.0
...........

Second function

return_valuesX <- function (df1,idd,dmda, CategoryChosse) {
  
  # First idea: Calculate the median of the values resulting from the subtraction between DR1 and the values of the DRM columns
  
  dt1 <- as.data.table(df1)
  
  num_to_pull <- as.numeric(ymd(dmda)-ymd(min(df1$date1)))+6

  cols <- grep("^DRM0", colnames(dt1), value = TRUE)[1:num_to_pull]
  
  med <- 
    dt1[, (paste0(cols, "_PV")) := DR1 - .SD, .SDcols = cols
    ][, lapply(.SD, median), by = .(Id, Category, Week), .SDcols = paste0(cols, "_PV") ]
  
  # Second idea: After obtaining the median, I add the values found with the values of the DRM columns of my df1 database.
  
  f2 <- function(nm, pat) grep(pat, nm, value = TRUE)
  nm1 <- f2(names(df1), "^DRM0\\d+$")[1:num_to_pull]
  nm2 <- f2(names(med), "_PV")[1:num_to_pull]
  nm3 <- paste0("i.", nm2)[1:num_to_pull]
  setDT(df1)[med,(nm2) := Map(`+`, mget(nm1), mget(nm3)), on = .(Id, Category, Week)]
  SPV <- df1[, c('Id','date1', 'date2', 'Week','Category', nm2), with = FALSE]#%>%data.frame
  
  # Third idea: Calculate the coef values
  
  coef<-SPV %>%
    filter(Id==idd, date2 == ymd(dmda), Category == CategoryChosse) %>%
    pull(num_to_pull)
  
  return(coef)
  
}

Results using second function

b<-subset_df1 %>%
  rowwise %>%
  select(-c(Week,starts_with('DR')))%>%
  mutate(Result = return_valuesX(df1,Id, date2, Category)) %>%
  data.frame()
> b
    Id      date1      date2 Category Result
1    1 2021-12-01 2021-12-02      ABC    4.0
2    2 2021-12-01 2021-12-02      EFG  238.0
3    3 2021-12-01 2021-12-03      ABC  198.0
4    4 2021-12-01 2021-12-03      EFG  163.0
5    5 2021-12-01 2021-12-04      ABC  462.0
...............

Comparing the two results:

identical(a, b)
[1] TRUE

Calculate processing time using benchmark

subset_df1 <- subset(df1, date2 > date1)

 
bench::mark(a=subset_df1 %>%
              rowwise %>%
              select(-c(Week,starts_with('DR')))%>%
              mutate(Result=return_values(df1,Id, date2, Category)),

            b=subset_df1 %>% 
              rowwise %>%
              select(-c(Week,starts_with('DR')))%>%
              mutate(Result=return_valuesX(df1,Id, date2, Category)),iterations = 1)


 # A tibble: 2 x 13
expression      min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result                 memory                   time           gc              
  <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list>                 <list>                   <list>         <list>          
1 a             53.7s    53.7s    0.0186    4.54GB    0.634     1    34      53.7s <rowwise_df [130 x 5]> <Rprofmem [981,580 x 3]> <bench_tm [1]> <tibble [1 x 3]>
2 b               21s      21s    0.0477  913.77MB    0.382     1     8        21s <rowwise_df [130 x 5]> <Rprofmem [278,340 x 3]> <bench_tm [1]> <tibble [1 x 3]>

To check df1 database enter image description here



My cash value is suppose to go up every minute but its not. (Roblox Studio lua error)

I was trying to re-edit the code over and over again but it still didn't work I've created the folder leader stats and when I play the game it shows that it's a part of the player. It says however that it isn't a valid member.

The code that causes the error

The other code that causes another error

The error The other error says: Cash is not a valid member of Folder "Players.(players name).leaderstats"



2022-04-28

How would I consume the body of a put request from a web worker

I want to consume data sent through a put request in a web worker. How would I do so?

this the part in my code where I am trying to handle the put request

if (method === 'put') {
    var data = await event.request.arrayBuffer(); // is this how I could consume the request?
    await updateTree(path); // this is successful
    await put(path, data); // this isnt written
    return new Response('', { // the request still finishes
        headers: {
            'content-length': 0
        },
        status: 201
    });
}

path: the request path

event: the fetch listener event

put: a function that uses the indexeddb api to store data, this function has been tested and works



How to bring browser to front and maximize using Selenium Python

I am working on automating a section of data entry using a mixture of Selenium and Pyautogui.

I have the manual automated part down using the module Pyautogui but I need to bring the browser to the front so the mouse and keyboard can interact with the browser.

All the solutions I've tried maximizes the window but it stays in the background.



Issues with data wrangling in R

I did an online experiment with 700 participants and got the data for each participant in a seperate csv file.

My first step was to import just one file and try to wrangle it the best way for further analysis. The next step would to apply this to all 700 csv files and then merge everything together. Is this more or less the right way to do it?

I am new to R and stuck on the wrangling part. The first picture is what I got so far (current). the second picture is were I want to go (goal).

current

goal

  1. Is it possible, to move all the data to the top of each column, that no empty cells/NA is above the data?
  2. in the column RT_first_letter: is it possible to get only the first entry of the row 6 (in picture current). In this case 2.949...?

Thanks for the help in advance!



Javascript string interpolation gives different result than string concatenation

I ran across a case where Javascript string interpolation is not giving the same result as string concatenation.

Here is a simplified version of the code showing the difference:

const mmt = moment();
console.log('concatenated: ' + mmt); // "concatenated: 1651070909974"
console.log(`interpolated: ${mmt}`); // "interpolated: Wed Apr 27 2022 10:48:29 GMT-0400"
console.log('mmt.valueOf(): ' + mmt.valueOf()); // "mmt.valueOf(): 1651070909974"
console.log('mmt.toString(): ' + mmt.toString()); // "mmt.toString(): Wed Apr 27 2022 10:48:29 GMT-0400"

So my immediate thought was that it was due to a difference in .toString() and .valueOf(), so I made a small test object to verify:

const obj = {
  toString: () => 'toString',
  valueOf: () => 'valueOf',
};

console.log('concatenated: ' + obj); // "concatenated: valueOf"
console.log(`interpolated: ${obj}`); // "interpolated: toString"
console.log('obj.valueOf(): ' + obj.valueOf()); // "obj.valueOf(): valueOf"
console.log('obj.toString(): ' + obj.toString()); // "obj.toString(): toString"

However, when I tried this with a Date object (which also has a different result from .toString() vs .valueOf()), I do not get the same behavior--this time interpolation and concatenation both use the .toString() value:

const dte = new Date();
console.log('concatenated: ' + dte); // "concatenated: Wed Apr 27 2022 10:48:29 GMT-0400 (Eastern Daylight Time)"
console.log(`interpolated: ${dte}`); // "interpolated: Wed Apr 27 2022 10:48:29 GMT-0400 (Eastern Daylight Time)"
console.log('dte.valueOf(): ' + dte.valueOf()); // "dte.valueOf(): 1651070909974"
console.log('dte.toString(): ' + dte.toString()); // "dte.toString(): Wed Apr 27 2022 10:48:29 GMT-0400 (Eastern Daylight Time)"

So my questions is: What are the actual rules for how an interpolated value is converted to a string when concatenated vs interpolated, and why does Date seem to be different from other objects? (I have tried to look this up, but thus far my googling has been unsuccessful...)

JSFiddle Example



Issues running an automatic and unattended clonezilla restore drive

When I try to run an automated and unattended restore via Clonezilla it returns the following error:

Now run "ocs_prerun": mount /dev/sdb2 /mnt...
Mount: /mnt: special device /dev/sdb2 does not exist.
Failed to run: mount /dev/sdb2 /mnt
Press "Enter" to continue......

Then, after hitting Enter it shows the following error:

The directory for this inputted image name does NOT exist: /home/partimag/Amentum_04_21_2022
Program Terminated!!!!
"ocs-sr -kl -e1 auto -e2 -batch -r -j2 -scr -p reboot restoredisk Amentum_04_21_2022 sda" finished with error!

Here is the first entry of my grub.cfg file:

# Since no network setting in the squashfs image, therefore if ip=, the network is disabled.

menuentry "Flysoft RESTORE" {
  search --set -f /live/vmlinuz
  $linux_cmd /live/vmlinuz boot=live union=overlay username=user config components quiet noswap edd=on nomodeset enforcing=0 noprompt ocs_prerun="mount /dev/sdb2 /mnt" ocs_prerun1="mount --bind /mnt/images /home/partimag/" ocs_live_run="ocs-sr -g auto -e1 auto -e2 -r -j2 -k -scr -batch -p reboot restoredisk Amentum_04_21_2022 sda" keyboard-layouts="de" ocs_live_batch="yes" locales=de_DE.UTF-8 vga=788 ip= nosplash net.ifnames=0 splash i915.blacklist=yes radeonhd.blacklist=yes nouveau.blacklist=yes vmwgfx.enable_fbdev=1
  $initrd_cmd /live/initrd.img
}

Here is my syslinux.cfg entry for prerun:

label Amentum_04_21_2022
  MENU DEFAULT
  # MENU HIDE
  MENU LABEL Amentum_04_21_2022
  # MENU PASSWD
  kernel /live/vmlinuz
  append initrd=/live/initrd.img boot=live union=overlay username=user config components quiet noswap edd=on nomodeset noeject locales=en_US.UTF-8 keyboard-layouts=NONE ocs_prerun="mount /dev/sdb2 /mnt" ocs_prerun1="mount --bind /mnt /home/partimag" ocs_live_run="ocs-sr -k1 -e1 auto -e2 -batch -r -j2 -scr -p reboot restoredisk Amentum_04_21_2022 sda" ocs_live_extra_param="" ocs_live_batch="no" vga=791 ip= net.ifnames=0  splash i915.blacklist=yes radeonhd.blacklist=yes nouveau.blacklist=yes vmwgfx.enable_fbdev=1
  TEXT HELP
  VGA mode 1024x768. OK for most of VGA cards.
  ENDTEXT

I'm not sure why this is happening because I've prepared these drives this way every other time and I feel like I'm missing something.

This is how they show up when viewing them in the file explorer in Windows. It's just two partitions on the same drive:

enter image description here

CZ(D:) would be sdb1 and images(E:) would be sdb2, right? This is what I've put in both the grub.cfg and the syslinux.cfg file and it's telling me sdb2 does not exist. Anyone have any ideas?

Thanks in advance!



karate.io.github.classgraph.ClassGraphException: Uncaught exception during scan and java.lang.OutOfMemoryError: Java heap space

Getting this error while trying to run a single Karate API test And also Added @SpringBootTest, @AutoConfiguration and @TestResourceProperty in the runner file and also tried increasing the heap space to 4096MB still the same error.

java.lang.ExceptionInInitializerError
    at com.intuit.karate.Runner$Builder.resolveAll(Runner.java:276)
    at com.intuit.karate.Suite.<init>(Suite.java:168)
    at com.intuit.karate.junit5.Karate.iterator(Karate.java:59)
    at java.base/java.lang.Iterable.spliterator(Iterable.java:101)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
>>Caused by: karate.io.github.classgraph.ClassGraphException: Uncaught exception during scan
    at karate.io.github.classgraph.ClassGraph.scan(ClassGraph.java:1570)
    at karate.io.github.classgraph.ClassGraph.scan(ClassGraph.java:1587)
    at com.intuit.karate.resource.ResourceUtils.<clinit>(ResourceUtils.java:94)
    ... 55 more
>>>Caused by: java.lang.OutOfMemoryError: Java heap space
    at java.base/java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:88)
    at java.base/java.lang.StringBuilder.<init>(StringBuilder.java:115)
    at karate.nonapi.io.github.classgraph.utils.FileUtils.sanitizeEntryPath(FileUtils.java:181)
    at karate.nonapi.io.github.classgraph.fastzipfilereader.LogicalZipFile.readCentralDirectory(LogicalZipFile.java:620)
    at karate.nonapi.io.github.classgraph.fastzipfilereader.LogicalZipFile.<init>(LogicalZipFile.java:154)
    at karate.nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler$3.newInstance(NestedJarHandler.java:144)
    at karate.nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler$3.newInstance(NestedJarHandler.java:139)
    at karate.nonapi.io.github.classgraph.concurrency.SingletonMap.get(SingletonMap.java:189)
    at karate.nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler$4.newInstance(NestedJarHandler.java:205)
    at karate.nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler$4.newInstance(NestedJarHandler.java:154)
    at karate.nonapi.io.github.classgraph.concurrency.SingletonMap.get(SingletonMap.java:189)
    at karate.io.github.classgraph.ClasspathElementZip.open(ClasspathElementZip.java:162)
    at karate.io.github.classgraph.Scanner$3.processWorkUnit(Scanner.java:595)
    at karate.io.github.classgraph.Scanner$3.processWorkUnit(Scanner.java:567)
    at java.base/java.lang.Thread.run(Thread.java:833)


youtube_dl stuck on "downloading webpage" when trying to run Discord Bot

I am trying to create a Discord music bot using Python, and when running my bot's code through the terminal, the bot successfully joins the channel I am in and recognizes that there was a link from Youtube that it needs to play.

However, the bot is for some reason stuck in the terminal on 'downloading webpage' and never loads through yet also never throws an error. I am unsure of what I need to fix or need to add.

An example of what it says is: [youtube] IOatp-OCw3E: Downloading webpage

All of the code for my bot is here:

import youtube_dl
import os
import asyncio
import nacl

client = discord.Client()
token = 'REMOVED FOR PRIVACY'

voice_clients = {}

yt_dl_opts = {'format': 'bestaudio/best'}
ytdl = youtube_dl.YoutubeDL(yt_dl_opts)

ffmpeg_options = {'options': '-vn'}

@client.event
async def on_ready():
    print(f"Bot logged in as {client.user}")
    
@client.event
async def on_message(msg):
    if msg.content.startswith('//play'):
        try:
            url = msg.content.split()[1]

            voice_client = await msg.author.voice.channel.connect()
            voice_clients[voice_client.guild.id] = voice_client
            
            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='/Users/sethstevens/audio-orchestrator-ffmpeg/bin/ffmpeg')
            
            voice_client.play(player)
            
        except Exception as err:
            print(err)

client.run(token)

I currently only have the '//play' command done and will finish the others when my bot can actually play the link given.



2022-04-27

Python in javascript (Brython) execute function with timeout

I'm trying to execute a python function with a timeout, I've found some good ideas on stackoverflow but they don't seem to work for me as I'm executing the python function from javascript (using Brython) and multithreading/sleep don't work well (no sleep function in javascript). Any idea relatively easy to implement that would allow me to terminate a function if its execution takes more than 10s (see logic below):

def function_to_execute:
    print("function executing")

time_out=10
exec(function_to_execute)
time_function_started=time()
if time()>(time_function_startedtime_out) and function_to_execute not complete: (simplified for clarity)
    function_to_execute.terminate()

Thanks,



Additive deserializing with Serde

I'd like to additively deserialize multiple files over the same data structure, where "additively" means that each new file deserializes by overwriting the fields that it effectively contains, leaving unmodified the ones that it does not. The context is config files; deserialize an "app" config provided by the app, then override it with a per-"user" config file.

I use "file" hear for the sake of clarity; this could be any deserializing data source.

Note: After writing the below, I realized maybe the question boils down to: is there a clever use of #[serde(default = ...)] to provide a default from an existing data structure? I'm not sure if that's (currently) possible.

Example

Data structure

struct S {
  x: f32,
  y: String,
}

"App" file (using JSON for example):

{ "x": 5.0, "y": "app" }

"User" file overriding only "y":

{ "y": "user" }

Expected deserializing (app, then user):

assert_eq!(s.x, 5.0);
assert_eq!(s.y, "user");

Expected solution

  • I'm ignoring on purpose any "dynamic" solution storing all config settings into, say, a single HashMap; although this works and is flexible, this is fairly inconvenient to use at runtime, and potentially slower. So I'm calling this approach out of scope for this question.
  • Data structure can contain other structs. Avoid having to write too many per-struct code manually (like implementing Deserialize by hand). A typical config file for a moderate-sized app can contains hundreds of settings, I don't want the burden of having to maintain those.
  • All fields can be expected to implement Default. The idea is that the first deserialized file would fallback on Default::default() for all missing fields, while subsequent ones would fallback on already-existing values if not explicitly overridden in the new file.
  • Avoid having to change every single field of every single struct to Option<T> just for the sake of serializing/deserializing. This would make runtime usage very painful, where due to above property there would anyway be no None value ever once deserialization completed (since, if a field is missing from all files, it defaults to Default::default() anyway).
  • I'm fine with a solution containing only a fixed number (2) of overriding files ("app" and "user" in example above).

Current partial solution

I know how to do the first part of falling back to Default; this is well documented. Simply use #[serde(default)] on all structs.

One approach would be to simply deserialize twice with #[serde(default)] and override any field which is equal to its default in the app config with its value in the user config. But this 1) probably requires all fields to implement Eq or PartialEq, and 2) is potentially expensive and not very elegant (lose the info during deserialization, then try to somehow recreate it).

I have a feeling I possibly need a custom Deserializer to hold a reference/value of the existing data structure, which I would fallback to when a field is not found, since the default one doesn't provide any user context when deserializing. But I'm not sure how to keep track of which field is currently being deserialized.

Any hint or idea much appreciated, thanks!



How to mark a vertex has been visited in graph

I am implementing graph structure for my path finding in a maze program. In some operation like: traversing graph, free the graph (which is malloc-ed before, or use breadth first search,... It is require to check if a vertex is visited or not.

This is vertex and edge struct:

typedef struct graph
{
    // val just use to label the vertex
    int val;

    // since the maze just has 4 directions,
    // I simplify vertex to just point to 4 other vertices
    edge up;
    edge down;
    edge left;
    edge right;
}vertex;

typedef struct Edge
{
    int weight;
    vertex *neighbour;
    bool visited;
}edge;

I have thought about 2 solutions. The first is add bool visited; in vertex or edge struct and initialize it to false, but it just able to use 1 time, because I don't know how to reinitialize the visited. The second approach is make a link list, put the visited vertex in that list and check for visited vertex in that list when required. But it costs so much work when there are hundred of vertices.

So what is the good mechanism to check a vertex is visited? What is the better way to implement this problem?



Handle Api response in Ktor

hey I am trying to learn ktor for my api request. I am reading Response validation in doc.

ApiResponse.kt

sealed class ApiResponse<out T : Any> {
    data class Success<out T : Any>(
        val data: T?
    ) : ApiResponse<T>()

    data class Error(
        val exception: Throwable? = null,
        val responseCode: Int = -1
    ) : ApiResponse<Nothing>()

    fun handleResult(onSuccess: ((responseData: T?) -> Unit)?, onError: ((error: Error) -> Unit)?) {
        when (this) {
            is Success -> {
                onSuccess?.invoke(this.data)
            }
            is Error -> {
                onError?.invoke(this)
            }
        }
    }
}

@Serializable
data class ErrorResponse(
    var errorCode: Int = 1,
    val errorMessage: String = "Something went wrong"
)

I have this ApiResponse class in which, I want to handle api response through this post. As you see in the link, there is function called fetchResult, inside that code is checking every time response.code() and route according to domain specific Success or Error body. Is there any better way it will automatically route on specific domain rather than checking every time in ktor.

actual fun httpClient(config: HttpClientConfig<*>.() -> Unit) = HttpClient(OkHttp) {
    config(this)
    install(Logging) {
        logger = Logger.SIMPLE
        level = LogLevel.BODY
    }
    expectSuccess = false
    HttpResponseValidator {
        handleResponseExceptionWithRequest { exception, _ ->
            val errorResponse: ErrorResponse
            when (exception) {
                is ResponseException -> {
                    errorResponse = exception.response.body()
                    errorResponse.errorCode = exception.response.status.value
                }
            }
        }
    }
}

KtorApi.kt

class KtorApi(private val httpClient: HttpClient) {
    suspend fun getAbc(): Flow<KtorResponse> {
        return httpClient.get {
            url("abc")
        }.body()
    }
}


How can I make a button clickable only one time?

I want to create a button that gets disabled after one click/is just clickable one time... I couldnt find anything about it.



2022-04-26

.htaccess redirect problem - [This rule was not met.]

I trying to create redirect old non existing page to new URL on Apache with htaccess file, i am very confused, because i tried a lot of combination of this redirect

I need to redirect something about 10 subpages like:

https://example.com/main/home/news -> https://example.com/
https://example.com/main/checkout/summary -> https://example.com/summary
https://example.com/main/auth/home -> https://example.com/myaccount

I tried to use (for 1st example) this .htaccess code:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^main/home/news$ /? [L,R=301]
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{QUERY_STRING} ^$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

but in the validator I have information: "This rule was no meet"

I am also wondering if it is not a matter of the fact that the application is running on azure app services

Screenshot from the validator:

screenshot from validator



Anaconda (3-2021.11) environment not showing up in Jupyter Notebook

I am having trouble getting my anaconda environment to show up in jupyter notebook. I'm not sure if the current solutions are dated or if I am doing something wrong. I make the behavior clear to hopefully make identifying the issue easier.

I install Anaconda3-2021.11 for Linux from their website:

$ sh ./Downloads/Anaconda3-2021.11-Linux-x86_64.sh
$ reboot
$ conda update conda -y
$ conda install nb_conda_kernels -y

We see the following conda environments:

$ conda env list

# conda environments:
#
base                  *  /home/user/anaconda3

And we can see where python is:

$ echo $CONDA_DEFAULT_ENV

base

$ which python

/home/user/anaconda3/bin/python

$ python --version

Python 3.9.7

I observe the following with jupyter and nb_conda_kernels:

$ jupyter kernelspec list

[ListKernelSpecs] WARNING | Config option `kernel_spec_manager_class` not recognized by `ListKernelSpecs`.
Available kernels:
  python3    /home/user/anaconda3/share/jupyter/kernels/python3

$ python -m nb_conda_kernels list

[ListKernelSpecs] WARNING | Config option `kernel_spec_manager_class` not recognized by `ListKernelSpecs`.
[ListKernelSpecs] [nb_conda_kernels] enabled, 1 kernels found
Available kernels:
  python3          /home/user/anaconda3/share/jupyter/kernels/python3
  conda-root-py    /home/user/anaconda3/share/jupyter/kernels/python3

If I try to create an environment like this:

conda create -n test_env python=3.8

It will show up in conda:

$ conda env list

# conda environments:
#
base                  *  /home/user/anaconda3
test_env                 /home/user/anaconda3/envs/test_env

And we can see where python for test_env is:

$ conda activate test_env
$ echo $CONDA_DEFAULT_ENV

test_env

$ which python

/home/user/anaconda3/envs/test_env/bin/python

$ python --version

Python 3.8.13

But, when in base, jupyter kernelspec list and python -m nb_conda_kernels list outputs do not change.

If I try to do it manually:

$ python -m ipykernel install --user --name test_env --display-name "Python (test_env)"

Installed kernelspec test_env in /home/user/.local/share/jupyter/kernels/test_env

It may show up in the jupyter kernelspec and nb_conda_kernels:

$ jupyter kernelspec list

[ListKernelSpecs] WARNING | Config option `kernel_spec_manager_class` not recognized by `ListKernelSpecs`.
Available kernels:
  test_env    /home/user/.local/share/jupyter/kernels/test_env
  python3     /home/user/anaconda3/share/jupyter/kernels/python3

$ python -m nb_conda_kernels list

[ListKernelSpecs] WARNING | Config option `kernel_spec_manager_class` not recognized by `ListKernelSpecs`.
[ListKernelSpecs] [nb_conda_kernels] enabled, 1 kernels found
Available kernels:
  test_env         /home/deepology/.local/share/jupyter/kernels/test_env
  python3          /home/user/anaconda3/share/jupyter/kernels/python3
  conda-root-py    /home/user/anaconda3/share/jupyter/kernels/python3

But if you actually launch jupyter notebook and create a test_env notebook, then we observe

Notebook Script Input

import sys
print(sys.executable)

Notebook Script Output

/home/user/anaconda3/bin/python
3.9.7 (default, Sep 16 2021, 13:09:58) 
[GCC 7.5.0]

If I reboot nothing changes.

What am I doing wrong?



F# GreaterThanZero passing int or decimal

I want to create a function that check if the passed value is greater than zero.
The passed value can be an int or a decimal (ideally a "numeric value").

In the immediate I just started with this:

type number =
| I of int 
| D of decimal 

type Checker () =
    member this.Validate value =
        match value with 
        | I x when x > 0 -> "ok"
        | D x when x > 0m -> "ok"
        | _ -> "error"

let a = 1f
let b = 1m
//let a_IsValid = Checker().Validate(a) // does not compile, expect number (not int)
//let b_IsValid = Checker().Validate(b) // does not compile, expect number (not decimal)

Found not immediate to pass a "number" so tried something different... I found this article (http://tomasp.net/blog/fsharp-generic-numeric.aspx/) and I thought "static member constraint" is the perfect solution for me. A basic example works as expected:

let inline divideByTwo value = 
    LanguagePrimitives.DivideByInt value 2

divideByTwo 1f |> ignore
divideByTwo 1m |> ignore

but a different scenario found me very surprised:

type Calculator () =
    let divideByTwo value = 
        LanguagePrimitives.DivideByInt value 2

    member this.DivideByTwo value = 
        LanguagePrimitives.DivideByInt value 2

    member this.ValidateGeneric value =
        match LanguagePrimitives.GenericGreaterThan value 0m with
        | true -> "ok"
        | _ -> "error"

//let half = Calculator().DivideByTwo(1) // DivideByInt does not support int !!

// cannot use both the following, the first one will "force" the type, and the other will not work
let a_half = Calculator().DivideByTwo(1f) // ok if used before the "decimal" version
let b_half = Calculator().DivideByTwo(1m) // ok only if comment the previous one

It seems not to work when I want to use more than one type for the passing value.

More than that, the function I need (GenericGreaterThan) seems to have another "limitation", explained below. The example in the article use DivideByInt and, as the name said, it divide the passed value by an int, a well defined type. LanguagePrimitives.GenericGreaterThan needs 2 parameters, a passed value and a fixed one to compare to. The signature of the function as only one generic type for both, so if you pass a type 'T it expect the second one to be 'T too.
I just wants to compare with zero without passing it, but using "0" forced my value to be an int and using "0m" force the value to be a decimal.

There is a simple way to have a function that check if a "numeric" value is greater than "zero" ? Should I use obj and box it .... or use cast ... or stop trying and just use a different function for every type I need ?

[UPDATE]
I tried to use the LanguagePrimitives.GenericZero as suggested but still not able to have a working solution for my particular scenario.
The real scenario involves an interface and it does not allow me to use inline. I haven't mentioned because I created a simplest use case as possible, didn't imagined that using a class and/or an interface makes the difference here.

type IValidationCheck =   
    abstract member Validate: unit -> Result<unit, string>

type NumberIsPositiveCheck (property:string, value) =
    interface IValidationCheck with
        member (*inline*) this.Validate () =  // does not allow me to use "inline"
            if value > LanguagePrimitives.GenericZero then Ok()  // fail to compile: the type IComparable does not have a get_Zero operator
            else Error $"{property} must be greater than zero"

I'm not able to figure out the way to use an inline function inside the class.



how to get focus in TitleText input from npyscreen?

I need to get the focus back to the first input after write and press the enter key in another input. For instance, after enter a value in myPrecio input and press enter i need to get the focus back to myCodigo input, how can i achieve this?


import npyscreen


class MyGrid(npyscreen.GridColTitles):
    # You need to override custom_print_cell to manipulate how
    # a cell is printed. In this example we change the color of the
    # text depending on the string value of cell.
    def custom_print_cell(self, actual_cell, cell_display_value):
        if cell_display_value =='FAIL':
           actual_cell.color = 'DANGER'
        elif cell_display_value == 'PASS':
           actual_cell.color = 'GOOD'
        else:
           actual_cell.color = 'DEFAULT'




class nuevoIngreso(npyscreen.FormBaseNew):
    def afterEditing(self):

        self.parentApp.setNextForm(none)


    def create(self):
        self.myDepartment = self.add(npyscreen.TitleSelectOne, scroll_exit=True, max_height=3, name='Departmento', values = ['M', 'C', 'L'])
        self.myCodigo = self.add(npyscreen.TitleText, name='CODIGO: ')
        self.myDescripcion = self.add(npyscreen.TitleText, name='DESCRIPCION: ')
        self.myKit = self.add(npyscreen.TitleText, name='UN/KIT: ')
        self.myPrecio = self.add(npyscreen.TitleText, name='$/UN')
        self.myGrid = self.add(MyGrid,select_whole_line = True,editable = False)
        # Adding values to the Grid, this code just randomly
        # fills a 2 x 4 grid with random PASS/FAIL strings.
        self.myGrid.values = []
        for x in range(3):
            row = []
            for y in range(4):
                if bool(random.getrandbits(1)):
                    row.append("PASS")
                else:
                    row.append("FAIL")
            self.myGrid.values.append(row)




class MyApplication(npyscreen.NPSAppManaged):
    def onStart(self):
        F=self.addForm('MAIN', nuevoIngreso, name='Nuevo Ingreso')
        # A real application might define more forms here.......



if __name__ == '__main__':
    TestApp = MyApplication().run()

UPDATE: after some test, i added to my code:

  self.myPrecio.entry_widget.handlers.update({curses.ascii.CR: self.input_send})

At the end of def Create(self) and i added this function to attach bind to enter key on TitleText widget:

    def input_send(self, _input):

        #self.myCodigo.editing = False
        #self.myDescripcion.editing = False
        #self.myKit.editing = False
        #self.myGrid.editing = False
        #self.myPrecio.editing =
        self.display()
        self.editw=1
        self.myPrecio.editing = False
        self.editing = False
        self.edit()

Now i can set focus on field myCodigo, but the cursor is also displayed on field myPrecio as follow:

enter image description here



Locating an element within another element

public LocatedCarParksMap locateAndClickOnTheCardByAddressIndicator(String location) {
            List<WebElement> quoteCards = driver.findElements(By.cssSelector(".quote-card"));
    
            for (WebElement webElement : quoteCards) {
                WebElement locationElement = webElement.findElement(By.cssSelector(".quote-card-asset-location"));
                if (locationElement.getText().equals(location)) {
                    webElement.findElement(By.xpath(".rate-card-description")).click();
                }
                throw new NoSuchElementException();
            }
            return this;
        }

DOM

  1. Locating list of cards
  2. iterating through it and locating needed card by locating the element that contains the address i am looking for
  3. if address is the one i am looking for i am trying to find .rate-card-description within the same card element and then clicking on it to proceed further

I have debugged it and it does locates the address from the card however it cant locate an element within the yellow text are for me to click on

What i am doing wrong, thank you



Unable to get mp4 tkhd info using go-mp4

Using package github.com/abema/go-mp4 when i try to run the example in the docs i get following error:

invalid operation: box (variable of type *mp4.BoxInfo) is not an interface 

Here is the example that i am trying:

// extract specific boxes
boxes, err := mp4.ExtractBox(file, nil, mp4.BoxPath{mp4.BoxTypeMoov(), mp4.BoxTypeTrak(), mp4.BoxTypeTkhd()})
if err != nil {
   :
}
for _, box := range boxes {
  tkhd := box.(*mp4.Tkhd)
  fmt.Println("track ID:", tkhd.TrackID)
}

https://pkg.go.dev/github.com/abema/go-mp4#section-readme



2022-04-25

Matching URL with username and password [closed]

I have a regex for validating IP addresses and domain names which has been working well so far

/** Checks if a URL is valid */
export function isValidURL(str: string): boolean {
  var pattern = new RegExp(
    '^(https?:\\/\\/)?' + // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
      '(\\#[-a-z\\d_]*)?$',
    'i'
  ); // fragment locator
  return !!pattern.test(str);
}

The problem is when I use a username and password it breaks.

http://admin:admin@192.168.92.106:5500/api/v1/

Is there a solution that would pass the URL as valid if including a username and password in the URL



Matlab new C++ MEX function runnign speed vs C Mex interfaces

Recently I am working on boosting Matlab project performances. As you may know, Matlab 2017 introduced a new C++ Mex function to avoid unnecessary data copies, I believe it supposes to be faster than previous C Mex interfaces. So I wrote a demo to test, this demo simply calculates returns for some 2d matrix, and for 50 rounds iterations, C++ MEX took 70s to complete vs 0.089s C Mex function. I am using Matlab 2021b and visual studio 2022. This runtime is unreasonable

Sample Matlab code:

ret(di,:) = basedata(di,:) ./ (basedata(di-1,:) * flag(di:, );

So I converted this function for both c mex and c++ mex function: c++ mex:

size_t numRows = inputs[0].getDimensions()[0];
size_t numColumns = inputs[0].getDimensions()[1];
TypedArray<double> ret = std::move(inputs[0]);
TypedArray<double> data = inputs[1];
TypedArray<double> flag = inputs[2];
size_t i, j, pos;
for (i = 1; i < numRows; i++) {
    for (j = 0; j < numColumns; j++) {
        if (data[i - 1][j] > 1 && data[i][j] > 1)
            ret[i][j] = (data[i][j] / data[i - 1][j] - 1.0) * flag[i][j];
        }
    }
outputs[0] = ret;

C MEX:

double *ret = mxGetPr(prhs[0]);
double *data = mxGetPr(prhs[1]);
double *flag = mxGetPr(prhs[2]);
size_t ROWS = mxGetM(prhs[0]);
size_t COLS = mxGetN(prhs[0]);
for (j = 0; j < COLS; j++) {
    for (i = 1; i < ROWS; i++) {
        pos = j * ROWS + i;
        if (data[pos - 1] > 1 && data[pos] > 1)
            ret[pos] = (data[pos] / data[pos - 1] - 1.0) * flag[pos];
    }
}

And I also did some future testing, in C Mex function matrix[i,j] converted into j*Rows +i, however in C++ interface we can use matrix[i][j] to index, So I believe it has issues with the operator overloading. And if I use below C++ Mex iterator the speed is almost identical with C Mex function.

for (auto &elem: ret) {
    elem = 1;
}

In my scenario, I am unable to use iterator like this. Can someone explain why?



Unable to show login messages when username is correct and password is wrong

I have just started learning express. I am adding basic authentication using passport js. I have followed this documentation. It is working a little bit odd on error messages. When the username is correct and password is wrong, it doesn't add any messages to session. It just has basic info like path.


    app.post("/login",(req,res)=>{
      const user = new User({
        username:req.body.username,
        password:req.body.password
      });
    
      console.log(req.session);
      req.login(user,function(err){
        if(err){
          console.log(err);
        }
        else{
          passport.authenticate("local",{ failureRedirect: '/login', failureMessage: true })(req,res,function(){
            res.redirect("/secrets");
          });
        }
      });
    
    });

When the username is wrong, it adds message to session but it doesn't reload properly. it doesn't reload at all to "/login". I have to literally kill the process and then this session data is added.

It doesn't seem to work at all. Kindly help me with dealing both of errors, i.e. right username wrong password and wrong username wrong password.



How can I upload the first name, last name, job and profile picture of the user?

Please Help me I want to know how to upload the first name, last name, job, date of birth and a picture of the user in Flutter Null Safety

this is my signup

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/login.dart';

class Signup extends StatefulWidget {
  @override
  State<Signup> createState() => _SignupState();
}

class _SignupState extends State<Signup> {
  final _formkey = GlobalKey<FormState>();
  var email = '';
  var password = '';
  var confirmPassword = '';
  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();

    super.dispose();
  }

  bool isLoading = false;
  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController();
  registeration() async {
    if (password == confirmPassword) {
      try {
        UserCredential userCredential = await FirebaseAuth.instance
            .createUserWithEmailAndPassword(email: email, password: password);
        print(UserCredential);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            backgroundColor: Colors.blueGrey,
            content: Text(
              'Registerd Successfully. Please Sign In ',
              style: TextStyle(fontSize: 20.0),
            ),
          ),
        );
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => const LoginPage(),
          ),
        );
      } on FirebaseAuthException catch (error) {
        if (error.code == 'week-password') {
          print('Password is too week');
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.blueGrey,
              content: Text(
                'Password is too week ',
                style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
              ),
            ),
          );
        } else if (error.code == 'email-already-in-use') {
          print('Account is already exists');
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.blueGrey,
              content: Text(
                'Account is already exists ',
                style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
              ),
            ),
          );
        }
      }
    } else {
      print('Password and Confirm Password does not match ');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          backgroundColor: Colors.blueGrey,
          content: Text(
            'Password and Confirm Password does not match ',
            style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: Colors.white,
      body: isLoading
          ? Center(
              child: Container(
                height: size.height / 20,
                width: size.height / 20,
                child: CircularProgressIndicator(),
              ),
            )
          : Form(
              key: _formkey,
              child: Padding(
                padding: const EdgeInsets.symmetric(
                    vertical: 20.0, horizontal: 20.0),
                child: ListView(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(30.0),
                      child: Image.asset('images/signup.png'),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                          autofocus: false,
                          decoration: const InputDecoration(
                            labelText: 'Name:',
                            labelStyle: TextStyle(fontSize: 20.0),
                            border: OutlineInputBorder(),
                            errorStyle: TextStyle(
                                color: Colors.black26, fontSize: 15.0),
                          ),
                          controller: nameController,
                          validator: (value) {
                            if (value == null || value.isNotEmpty) {
                              return 'Please Enter Your Name';
                            }
                            if (value.length > 4) {
                              return (' Name(Max. 4 Character)');
                            }

                            return null;
                          }),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                          autofocus: false,
                          decoration: const InputDecoration(
                            labelText: 'Last Name:',
                            labelStyle: TextStyle(fontSize: 20.0),
                            border: OutlineInputBorder(),
                            errorStyle: TextStyle(
                                color: Colors.black26, fontSize: 15.0),
                          ),
                          controller: nameController,
                          validator: (value) {
                            if (value == null || value.isNotEmpty) {
                              return 'Please Enter Your Last Name';
                            }
                            if (value.length > 4) {
                              return ('Last Name(Max. 4 Character)');
                            }

                            return null;
                          }),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                        autofocus: false,
                        decoration: const InputDecoration(
                          labelText: 'Email:',
                          labelStyle: TextStyle(fontSize: 20.0),
                          border: OutlineInputBorder(),
                          errorStyle:
                              TextStyle(color: Colors.black26, fontSize: 15.0),
                        ),
                        controller: emailController,
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Please Enter Email';
                          } else if (!value.contains('@')) {
                            return 'Please Enter Valid Email';
                          }
                          return null;
                        },
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                        autofocus: false,
                        obscureText: true,
                        decoration: const InputDecoration(
                          labelText: ' Password',
                          labelStyle: TextStyle(fontSize: 20.0),
                          border: OutlineInputBorder(),
                          errorStyle:
                              TextStyle(color: Colors.black26, fontSize: 15.0),
                        ),
                        controller: passwordController,
                        validator: (value) {
                          if (value == null ||
                              value.isEmpty ||
                              value.length < 6 ||
                              value.length > 14) {
                            return 'Please Enter Password';
                          }
                          return null;
                        },
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                        autofocus: false,
                        obscureText: true,
                        decoration: const InputDecoration(
                          labelText: 'Confirm Password',
                          labelStyle: TextStyle(fontSize: 20.0),
                          border: OutlineInputBorder(),
                          errorStyle:
                              TextStyle(color: Colors.black26, fontSize: 15.0),
                        ),
                        controller: confirmPasswordController,
                        validator: (value) {
                          if (value == null ||
                              value.isEmpty ||
                              value.length < 6 ||
                              value.length > 14) {
                            return 'Please Confirm Password';
                          }
                          return null;
                        },
                      ),
                    ),
                    const SizedBox(
                      height: 10.0,
                    ),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton(
                            onPressed: () {
                              if (_formkey.currentState!.validate()) {
                                setState(() {
                                  email = emailController.text;
                                  password = passwordController.text;
                                  confirmPassword =
                                      confirmPasswordController.text;
                                });
                                registeration();
                              }
                            },
                            child: const Text(
                              'Signup ',
                              style: TextStyle(fontSize: 18.0),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Text('Already Have An Account ?'),
                          TextButton(
                            onPressed: () {
                              Navigator.pushReplacement(
                                context,
                                PageRouteBuilder(
                                  pageBuilder:
                                      (context, animation1, animation2) =>
                                          const LoginPage(),
                                  transitionDuration:
                                      const Duration(seconds: 0),
                                ),
                              );
                            },
                            child: const Text('Login'),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
}

this is my main

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/login.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initialization,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          print('something wrong');
        }
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter email & password',
          theme: ThemeData(primarySwatch: Colors.blue),
          home: const LoginPage(),
        );
      },
    );
  }
}

this is my login

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/forget_password.dart';
import 'package:newlivenullsaf/pages/signup.dart';
import 'package:newlivenullsaf/pages/user_main.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  var email = "";
  var password = "";
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  userLogin() async {
    try {
      await FirebaseAuth.instance
          .signInWithEmailAndPassword(email: email, password: password);
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => const UserMain()));
    } on FirebaseAuthException catch (error) {
      if (error.code == ' user-not-found') {
        print('No user found for that email ');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            backgroundColor: Colors.blueGrey,
            content: Text(
              'No user found for that email',
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.amber,
              ),
            ),
          ),
        );
      } else if (error.code == 'wrong-password') {
        print('wrong password provided by the user');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            backgroundColor: Colors.blueGrey,
            content: Text(
              'wrong password provided by the user',
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.amber,
              ),
            ),
          ),
        );
      }
    }
  }

  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Form(
        key: _formKey,
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 40.0, horizontal: 20.0),
          child: ListView(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Image.asset('images/login.jpg'),
              ),
              Container(
                margin: const EdgeInsets.symmetric(vertical: 10.0),
                child: TextFormField(
                    autofocus: false,
                    decoration: const InputDecoration(
                      labelText: 'Email:',
                      labelStyle: TextStyle(fontSize: 20.0),
                      border: OutlineInputBorder(),
                      errorStyle:
                          TextStyle(color: Colors.black26, fontSize: 15.0),
                    ),
                    controller: emailController,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please Enter Email';
                      } else if (!value.contains('@')) {
                        return 'Please Enter Valid Email';
                      }
                      return null;
                    }),
              ),
              Container(
                margin: const EdgeInsets.symmetric(vertical: 10.0),
                child: TextFormField(
                  autofocus: false,
                  obscureText: true,
                  decoration: const InputDecoration(
                    labelText: 'Password',
                    labelStyle: TextStyle(fontSize: 20.0),
                    border: OutlineInputBorder(),
                    errorStyle:
                        TextStyle(color: Colors.black26, fontSize: 15.0),
                  ),
                  controller: passwordController,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please Enter Password';
                    }
                    return null;
                  },
                ),
              ),
              Container(
                margin: const EdgeInsets.symmetric(vertical: 20.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        if (_formKey.currentState!.validate()) {
                          setState(() {
                            email = emailController.text;
                            password = passwordController.text;
                          });
                          userLogin();
                        }
                      },
                      child: const Text(
                        'Login',
                        style: TextStyle(fontSize: 18.0),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => ForgotPass(),
                          ),
                        );
                      },
                      child: const Text(
                        'Forget Password ?',
                        style: TextStyle(
                          fontSize: 12.0,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text('Do Not Have Account ?'),
                    TextButton(
                      onPressed: () {
                        Navigator.pushAndRemoveUntil(
                            context,
                            PageRouteBuilder(
                              pageBuilder: (context, a, b) => Signup(),
                              transitionDuration: const Duration(seconds: 0),
                            ),
                            (route) => false);
                      },
                      child: const Text('Signup'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Iused these packages

firebase_core: ^1.5.0
firebase_auth: ^3.0.2

I searched a lot and found a lot of codes and This code is the best I've found

please i need help quickly