问:
react-native-notifications not working with @voximplant/react-native-foreground-service
So I'm using react-native-foreground-service to keep my websocket connection in background and using react-native-notifications to show data from websocket to notification. My websocket doesn't have issues, because my console log showing data message from websocket. But Notifications package didn't show notification and no errors. Here is my code :</p>
```<code>import { Notifications } from "react-native-notifications";
import VIForegroundService from "@voximplant/react-native-foreground-service";
import config from "./config";

export default async function Notif(){
    await VIForegroundService.getInstance().createNotificationChannel({
        id:"id",
        name:"app_name",
        description:"service",
        enableVibration:false
    });

    try {
        await VIForegroundService.getInstance().startService({
            channelId:"id",
            id:1,
            title:"app_title",
            text:"Listening...",
            icon:"ic_icon",
            button:"Ok"
        });
    } catch (e) {
        console.error(e);
    }
    const ws = new WebSocket(config.ws_url);
    ws.onopen = () => setInterval(() => ws.send("ping"), 60 * 1000);
    ws.onmessage = (e) => {
        if(e.data !== "pong"){
            var data = JSON.parse(e.data);
            console.log(data);
            Notifications.postLocalNotification({
                title:"app_name",
                body:`Received report type ${data.type === 1 ? "Post" : "Comment"} from ${data.from}`
            });
        }
    }
}
</code>```

Body:
So I'm using react-native-foreground-service to keep my websocket connection in background and using react-native-notifications to show data from websocket to notification. My websocket doesn't have issues, because my console log showing data message from websocket. But Notifications package didn't show notification and no errors. Here is my code :

import { Notifications } from "react-native-notifications";
import VIForegroundService from "@voximplant/react-native-foreground-service";
import config from "./config";

export default async function Notif(){
    await VIForegroundService.getInstance().createNotificationChannel({
        id:"id",
        name:"app_name",
        description:"service",
        enableVibration:false
    });

    try {
        await VIForegroundService.getInstance().startService({
            channelId:"id",
            id:1,
            title:"app_title",
            text:"Listening...",
            icon:"ic_icon",
            button:"Ok"
        });
    } catch (e) {
        console.error(e);
    }
    const ws = new WebSocket(config.ws_url);
    ws.onopen = () => setInterval(() => ws.send("ping"), 60 * 1000);
    ws.onmessage = (e) => {
        if(e.data !== "pong"){
            var data = JSON.parse(e.data);
            console.log(data);
            Notifications.postLocalNotification({
                title:"app_name",
                body:`Received report type ${data.type === 1 ? "Post" : "Comment"} from ${data.from}`
            });
        }
    }
}


来源: stackexchange

问:
Is passing basic datatypes, like int, by constant reference for efficiency reasons in C++ worth it?
When passing objects to functions, we usually do it by constant reference for efficiency reasons, especially with heavy objects, such as an object that contains a huge vector.

Take the following function declaration as an example: void foo(const ObjType &myObj);

Is it a good practice to do a similar thing when passing basic datatypes (int, char, double, etc.) to functions? Does it increase the efficiency or is the difference negligible? Eg: void boo(const int &x);

ContentLicense: CC BY-SA 4.0


问:
Re-launch node.js script to run in detached screen process
I have a node.js script that, at some point needs to re-launch itself inside of screen so it can run in the background. I made some code that is supposed to launch a copy of the script in a detached process that can continue executing after the parent process exits, but it doesn't seem to run. I then tried commenting out the line that forces the parent script to exit to see what that would do, and I get an error about an unhandled error event inside of events.js. Here's the code sample I made to test the basic problem:

NOTE: The name of this test script is relaunch.js for this example

```<code>try {
    // if the runInScreenSession is set, then re-launch this script inside screen
    if (inScreenSession() === false) {
        console.log("Relaunching script inside screen session...");
        executeDetachedProcess('screen -d -m "node relaunch.js"');
        //process.exit(0);
    } else {
        console.log("Relaunched inside screen session");
    }
} catch (error) {
    console.error(error);
    console.log("Exiting...");
}

function inScreenSession() {
    try {
        return (executeCommand("echo $STY") !== "\n");
    } catch (error) {
        return console.error(error);
    }
}

function executeDetachedProcess(cmd) {
    try {
        var fs = require('fs');
        var spawn = require('child_process').spawn;
        var out = fs.openSync('./out.log', 'a');
        var err = fs.openSync('./out.log', 'a');

        var child = spawn(cmd, [], {
            detached: true,
            stdio: [ 'ignore', out, err ]
        });

        child.unref();
        return true;
    } catch (error) {
        console.error(error);
        return false;
    }
}

function executeCommand(cmd) {
    try {
        var execSync = require('child_process').execSync;
        return execSync(cmd, { encoding: 'utf8', maxBuffer: 50 * 1024 * 1024 }).toString();
    } catch (error) {
        console.error(error);
        return null;
    }
}
</code>```

Any help/insights greatly appreciated.

Body:
I have a node.js script that, at some point needs to re-launch itself inside of screen so it can run in the background. I made some code that is supposed to launch a copy of the script in a detached process that can continue executing after the parent process exits, but it doesn't seem to run. I then tried commenting out the line that forces the parent script to exit to see what that would do, and I get an error about an unhandled error event inside of events.js. Here's the code sample I made to test the basic problem:

NOTE: The name of this test script is relaunch.js for this example

try {
    // if the runInScreenSession is set, then re-launch this script inside screen
    if (inScreenSession() === false) {
        console.log("Relaunching script inside screen session...");
        executeDetachedProcess('screen -d -m "node relaunch.js"');
        //process.exit(0);
    } else {
        console.log("Relaunched inside screen session");
    }
} catch (error) {
    console.error(error);
    console.log("Exiting...");
}

function inScreenSession() {
    try {
        return (executeCommand("echo $STY") !== "\n");
    } catch (error) {
        return console.error(error);
    }
}

function executeDetachedProcess(cmd) {
    try {
        var fs = require('fs');
        var spawn = require('child_process').spawn;
        var out = fs.openSync('./out.log', 'a');
        var err = fs.openSync('./out.log', 'a');

        var child = spawn(cmd, [], {
            detached: true,
            stdio: [ 'ignore', out, err ]
        });

        child.unref();
        return true;
    } catch (error) {
        console.error(error);
        return false;
    }
}

function executeCommand(cmd) {
    try {
        var execSync = require('child_process').execSync;
        return execSync(cmd, { encoding: 'utf8', maxBuffer: 50 * 1024 * 1024 }).toString();
    } catch (error) {
        console.error(error);
        return null;
    }
}

Any help/insights greatly appreciated.


问:
rustc/cargo unable to find legacy_stdio_definitions.lib in link stage
I'm attempting to get started with rust by building a simple main.rs program which prints "Hello, World!". When I attempt to compile the file I get

```<code>rustc main.rs
error: linking with `link.exe` failed: exit code: 1181
  |
  = note: "C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\bin\\amd64\\link.exe" "/NOLOGO" "C:\\Users\\NEIL~1.BAK\\AppData\\Local\\Temp\\rustchfye9L\\symbols.o" "main.main.8e379572-cgu.0.rcgu.o" "main.main.8e379572-cgu.1.rcgu.o" "main.main.8e379572-cgu.2.rcgu.o" "main.main.8e379572-cgu.3.rcgu.o" "main.main.8e379572-cgu.4.rcgu.o" "main.main.8e379572-cgu.5.rcgu.o" "main.4mzbhfmy0dxps4xd.rcgu.o" "/LIBPATH:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libstd-e33da769ef0fc5d8.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libpanic_unwind-32a15d205c9250ae.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\librustc_demangle-e8e6c5708c3a854a.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libstd_detect-19b5cc13cfb1dd2f.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libcfg_if-0cbfd78dde2c666e.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libhashbrown-973b1c4de7cc0d1f.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libminiz_oxide-00afebe6ef29bc45.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libadler-e0530c58d9305cc2.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\librustc_std_workspace_alloc-7566ec688921bb2a.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libunwind-22e56a2a769a0eb9.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libcfg_if-fd701987ba9e9f4b.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\liblibc-86d63b23439b0a40.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\liballoc-2e3b7f0ce600a8f1.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\librustc_std_workspace_core-eb5afab0418f686f.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libcore-1dc79725e6344392.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libcompiler_builtins-0fb63777e7f87f93.rlib" "kernel32.lib" "advapi32.lib" "userenv.lib" "kernel32.lib" "ws2_32.lib" "bcrypt.lib" "msvcrt.lib" "legacy_stdio_definitions.lib" "/NXCOMPAT" "/LIBPATH:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib" "/OUT:main.exe" "/OPT:REF,NOICF" "/DEBUG" "/NATVIS:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\etc\\intrinsic.natvis" "/NATVIS:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\etc\\liballoc.natvis" "/NATVIS:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\etc\\libcore.natvis" "/NATVIS:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\etc\\libstd.natvis"
  = note: LINK : warning LNK4044: unrecognized option '/NATVIS:C:\Users\neil.baker\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\etc\intrinsic.natvis'; ignored
          LINK : warning LNK4044: unrecognized option '/NATVIS:C:\Users\neil.baker\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\etc\liballoc.natvis'; ignored
          LINK : warning LNK4044: unrecognized option '/NATVIS:C:\Users\neil.baker\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\etc\libcore.natvis'; ignored
          LINK : warning LNK4044: unrecognized option '/NATVIS:C:\Users\neil.baker\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\etc\libstd.natvis'; ignored
          LINK : fatal error LNK1181: cannot open input file 'legacy_stdio_definitions.lib'

error: aborting due to previous error
</code>```

rustc --version gives rustc 1.66.0 (69f9c33d7 2022-12-12)

cargo --version gives cargo 1.66.0 (d65d197ad 2022-11-15)

I can see legacy_stdio_definitions.lib in various folders under C:\Program Files (x86)\Microsoft Visual Studio\2017\WDExpress\VC\Tools\MSVC\14.16.27023 and under C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933. However LIBPATH does not point to any of these folders.

Can anyone tell me what I need to do to make this work please.

Body:
I'm attempting to get started with rust by building a simple main.rs program which prints "Hello, World!". When I attempt to compile the file I get

rustc main.rs
error: linking with `link.exe` failed: exit code: 1181
  |
  = note: "C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\bin\\amd64\\link.exe" "/NOLOGO" "C:\\Users\\NEIL~1.BAK\\AppData\\Local\\Temp\\rustchfye9L\\symbols.o" "main.main.8e379572-cgu.0.rcgu.o" "main.main.8e379572-cgu.1.rcgu.o" "main.main.8e379572-cgu.2.rcgu.o" "main.main.8e379572-cgu.3.rcgu.o" "main.main.8e379572-cgu.4.rcgu.o" "main.main.8e379572-cgu.5.rcgu.o" "main.4mzbhfmy0dxps4xd.rcgu.o" "/LIBPATH:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libstd-e33da769ef0fc5d8.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libpanic_unwind-32a15d205c9250ae.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\librustc_demangle-e8e6c5708c3a854a.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libstd_detect-19b5cc13cfb1dd2f.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libcfg_if-0cbfd78dde2c666e.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libhashbrown-973b1c4de7cc0d1f.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libminiz_oxide-00afebe6ef29bc45.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libadler-e0530c58d9305cc2.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\librustc_std_workspace_alloc-7566ec688921bb2a.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libunwind-22e56a2a769a0eb9.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libcfg_if-fd701987ba9e9f4b.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\liblibc-86d63b23439b0a40.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\liballoc-2e3b7f0ce600a8f1.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\librustc_std_workspace_core-eb5afab0418f686f.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libcore-1dc79725e6344392.rlib" "C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib\\libcompiler_builtins-0fb63777e7f87f93.rlib" "kernel32.lib" "advapi32.lib" "userenv.lib" "kernel32.lib" "ws2_32.lib" "bcrypt.lib" "msvcrt.lib" "legacy_stdio_definitions.lib" "/NXCOMPAT" "/LIBPATH:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\x86_64-pc-windows-msvc\\lib" "/OUT:main.exe" "/OPT:REF,NOICF" "/DEBUG" "/NATVIS:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\etc\\intrinsic.natvis" "/NATVIS:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\etc\\liballoc.natvis" "/NATVIS:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\etc\\libcore.natvis" "/NATVIS:C:\\Users\\neil.baker\\.rustup\\toolchains\\stable-x86_64-pc-windows-msvc\\lib\\rustlib\\etc\\libstd.natvis"
  = note: LINK : warning LNK4044: unrecognized option '/NATVIS:C:\Users\neil.baker\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\etc\intrinsic.natvis'; ignored
          LINK : warning LNK4044: unrecognized option '/NATVIS:C:\Users\neil.baker\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\etc\liballoc.natvis'; ignored
          LINK : warning LNK4044: unrecognized option '/NATVIS:C:\Users\neil.baker\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\etc\libcore.natvis'; ignored
          LINK : warning LNK4044: unrecognized option '/NATVIS:C:\Users\neil.baker\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib\rustlib\etc\libstd.natvis'; ignored
          LINK : fatal error LNK1181: cannot open input file 'legacy_stdio_definitions.lib'

error: aborting due to previous error

rustc --version gives rustc 1.66.0 (69f9c33d7 2022-12-12)

cargo --version gives cargo 1.66.0 (d65d197ad 2022-11-15)

I can see legacy_stdio_definitions.lib in various folders under C:\Program Files (x86)\Microsoft Visual Studio\2017\WDExpress\VC\Tools\MSVC\14.16.27023 and under C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933. However LIBPATH does not point to any of these folders.

Can anyone tell me what I need to do to make this work please.


问:
Sorting list based upon string stored in date format
So I have an app which allows people to add items, and assign a 'date' to them. This 'date' isn't an ISO stored date, instead it's a literal string.

For example:

December 2020

February 2022

January 2021

And so on.. In this case, I'd want to order them from newest to oldest, so it'd be this order:

February 2022

January 2021

December 2020

It'd be feasible to convert from string to date (I guess?), but this doesn't feel very efficient.

Is there a way to easily sort strings like this in JavaScript?


问:
How To Replace Image on Layer with PhotoShop - Python
I am using Adobe Photoshop CC2019 and am trying to replace an image in a layer using python photoshop api package.

```<code>with Session() as ps:
    replace_contents = ps.app.stringIDToTypeID("placedLayerReplaceContents")
    desc = ps.ActionDescriptor
    idnull = ps.app.charIDToTypeID("null")
    desc.putPath(idnull, "your/image/path.jpg")
    ps.app.executeAction(replace_contents, desc)
</code>```

I am getting an error saying

Body:
I am using Adobe Photoshop CC2019 and am trying to replace an image in a layer using python photoshop api package.

with Session() as ps:
    replace_contents = ps.app.stringIDToTypeID("placedLayerReplaceContents")
    desc = ps.ActionDescriptor
    idnull = ps.app.charIDToTypeID("null")
    desc.putPath(idnull, "your/image/path.jpg")
    ps.app.executeAction(replace_contents, desc)

I am getting an error saying


问:
Value does not fall within the expected range with GetServerVariableInternal
I am not sure why this error is happening but following the source code it is caused by GetServerVariableInternal with the value IIS_WasUrlRewritten.  Why is this happening and how can I stop it?  When I manually go to this page it never happens.  The ThrowIfFailedHr keeps throwing an error.

Original Error

```<code>Error in Path :/177359/2021-2022-abybl-regular-season/schedule
Raw Url :/177359/2021-2022-abybl-regular-season/schedule
Message :Value does not fall within the expected range.
Source :mscorlib
Stack Trace :   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)
   at System.Web.WebPages.UrlRewriterHelper.WasThisRequestRewritten(HttpContextBase httpContext)
   at System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
   at System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String contentPath)
   at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
   at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, String protocol, String hostName, String fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
   at System.Web.Mvc.UrlHelper.RouteUrl(String routeName, RouteValueDictionary routeValues, String protocol, String hostName)
   at System.Web.Mvc.T4Extensions.Action(UrlHelper urlHelper, ActionResult result)
</code>```

WasThisRequestRewritten

```<code>    private const string UrlWasRewrittenServerVar = "IIS_WasUrlRewritten";
            private const string UrlRewriterEnabledServerVar = "IIS_UrlRewriteModule";

            private object _lockObject = new object();
            private bool _urlRewriterIsTurnedOnValue;
            private volatile bool _urlRewriterIsTurnedOnCalculated = false;

            private static bool WasThisRequestRewritten(HttpContextBase httpContext)
            {
                NameValueCollection serverVars = httpContext.Request.ServerVariables;
                bool requestWasRewritten = (serverVars != null && serverVars[UrlWasRewrittenServerVar] != null);
                return requestWasRewritten;
            }

private string GetServerVariableInternal(string name) {
            IntPtr buffer;
            int bufLen;

            int retval = IIS.MgdGetServerVariableW(_context,
                                                   name,
                                                   out buffer,
                                                   out bufLen);

            Misc.ThrowIfFailedHr(retval);

            if (buffer != IntPtr.Zero) {
                return StringUtil.StringFromWCharPtr(buffer, bufLen);
            }

            return null;
        }
</code>```

Body:
I am not sure why this error is happening but following the source code it is caused by GetServerVariableInternal with the value IIS_WasUrlRewritten.  Why is this happening and how can I stop it?  When I manually go to this page it never happens.  The ThrowIfFailedHr keeps throwing an error.

Original Error

Error in Path :/177359/2021-2022-abybl-regular-season/schedule
Raw Url :/177359/2021-2022-abybl-regular-season/schedule
Message :Value does not fall within the expected range.
Source :mscorlib
Stack Trace :   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)
   at System.Web.WebPages.UrlRewriterHelper.WasThisRequestRewritten(HttpContextBase httpContext)
   at System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
   at System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String contentPath)
   at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
   at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, String protocol, String hostName, String fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
   at System.Web.Mvc.UrlHelper.RouteUrl(String routeName, RouteValueDictionary routeValues, String protocol, String hostName)
   at System.Web.Mvc.T4Extensions.Action(UrlHelper urlHelper, ActionResult result)

WasThisRequestRewritten

    private const string UrlWasRewrittenServerVar = "IIS_WasUrlRewritten";
            private const string UrlRewriterEnabledServerVar = "IIS_UrlRewriteModule";

            private object _lockObject = new object();
            private bool _urlRewriterIsTurnedOnValue;
            private volatile bool _urlRewriterIsTurnedOnCalculated = false;

            private static bool WasThisRequestRewritten(HttpContextBase httpContext)
            {
                NameValueCollection serverVars = httpContext.Request.ServerVariables;
                bool requestWasRewritten = (serverVars != null && serverVars[UrlWasRewrittenServerVar] != null);
                return requestWasRewritten;
            }

private string GetServerVariableInternal(string name) {
            IntPtr buffer;
            int bufLen;

            int retval = IIS.MgdGetServerVariableW(_context,
                                                   name,
                                                   out buffer,
                                                   out bufLen);

            Misc.ThrowIfFailedHr(retval);

            if (buffer != IntPtr.Zero) {
                return StringUtil.StringFromWCharPtr(buffer, bufLen);
            }

            return null;
        }


问:
Tailwind CSS Next.js error: You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
I tried using the Tailwind CSS Product QuickViews template
https://tailwindui.com/components/ecommerce/components/product-quickviews

But I am getting the error "

```<code>You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
</code>```

I am really confused on what to do, please help.

Body:
I tried using the Tailwind CSS Product QuickViews template
https://tailwindui.com/components/ecommerce/components/product-quickviews

But I am getting the error "

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

I am really confused on what to do, please help.


问:
How do I press this button unable to access it in this path
**How do I press this button unable to access it in this path
**

```<code>

from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as ChromeOptions
import time
chrome_options = ChromeOptions()
chrome_options.add_extension('extension_0_3_4_0.crx')
chrome_options.add_extension('extension_2_0_1_0.crx')
chrome_options.add_argument("--window-size=1920,1080")

driver = webdriver.Chrome(options=chrome_options)
driver.get('https://patrickhlauke.github.io/recaptcha/')
time.sleep(10)
elements = driver.find_elements(By.XPATH,'//button[@id="solver-button"]')
for element in elements:
    element.click()

input('enter to exit ')
driver.quit()

</code>```

I have added to the code an addition to the captcha opening automatically, but the button is not pressed. For your information, I added the addition. The button is present, but it is not pressed. I think there is a problem with my path to select the button.
enter image description here

Body:
**How do I press this button unable to access it in this path
**

from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as ChromeOptions
import time
chrome_options = ChromeOptions()
chrome_options.add_extension('extension_0_3_4_0.crx')
chrome_options.add_extension('extension_2_0_1_0.crx')
chrome_options.add_argument("--window-size=1920,1080")

driver = webdriver.Chrome(options=chrome_options)
driver.get('https://patrickhlauke.github.io/recaptcha/')
time.sleep(10)
elements = driver.find_elements(By.XPATH,'//button[@id="solver-button"]')
for element in elements:
    element.click()

input('enter to exit ')
driver.quit()

I have added to the code an addition to the captcha opening automatically, but the button is not pressed. For your information, I added the addition. The button is present, but it is not pressed. I think there is a problem with my path to select the button.
enter image description here


问:
exposing dto properties based on groups (user role) in NestJS
I'm using Prisma, my schema has a table user where a user can have the role of a normal user or an admin.

I have an editUserDto that validates the incoming data during patch requests for the user.

I want to change the logic so that if the user role is ADMIN, the admin can only change the role of the user (so only the role will be exposed to the admin)

and if the user role is USER, only fullname and phoneNumber will be exposed

the following is edit-user.dto.ts:

```<code>import { Role } from '@prisma/client';
import { Expose } from 'class-transformer';
import { IsEmail, IsEnum, IsOptional, IsString } from 'class-validator';

export class EditUserDto {
  @IsString()
  @Expose({ groups: [Role.USER] })
  fullname: string;

  @IsString()
  @Expose({ groups: [Role.USER] })
  phoneNumber: string;

  @IsEnum(Role)
  @Expose({ groups: [Role.ADMIN] })
  role: Role;
}
</code>```

user.controller.ts:

```<code>import {
  Body,
  ClassSerializerInterceptor,
  Controller,
  Get,
  Param,
  Patch,
  SerializeOptions,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Role, User } from '@prisma/client';
import { GetUser } from '../auth/decorator';
import { JwtGuard } from '../auth/guard';
import { EditUserDto } from './dto';
import { UserService } from './user.service';

@UseGuards(JwtGuard)
@Controller('user')
export class UserController {
  constructor(private userService: UserService) {}

  @Get('me')
  getMe(@GetUser() user: User) {
    return user;
  }

  @Patch('/:userId')
  @UseInterceptors(ClassSerializerInterceptor, FileInterceptor('file'))
  @SerializeOptions({
    groups: [Role.ADMIN],
  })
  editUser(
    @GetUser('id') requestingUserId: string,
    @Param('userId') userId,
    @Body() dto: EditUserDto,
    @UploadedFile() file: Express.Multer.File,
  ) {
    return this.userService.editUser(userId, dto, requestingUserId, file);
  }
}
</code>```

the code I have shown above acts a bit weird. when I make a request and provide the data for all properties, I get the following error:

```<code>{
    "statusCode": 400,
    "message": [
        "fullname must be a string",
        "phoneNumber must be a string",
        "role must be a valid enum value"
    ],
    "error": "Bad Request"
}
</code>```

my 1st question: why would it complain that these values haven't been passed? if I comment out the expose decorator or pass an empty array, the data is accepted by the dto so I'm guessing the problem is related to expose.

my 2nd question: assuming that problem is resolved, how can I pass a dynamic group into the SerializeOptions based on the current user's role?

my 3rd question: is this the right approach? is there an entirely different way to do this?

appreciate any help I can get.
thanks in advance.

Body:
I'm using Prisma, my schema has a table user where a user can have the role of a normal user or an admin.

I have an editUserDto that validates the incoming data during patch requests for the user.

I want to change the logic so that if the user role is ADMIN, the admin can only change the role of the user (so only the role will be exposed to the admin)

and if the user role is USER, only fullname and phoneNumber will be exposed

the following is edit-user.dto.ts:

import { Role } from '@prisma/client';
import { Expose } from 'class-transformer';
import { IsEmail, IsEnum, IsOptional, IsString } from 'class-validator';

export class EditUserDto {
  @IsString()
  @Expose({ groups: [Role.USER] })
  fullname: string;

  @IsString()
  @Expose({ groups: [Role.USER] })
  phoneNumber: string;

  @IsEnum(Role)
  @Expose({ groups: [Role.ADMIN] })
  role: Role;
}

user.controller.ts:

import {
  Body,
  ClassSerializerInterceptor,
  Controller,
  Get,
  Param,
  Patch,
  SerializeOptions,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Role, User } from '@prisma/client';
import { GetUser } from '../auth/decorator';
import { JwtGuard } from '../auth/guard';
import { EditUserDto } from './dto';
import { UserService } from './user.service';

@UseGuards(JwtGuard)
@Controller('user')
export class UserController {
  constructor(private userService: UserService) {}

  @Get('me')
  getMe(@GetUser() user: User) {
    return user;
  }

  @Patch('/:userId')
  @UseInterceptors(ClassSerializerInterceptor, FileInterceptor('file'))
  @SerializeOptions({
    groups: [Role.ADMIN],
  })
  editUser(
    @GetUser('id') requestingUserId: string,
    @Param('userId') userId,
    @Body() dto: EditUserDto,
    @UploadedFile() file: Express.Multer.File,
  ) {
    return this.userService.editUser(userId, dto, requestingUserId, file);
  }
}

the code I have shown above acts a bit weird. when I make a request and provide the data for all properties, I get the following error:

{
    "statusCode": 400,
    "message": [
        "fullname must be a string",
        "phoneNumber must be a string",
        "role must be a valid enum value"
    ],
    "error": "Bad Request"
}

my 1st question: why would it complain that these values haven't been passed? if I comment out the expose decorator or pass an empty array, the data is accepted by the dto so I'm guessing the problem is related to expose.

my 2nd question: assuming that problem is resolved, how can I pass a dynamic group into the SerializeOptions based on the current user's role?

my 3rd question: is this the right approach? is there an entirely different way to do this?

appreciate any help I can get.
thanks in advance.


问:
ethersjs how to sign with raw transaction data
As the below picture display.

If I know the raw transaction data, then how can I sign this transaction with the ethers.js?

Thanks.


问:
No exception thrown in java threads
Problem statement: I see test case is not getting failed when the method is executed inside java thread but the same case failed when executed without thread. This leads misleading results  in test automation. Could someone help me to know the root cuase.?

Expected: Exception should be thrown and test case must be failed.

Actual: Exception is thrown but test case is not failed if method is executed inside thread.

With Thread:-

```<code> public void test()
    {
        Thread t1 = new Thread(() -> {
               obj.js_FindElement(2, "foo",5);
            });
      t1.start();
      t1.join();
    }
</code>```

Output:-

```<code>Exception in thread "Thread-10" org.openqa.selenium.InvalidElementStateException: invalid element state: Failed to execute 'querySelector' on 'Document': '#fooboo]' is not a valid selector.

Result: Passed
</code>```

Without thread:-

```<code>public void test()
    {
     obj.js_FindElement(2, "foo",5);

    }
</code>```

Output:-

```<code>[ERROR] Errors:
[ERROR]   invalid element state: Failed to execute 'querySelector' on 'Document': '#fooboo]' is not a valid selector.

Result: Failed
</code>```

Method:-

```<code>@Step
public WebElement js_FindElement(int sequence, String element, int timer) {
    JavascriptExecutor js = driver(sequence);
    WebElement elem = (WebElement) js.executeScript("return " + element + "");
    int i = 1;
    while (elem == null && i <= duration(timer)) {
        elem = (WebElement) js.executeScript("return " + element + "");
        i += 1;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
    return elem;
}
</code>```

Title: No exception thrown in java threads

Body:
Problem statement: I see test case is not getting failed when the method is executed inside java thread but the same case failed when executed without thread. This leads misleading results  in test automation. Could someone help me to know the root cuase.?

Expected: Exception should be thrown and test case must be failed.

Actual: Exception is thrown but test case is not failed if method is executed inside thread.

With Thread:-

 public void test()
    {
        Thread t1 = new Thread(() -> {
               obj.js_FindElement(2, "foo",5);
            });
      t1.start();
      t1.join();
    }

Output:-

Exception in thread "Thread-10" org.openqa.selenium.InvalidElementStateException: invalid element state: Failed to execute 'querySelector' on 'Document': '#fooboo]' is not a valid selector.

Result: Passed

Without thread:-

public void test()
    {
     obj.js_FindElement(2, "foo",5);

    }

Output:-

[ERROR] Errors:
[ERROR]   invalid element state: Failed to execute 'querySelector' on 'Document': '#fooboo]' is not a valid selector.

Result: Failed

Method:-

@Step
public WebElement js_FindElement(int sequence, String element, int timer) {
    JavascriptExecutor js = driver(sequence);
    WebElement elem = (WebElement) js.executeScript("return " + element + "");
    int i = 1;
    while (elem == null && i <= duration(timer)) {
        elem = (WebElement) js.executeScript("return " + element + "");
        i += 1;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
    return elem;
}


问:
How to trigger a cloud function when a user Subs using Firebase Stripe extension
I struggling with building a payment modal using Firebase and Stripe extension
The modal is that I will have different plans and each will have limited quota.
For instance, I will have a plan that will give the user the ability to download X items from my store

So the question is how can I create a cloud function that gets triggered ones a user subscribes and I can take an action depending on the purchased plan, for example, if he purchased the premium plan, I will create a field in his document "freeDownloadsRemaining": 3

Thanks,

I have searched a lot and I knew that I can create a custom event to be triggered but I didn't find anything helpful to guide me through it


问:
How to use levenshtein function in Sequelize ORM?
I am trying to perform a search query in PostgreSQL database using Sequelize orm.

The Levenshtein distance (a.k.a edit distance) is a measure of similarity between two strings. It is defined as the minimum number of changes required to convert string a into string b (this is done by inserting, deleting or replacing a character in string a). The smaller the Levenshtein distance, the more similar the strings are.


问:
predict crypto price trend with LSTM
I am new in keras and try to write a simple program to predict crypto price trends. I wrote this code but its accuracy is 50% and does not increase during the learning process. is this code has any problem?

```<code>import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.optimizers import Adam
from sklearn.preprocessing import MinMaxScaler
#read file
df = pd.read_csv('data/binancePrices2022.csv')

#determine labels
df["nextClose"] = df["close"].shift(-1)
df["label"] = df["close"] < df["nextClose"]

#determine train and test sets
dataset=df[["close","label" ]]
trainSet=dataset[0:300000]
testSet=dataset[300000:]

#normalize train and test set
sc = MinMaxScaler(feature_range = (0,1))
trainSet["close"] = sc.fit_transform(trainSet[["close"]])
testSet["close"]=sc.fit_transform(testSet[["close"]])

#prepare X_train y_train
X_train = []
y_train = []
for i in range(20, len(trainSet)):
    X_train.append(trainSet[i-20: i]["close"])
X_train = np.array(X_train)
y_train=np.array(trainSet[20:]["label"])
X_train = np.reshape(X_train, newshape = (X_train.shape[0], X_train.shape[1], 1))
y_train=np.reshape(y_train,newshape=(y_train.shape[0],1))
print(y_train)

#prepare X_test y_test
X_test = []
y_test = []
for i in range(20, len(testSet)):
    X_test.append(testSet[i-20: i]["close"])
X_test = np.array(X_test)
y_test=np.array(testSet[20:]["label"])
X_test = np.reshape(X_test, newshape = (X_test.shape[0], X_test.shape[1], 1))
y_test=np.reshape(y_test,newshape=(y_test.shape[0],1))
print(y_test)

#create model
model = Sequential()
model.add(LSTM(units = 20, return_sequences = False, input_shape = (X_train.shape[1], 1)))
model.add(Dropout(rate = 0.2))
model.add(Dense(units = 1,activation='sigmoid'))
opt = Adam(lr=0.0002, beta_1=0.5)
model.compile(optimizer = opt, loss = "binary_crossentropy", metrics=["accuracy"])

model.fit(x = X_train, y = y_train, batch_size = 32, epochs = 100)

model.evaluate(X_test,y_test)

</code>```

I wrote the code and expected the accuracy increase during the learning process but accuracy is always 50% and does not changed. I downloaded binance HLOC prices data minutely from https://www.cryptodatadownload.com/data/binance/ and used close price only.  The label of data is true if next closePrice is higher that current one.

Title: predict crypto price trend with LSTM

Body:
I am new in keras and try to write a simple program to predict crypto price trends. I wrote this code but its accuracy is 50% and does not increase during the learning process. is this code has any problem?

import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.optimizers import Adam
from sklearn.preprocessing import MinMaxScaler
#read file
df = pd.read_csv('data/binancePrices2022.csv')

#determine labels
df["nextClose"] = df["close"].shift(-1)
df["label"] = df["close"] < df["nextClose"]

#determine train and test sets
dataset=df[["close","label" ]]
trainSet=dataset[0:300000]
testSet=dataset[300000:]

#normalize train and test set
sc = MinMaxScaler(feature_range = (0,1))
trainSet["close"] = sc.fit_transform(trainSet[["close"]])
testSet["close"]=sc.fit_transform(testSet[["close"]])

#prepare X_train y_train
X_train = []
y_train = []
for i in range(20, len(trainSet)):
    X_train.append(trainSet[i-20: i]["close"])
X_train = np.array(X_train)
y_train=np.array(trainSet[20:]["label"])
X_train = np.reshape(X_train, newshape = (X_train.shape[0], X_train.shape[1], 1))
y_train=np.reshape(y_train,newshape=(y_train.shape[0],1))
print(y_train)

#prepare X_test y_test
X_test = []
y_test = []
for i in range(20, len(testSet)):
    X_test.append(testSet[i-20: i]["close"])
X_test = np.array(X_test)
y_test=np.array(testSet[20:]["label"])
X_test = np.reshape(X_test, newshape = (X_test.shape[0], X_test.shape[1], 1))
y_test=np.reshape(y_test,newshape=(y_test.shape[0],1))
print(y_test)

#create model
model = Sequential()
model.add(LSTM(units = 20, return_sequences = False, input_shape = (X_train.shape[1], 1)))
model.add(Dropout(rate = 0.2))
model.add(Dense(units = 1,activation='sigmoid'))
opt = Adam(lr=0.0002, beta_1=0.5)
model.compile(optimizer = opt, loss = "binary_crossentropy", metrics=["accuracy"])

model.fit(x = X_train, y = y_train, batch_size = 32, epochs = 100)

model.evaluate(X_test,y_test)

I wrote the code and expected the accuracy increase during the learning process but accuracy is always 50% and does not changed. I downloaded binance HLOC prices data minutely from https://www.cryptodatadownload.com/data/binance/ and used close price only.  The label of data is true if next closePrice is higher that current one.


问:
Type error when dispatching action with params in redux toolkit
I tried making a user authentication using redux toolkit in Nextjs with Typescript but I keep getting the following error when dispatching an action.

```<code>Type error: Argument of type 'AsyncThunkAction<any, SigninParams, AsyncThunkConfig>' is not assignable to parameter of type 'AnyAction'.
</code>```

This is my signin.tsx file

```<code>import { useState } from 'react'
import { useDispatch } from 'react-redux'
import { getUser } from '../../store/slices/userSlice'

const Signin = () => {
    const dispatch = useDispatch()

    const [userData, setUserData] = useState({
        email: '',
        password: '',
    })

    const signinHandler = async (e: any) => {
        e.preventDefault()
        dispatch(getUser({ userData }))
    }

    return (
        <div className='flex items-center justify-center w-screen h-screen'>
            <form
                onSubmit={signinHandler}
                className='border p-5 flex flex-col items-center justify-center'>
                <input
                    type='email'
                    onChange={(e) =>
                        setUserData((prev) => ({
                            ...prev,
                            email: e.target.value,
                        }))
                    }
                />
                <input
                    type='password'
                    onChange={(e) =>
                        setUserData((prev) => ({
                            ...prev,
                            password: e.target.value,
                        }))
                    }
                />
                <button>Signin</button>
            </form>
        </div>
    )
}

export default Signin

</code>```

This is what the userSlice.ts file looks like

```<code>import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import dbConnect from '../../lib/dbConnect'
import axios from 'axios'

export interface UserState {
    status: 'idle' | 'loading' | 'failed'
    user: object
    error: string | null | object
}

interface SigninParams {
    email: string
    password: string
}

// Default state object with initial values.
const initialState: UserState = {
    status: 'idle',
    user: {},
    error: null,
} as const

// Thunks
export const getUser = createAsyncThunk(
    'user/signin',
    async (params: SigninParams) => {
        await dbConnect()
        const { email, password } = params

        const config = {
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
            },
        }
        const { data } = await axios.post(
            '/api/signin',
            { email, password },
            config
        )

        localStorage.setItem('userInfo', JSON.stringify(data))
        localStorage.setItem('token', data.token)

        return data
    }
)

//Slice
export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder.addCase(getUser.pending, (state) => {
            state.status = 'loading'
            state.error = null
        })

        builder.addCase(getUser.fulfilled, (state, { payload }) => {
            state.status = 'idle'
            state.user = payload
        })

        builder.addCase(getUser.rejected, (state, { payload }) => {
            if (payload) state.error = payload
            state.status = 'failed'
        })
    },
})

export const getUserState = (state: { user: UserState }) => state.user
// export const { setName, setEmail } = userSlice.actions
export default userSlice.reducer

</code>```

And here is the store.ts file

```<code>import { configureStore } from '@reduxjs/toolkit'
import userSlice from './slices/userSlice'
import {
    useDispatch as useDispatchBase,
    useSelector as useSelectorBase,
} from 'react-redux'

export const store = configureStore({
    reducer: {
        user: userSlice,
    },
})

export type RootState = ReturnType<typeof store.getState>

type AppDispatch = typeof store.dispatch

export const useDispatch = () => useDispatchBase<AppDispatch>()

export const useSelector = <TSelected = unknown>(
    selector: (state: RootState) => TSelected
): TSelected => useSelectorBase<RootState, TSelected>(selector)

</code>```

I followed the examples in this and this tutorial for setting up redux toolkit with typescript in NextJs.

Body:
I tried making a user authentication using redux toolkit in Nextjs with Typescript but I keep getting the following error when dispatching an action.

Type error: Argument of type 'AsyncThunkAction<any, SigninParams, AsyncThunkConfig>' is not assignable to parameter of type 'AnyAction'.

This is my signin.tsx file

import { useState } from 'react'
import { useDispatch } from 'react-redux'
import { getUser } from '../../store/slices/userSlice'

const Signin = () => {
    const dispatch = useDispatch()

    const [userData, setUserData] = useState({
        email: '',
        password: '',
    })

    const signinHandler = async (e: any) => {
        e.preventDefault()
        dispatch(getUser({ userData }))
    }

    return (

            <form
                onSubmit={signinHandler}
                className='border p-5 flex flex-col items-center justify-center'>
                <input
                    type='email'
                    onChange={(e) =>
                        setUserData((prev) => ({
                            ...prev,
                            email: e.target.value,
                        }))
                    }
                />
                <input
                    type='password'
                    onChange={(e) =>
                        setUserData((prev) => ({
                            ...prev,
                            password: e.target.value,
                        }))
                    }
                />
                <button>Signin</button>
            </form>

    )
}

export default Signin

This is what the userSlice.ts file looks like

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import dbConnect from '../../lib/dbConnect'
import axios from 'axios'

export interface UserState {
    status: 'idle' | 'loading' | 'failed'
    user: object
    error: string | null | object
}

interface SigninParams {
    email: string
    password: string
}

// Default state object with initial values.
const initialState: UserState = {
    status: 'idle',
    user: {},
    error: null,
} as const

// Thunks
export const getUser = createAsyncThunk(
    'user/signin',
    async (params: SigninParams) => {
        await dbConnect()
        const { email, password } = params

        const config = {
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
            },
        }
        const { data } = await axios.post(
            '/api/signin',
            { email, password },
            config
        )

        localStorage.setItem('userInfo', JSON.stringify(data))
        localStorage.setItem('token', data.token)

        return data
    }
)

//Slice
export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder.addCase(getUser.pending, (state) => {
            state.status = 'loading'
            state.error = null
        })

        builder.addCase(getUser.fulfilled, (state, { payload }) => {
            state.status = 'idle'
            state.user = payload
        })

        builder.addCase(getUser.rejected, (state, { payload }) => {
            if (payload) state.error = payload
            state.status = 'failed'
        })
    },
})

export const getUserState = (state: { user: UserState }) => state.user
// export const { setName, setEmail } = userSlice.actions
export default userSlice.reducer

And here is the store.ts file

import { configureStore } from '@reduxjs/toolkit'
import userSlice from './slices/userSlice'
import {
    useDispatch as useDispatchBase,
    useSelector as useSelectorBase,
} from 'react-redux'

export const store = configureStore({
    reducer: {
        user: userSlice,
    },
})

export type RootState = ReturnType<typeof store.getState>

type AppDispatch = typeof store.dispatch

export const useDispatch = () => useDispatchBase<AppDispatch>()

export const useSelector = <TSelected = unknown>(
    selector: (state: RootState) => TSelected
): TSelected => useSelectorBase<RootState, TSelected>(selector)

I followed the examples in this and this tutorial for setting up redux toolkit with typescript in NextJs.


问:
Flutter Firestore Cached Netwok Image Time
I have a social media app and I get photos from firebase and show them on my home screen. In this process, I use Cached Network Image to load photos faster and the photos are successfully cached. What I'm wondering is whether these cached photos automatically clean themselves after a certain time, if they do, after how much time has passed. If it doesn't clean, what should I do for it to automatically clean itself?


问:
Python 3.9.7 Visual Studio Code; Could not find a version that satisfies the requirement numpy (from versions: none)
My goal is to be able to use CUDA.
For installation, I implemented below code, and got error messages.

```<code>pip install numpy --pre torch torchvision torchaudio --force-reinstall --index-url https://download.pytorch.org/whl/nightly/cu116
</code>```

Looking in indexes: https://download.pytorch.org/whl/nightly/cu116

ERROR: Could not find a version that satisfies the requirement numpy (from versions: none)

ERROR: No matching distribution found for numpy

Note: you may need to restart the kernel to use updated packages.

Already tried all solutions on StackOverflow and Github but nothing worked.

Body:
My goal is to be able to use CUDA.
For installation, I implemented below code, and got error messages.

pip install numpy --pre torch torchvision torchaudio --force-reinstall --index-url https://download.pytorch.org/whl/nightly/cu116

Looking in indexes: https://download.pytorch.org/whl/nightly/cu116

ERROR: Could not find a version that satisfies the requirement numpy (from versions: none)

ERROR: No matching distribution found for numpy

Note: you may need to restart the kernel to use updated packages.

Already tried all solutions on StackOverflow and Github but nothing worked.


问:
Create Password List of specific length words and combine it with a dictionary, in combination with a character set
Let's say all passwords should be 4 characters long use a dictionary and a-z and 0-9

1car 2car ..

car1 car2 ..

acar bcar ..

cara carb ..

Any known tool that can generate this. It's going to be used for specific length passwords that contain 1 or more words in the rest is generated with all combinatory possibilities using defined character sets.


问:
Android keyboard not filling full width
I'm very new to Java and Android SDK and I'm trying to code a custom keyboard.
The problem is that I don't understand why my keyboard's width is matching its content and not the entire screen width as seen here.

Here's my KeyboardView xml:

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="#292E32"
    android:fontFamily="@font/noto_sans_runic"
    android:keyBackground="@drawable/key"
    android:keyPreviewLayout="@layout/key_preview"
    android:keyTextColor="#FFFFFF"
    android:keyTextSize="20sp"
/>
```
<p>And my KeyboardLayout xml:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="10%"
    android:horizontalGap="1.2%"
    android:verticalGap="1.5%"
    android:keyHeight="40dip"
    >

    <Row>
        <Key android:codes="5792" android:keyLabel="ᚠ" android:keyEdgeFlags="left"/>
        <Key android:codes="5794" android:keyLabel="ᚢ"/>
        <Key android:codes="5798" android:keyLabel="ᚦ"/>
        <Key android:codes="5800" android:keyLabel="ᚨ"/>
        <Key android:codes="5809" android:keyLabel="ᚱ"/>
        <Key android:codes="5810" android:keyLabel="ᚲ"/>
        <Key android:codes="5815" android:keyLabel="ᚷ"/>
        <Key android:codes="5817" android:keyLabel="ᚹ" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="5818" android:keyLabel="ᚺ" android:keyEdgeFlags="left"/>
        <Key android:codes="5822" android:keyLabel="ᚾ"/>
        <Key android:codes="5825" android:keyLabel="ᛁ"/>
        <Key android:codes="5827" android:keyLabel="ᛃ"/>
        <Key android:codes="5831" android:keyLabel="ᛇ"/>
        <Key android:codes="5832" android:keyLabel="ᛈ"/>
        <Key android:codes="5833" android:keyLabel="ᛉ"/>
        <Key android:codes="5834" android:keyLabel="ᛊ" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="5839" android:keyLabel="ᛏ" android:keyEdgeFlags="left"/>
        <Key android:codes="5842" android:keyLabel="ᛒ"/>
        <Key android:codes="5846" android:keyLabel="ᛖ"/>
        <Key android:codes="5847" android:keyLabel="ᛗ"/>
        <Key android:codes="5850" android:keyLabel="ᛚ"/>
        <Key android:codes="5852" android:keyLabel="ᛜ"/>
        <Key android:codes="5854" android:keyLabel="ᛞ"/>
        <Key android:codes="5855" android:keyLabel="ᛟ" android:keyEdgeFlags="right"/>
    </Row>

    <Row android:rowEdgeFlags="bottom">
        <Key android:codes="12345" android:keyLabel="/" android:keyEdgeFlags="left"/>
        <Key android:codes="5867" android:keyLabel="᛫" android:popupKeyboard="@xml/keyboard_popup" android:popupCharacters="᛬᛭"/>
        <Key android:codes="32" android:keyLabel=" " android:keyWidth="40%" android:isRepeatable="true"/>
        <Key android:codes="-5" android:keyLabel="Del" android:keyWidth="15%" android:isRepeatable="true"/>
        <Key android:codes="10" android:keyLabel="Ret" android:keyEdgeFlags="right" android:keyWidth="15%"/>
    </Row>
</Keyboard>
</code>```

Title: Android keyboard not filling full width

Body:
I'm very new to Java and Android SDK and I'm trying to code a custom keyboard.
The problem is that I don't understand why my keyboard's width is matching its content and not the entire screen width as seen here.

Here's my KeyboardView xml:

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="#292E32"
    android:fontFamily="@font/noto_sans_runic"
    android:keyBackground="@drawable/key"
    android:keyPreviewLayout="@layout/key_preview"
    android:keyTextColor="#FFFFFF"
    android:keyTextSize="20sp"
/>

And my KeyboardLayout xml:

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="10%"
    android:horizontalGap="1.2%"
    android:verticalGap="1.5%"
    android:keyHeight="40dip"
    >

    <Row>
        <Key android:codes="5792" android:keyLabel="ᚠ" android:keyEdgeFlags="left"/>
        <Key android:codes="5794" android:keyLabel="ᚢ"/>
        <Key android:codes="5798" android:keyLabel="ᚦ"/>
        <Key android:codes="5800" android:keyLabel="ᚨ"/>
        <Key android:codes="5809" android:keyLabel="ᚱ"/>
        <Key android:codes="5810" android:keyLabel="ᚲ"/>
        <Key android:codes="5815" android:keyLabel="ᚷ"/>
        <Key android:codes="5817" android:keyLabel="ᚹ" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="5818" android:keyLabel="ᚺ" android:keyEdgeFlags="left"/>
        <Key android:codes="5822" android:keyLabel="ᚾ"/>
        <Key android:codes="5825" android:keyLabel="ᛁ"/>
        <Key android:codes="5827" android:keyLabel="ᛃ"/>
        <Key android:codes="5831" android:keyLabel="ᛇ"/>
        <Key android:codes="5832" android:keyLabel="ᛈ"/>
        <Key android:codes="5833" android:keyLabel="ᛉ"/>
        <Key android:codes="5834" android:keyLabel="ᛊ" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="5839" android:keyLabel="ᛏ" android:keyEdgeFlags="left"/>
        <Key android:codes="5842" android:keyLabel="ᛒ"/>
        <Key android:codes="5846" android:keyLabel="ᛖ"/>
        <Key android:codes="5847" android:keyLabel="ᛗ"/>
        <Key android:codes="5850" android:keyLabel="ᛚ"/>
        <Key android:codes="5852" android:keyLabel="ᛜ"/>
        <Key android:codes="5854" android:keyLabel="ᛞ"/>
        <Key android:codes="5855" android:keyLabel="ᛟ" android:keyEdgeFlags="right"/>
    </Row>

    <Row android:rowEdgeFlags="bottom">
        <Key android:codes="12345" android:keyLabel="/" android:keyEdgeFlags="left"/>
        <Key android:codes="5867" android:keyLabel="᛫" android:popupKeyboard="@xml/keyboard_popup" android:popupCharacters="᛬᛭"/>
        <Key android:codes="32" android:keyLabel=" " android:keyWidth="40%" android:isRepeatable="true"/>
        <Key android:codes="-5" android:keyLabel="Del" android:keyWidth="15%" android:isRepeatable="true"/>
        <Key android:codes="10" android:keyLabel="Ret" android:keyEdgeFlags="right" android:keyWidth="15%"/>
    </Row>
</Keyboard>


问:
Unable to run rust playground locally
I am trying to run rust playground locally : https://github.com/integer32llc/rust-playground
The instructions are to

cd to ui/frontend && yarn to build the frontend

cd ../ && cargo run to run the server.

However , when i navigate to 127.0.0.1:5000 on my browser , the page returns on 404.  This is quite confusing as looking at the code , the default port is 5000 and its running on 127.0.0.1

```<code>   Compiling octocrab v0.16.0
   Compiling ui v0.1.0 (/Users/Code/rust/rust-playground/ui)
    Finished dev [unoptimized + debuginfo] target(s) in 58.76s
     Running `target/debug/ui`
</code>```

I would appreciate any guidance on this

Title: Unable to run rust playground locally

Body:
I am trying to run rust playground locally : https://github.com/integer32llc/rust-playground
The instructions are to

cd to ui/frontend && yarn to build the frontend

cd ../ && cargo run to run the server.

However , when i navigate to 127.0.0.1:5000 on my browser , the page returns on 404.  This is quite confusing as looking at the code , the default port is 5000 and its running on 127.0.0.1

   Compiling octocrab v0.16.0
   Compiling ui v0.1.0 (/Users/Code/rust/rust-playground/ui)
    Finished dev [unoptimized + debuginfo] target(s) in 58.76s
     Running `target/debug/ui`

I would appreciate any guidance on this


问:
how to make dynamic arrays of classes in c++
i would like to make a dynamic array of classes in C++.

So if we have in a first attempt:

```<code>class A {

};
</code>```

and then i want to have an array of pointers of class A:

```<code>class B {
    A * classes_a[16] = {nullptr};
    public:
    B()
    {
         for (int i = 0; i < 16; ++i)
                classes_a[i] = new A();
    }
};
</code>```

Well, this way is stright, i mean is an array of "A" pointer classes.

But, what i want to do, and i dont know how to do it isn't havinga fixed array of "A" pointers.
So the code would be the following:

```<code>class B {
    A ** classes_a = nullptr;
    public:
    B()
    {
         for (int i = 0; i < 16; ++i)
                classes_a[i] = new A();     //this cannot be done
    }
};
</code>```

What i want to do is, if i want 16 elements of class "A" pointers. There must be some way to not have a fixed "array" of pointers. I would like to have, for example: 8 class A pointers, ot 12 or whatever i like.

How to do it?

Body:
i would like to make a dynamic array of classes in C++.

So if we have in a first attempt:

class A {

};

and then i want to have an array of pointers of class A:

class B {
    A * classes_a[16] = {nullptr};
    public:
    B()
    {
         for (int i = 0; i < 16; ++i)
                classes_a[i] = new A();
    }
};

Well, this way is stright, i mean is an array of "A" pointer classes.

But, what i want to do, and i dont know how to do it isn't havinga fixed array of "A" pointers.
So the code would be the following:

class B {
    A ** classes_a = nullptr;
    public:
    B()
    {
         for (int i = 0; i < 16; ++i)
                classes_a[i] = new A();     //this cannot be done
    }
};

What i want to do is, if i want 16 elements of class "A" pointers. There must be some way to not have a fixed "array" of pointers. I would like to have, for example: 8 class A pointers, ot 12 or whatever i like.

How to do it?


问:
in html rowspan = "1.5" not working why ans what is the alternative way to do it
I want to create table and there are two columns, in first column there are three rows, and in second column there are two rows.
I want to use rowspan and value is 1.5 rowspan="1.5" but it is not working. Why? and what is the alternative for it.

I want to use rowspan and value is 1.5 rowspan="1.5" but it is not working. Why? and what is the alternative for it.


问:
Generated file missing from Docker image
When I build a container on Google Cloud Build, I echo a secret from an environment variable into a cert file. The file is definitely there during the build process. I've echoed it after it was written and have done an ls on the directory and it's all correct. However, the final container image doesn't have the file. My .dockerignore ignores /tmp, /log and local dev DB files. Here is the dockerfile:

```<code>FROM alpine:3.14
ARG MASTER_KEY
ARG GCS_SECRET

RUN apk update && apk add --no-cache build-base libpq vips-dev postgresql-dev ruby-dev ruby-etc
RUN apk add nodejs

WORKDIR /app

COPY Gemfile Gemfile.lock ./

RUN gem install bundler && \
    bundle config set --local deployment 'true' && \
    bundle config set --local without 'development test' && \
    bundle install

COPY . /app

ENV RAILS_ENV=production \
    LANG=C.UTF-8 \
    BUNDLE_JOBS=4 \
    BUNDLE_RETRY=3 \
    RAILS_SERVE_STATIC_FILES=true \
    RAILS_LOG_TO_STDOUT=true

ENV RAILS_MASTER_KEY=$MASTER_KEY
RUN bundle exec rake assets:precompile

RUN echo "$GCS_SECRET" > config/gcs_secret.json
RUN ls config

EXPOSE 8080
CMD ["bin/rails", "server", "-b", "0.0.0.0", "-p", "8080"]
</code>```

The file in question is the config/gcs_secret. I tried copying it to / and again, it's not there in the image.

Body:
When I build a container on Google Cloud Build, I echo a secret from an environment variable into a cert file. The file is definitely there during the build process. I've echoed it after it was written and have done an ls on the directory and it's all correct. However, the final container image doesn't have the file. My .dockerignore ignores /tmp, /log and local dev DB files. Here is the dockerfile:

FROM alpine:3.14
ARG MASTER_KEY
ARG GCS_SECRET

RUN apk update && apk add --no-cache build-base libpq vips-dev postgresql-dev ruby-dev ruby-etc
RUN apk add nodejs

WORKDIR /app

COPY Gemfile Gemfile.lock ./

RUN gem install bundler && \
    bundle config set --local deployment 'true' && \
    bundle config set --local without 'development test' && \
    bundle install

COPY . /app

ENV RAILS_ENV=production \
    LANG=C.UTF-8 \
    BUNDLE_JOBS=4 \
    BUNDLE_RETRY=3 \
    RAILS_SERVE_STATIC_FILES=true \
    RAILS_LOG_TO_STDOUT=true

ENV RAILS_MASTER_KEY=$MASTER_KEY
RUN bundle exec rake assets:precompile

RUN echo "$GCS_SECRET" > config/gcs_secret.json
RUN ls config

EXPOSE 8080
CMD ["bin/rails", "server", "-b", "0.0.0.0", "-p", "8080"]

The file in question is the config/gcs_secret. I tried copying it to / and again, it's not there in the image.


问:
unstable_getServerSession returning session null and 'decryption operation failed',
I'm trying to get session as respond to PUT request. But I only get null as respond.

```<code>import mongoose from "mongoose";
import { unstable_getServerSession } from "next-auth";
import { initMongoose } from "../../lib/mongoose";
import User from "../../models/User";
import { authOptions } from "./auth/[...nextauth]";

export default async function handle(req, res) {
  await initMongoose();
  const session = await unstable_getServerSession(req, res, authOptions);

  if (req.method === "PUT") {
    const { username } = req.body;
    await User.findByIdAndUpdate();
    res.json(session);
  }

  if (req.method === "GET") {
    const id = req.query.id;
    const user = await User.findById(id);
    res.json({ user });
  }
}

</code>```

[...nextauth].js

```<code>import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { MongoDBAdapter } from "@next-auth/mongodb-adapter";
import clientPromise from "../../../lib/mongodb";

export const authOptions = {
  adapter: MongoDBAdapter(clientPromise),
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  pages: {
    signIn: "/",
  },
  session: {
    strategy: "jwt",
  },
  callbacks: {
    session: async ({ token, session }) => {
      if (session?.user && token?.sub) {
        session.user.id = token.sub;
      }

      return session;
    },
  },
};

export default NextAuth(authOptions);

</code>```

`

I'm trying to get session as respond to PUT request. But I only get null as respond. this is the git repo link : https://github.com/kusalkalinga00/twitter-clone.

Body:
I'm trying to get session as respond to PUT request. But I only get null as respond.

import mongoose from "mongoose";
import { unstable_getServerSession } from "next-auth";
import { initMongoose } from "../../lib/mongoose";
import User from "../../models/User";
import { authOptions } from "./auth/[...nextauth]";

export default async function handle(req, res) {
  await initMongoose();
  const session = await unstable_getServerSession(req, res, authOptions);

  if (req.method === "PUT") {
    const { username } = req.body;
    await User.findByIdAndUpdate();
    res.json(session);
  }

  if (req.method === "GET") {
    const id = req.query.id;
    const user = await User.findById(id);
    res.json({ user });
  }
}

[...nextauth].js

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { MongoDBAdapter } from "@next-auth/mongodb-adapter";
import clientPromise from "../../../lib/mongodb";

export const authOptions = {
  adapter: MongoDBAdapter(clientPromise),
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  pages: {
    signIn: "/",
  },
  session: {
    strategy: "jwt",
  },
  callbacks: {
    session: async ({ token, session }) => {
      if (session?.user && token?.sub) {
        session.user.id = token.sub;
      }

      return session;
    },
  },
};

export default NextAuth(authOptions);

`

I'm trying to get session as respond to PUT request. But I only get null as respond. this is the git repo link : https://github.com/kusalkalinga00/twitter-clone.


问:
How to create a custom Circle() property in swiftui
I would like to create a custom circle that I can reuse. (Essentially, I would have one spot to edit the circle's properties. So in the future, it will be easier to update my circle's properties without having to edit them in every location they are used.)

I have attempted to do this by using a computed property like so:

```<code>var circleView: Circle {
    let customCircle = Circle()
        .fill(circleBackgroundColor)
        .frame(height: circleHeight)
    return customCircle as! Circle
}

var body: some View {
    ZStack() {
        RoundedRectangle(cornerRadius: cellCornerRadius)
            .fill(cellBackgroundColor)
            .frame(width: cellWidth, height: cellHeight)
        VStack() {
            circleView
            Text($firstName.wrappedValue)
                .bold()
                .foregroundColor(titleColor)
        }
    }
}
</code>```

However, strangely, Xcode just crashes.. No errors, no reasons explaining why... just crash. Won't show any preview...

Edit: Oh, and I'm fairly positive the crash has to do with force casting as Circle... but that's the only way I can think of this to work, hence the reason for posting the question.

Any ideas?

Body:
I would like to create a custom circle that I can reuse. (Essentially, I would have one spot to edit the circle's properties. So in the future, it will be easier to update my circle's properties without having to edit them in every location they are used.)

I have attempted to do this by using a computed property like so:

var circleView: Circle {
    let customCircle = Circle()
        .fill(circleBackgroundColor)
        .frame(height: circleHeight)
    return customCircle as! Circle
}

var body: some View {
    ZStack() {
        RoundedRectangle(cornerRadius: cellCornerRadius)
            .fill(cellBackgroundColor)
            .frame(width: cellWidth, height: cellHeight)
        VStack() {
            circleView
            Text($firstName.wrappedValue)
                .bold()
                .foregroundColor(titleColor)
        }
    }
}

However, strangely, Xcode just crashes.. No errors, no reasons explaining why... just crash. Won't show any preview...

Edit: Oh, and I'm fairly positive the crash has to do with force casting as Circle... but that's the only way I can think of this to work, hence the reason for posting the question.

Any ideas?


问:
How to disable arkose lab captcha in puppeteer
I've been going through a lot of answers on SO for bypassing captcha verification, most of them deal with Google's reCaptcha.

In most of them a siteKey parameter is passed in the web pack file to disable the reCaptcha, I was wondering if something similar can be done with Arkose lab's surl.

I also found this answer, which does something with cookies in Selenium.

Again, it would be great if there was a way to replicate this puppeteer and web pack.


问:
Is there a limit for number of parameter list Scala 3 function can have?
I am reading a great book Programming in Scala by Martin Odersky (creator of Scala) and others.

There comes up the chapter 9.3 Currying where currying is introduced. This leads me to the question, is there some limit to the number of parameter lists a Scala 3 function can have? Follow-up question: if there is/n't a limit, why?

For example, the following Scala 3 snippet compiles just fine.

There is a function curriedSum with 5 parameter lists (it is only for illustration, every sane programmer would use a single parameter list).

def curriedSum(a: Int)(b: Int)(c: Int)(d: Int)(e: Int) = a + b + c + d + e
curriedSum(1)(2)(3)(4)(5) // 15
```
<p>version without <em>currying</em></p>
```def ordinarySum(a: Int, b: Int, c: Int, d: Int, e: Int) = a + b + c + d + e
ordinarySum(1, 2, 3, 4, 5) // 15
```

Body:
I am reading a great book Programming in Scala by Martin Odersky (creator of Scala) and others.

There comes up the chapter 9.3 Currying where currying is introduced. This leads me to the question, is there some limit to the number of parameter lists a Scala 3 function can have? Follow-up question: if there is/n't a limit, why?

For example, the following Scala 3 snippet compiles just fine.

There is a function curriedSum with 5 parameter lists (it is only for illustration, every sane programmer would use a single parameter list).

def curriedSum(a: Int)(b: Int)(c: Int)(d: Int)(e: Int) = a + b + c + d + e
curriedSum(1)(2)(3)(4)(5) // 15

version without currying

def ordinarySum(a: Int, b: Int, c: Int, d: Int, e: Int) = a + b + c + d + e
ordinarySum(1, 2, 3, 4, 5) // 15


问:
Generating a 1000 static paths fails in both Vercel and Netlify, but works on localhost
Generating a 1000 static paths fails to build in both Vercel and Netlify using the below code, but works on localhost. If I change to const paths = Array.from({ length: 250 } within getStaticPaths() it then builds successfully in Netlify and also Vercel I assume.

How can I update the code to generate 1000 static paths so it works in Vercel and Netlify just like it works on localhost currently

```<code>import Head from 'next/head'
function Home({ id }) {
  return (
    <>
      <Head> <title>Test</title> </Head>
      <main> <div>{id}</div> </main>
    </>
  )
}

export async function getStaticPaths() {
// Generate a list of 1000 paths for the dynamic routes
const paths = Array.from({ length: 1000 }, (_, i) => ({
    params: { id: (i + 1).toString() },
}));

return {
  paths,
  fallback: false,
};

}

export async function getStaticProps({ params }) {
// Pass the id parameter to the Home function
return {
    props: {
    id: params.id,
    },
};
}

export default Home
</code>```

Vercel and Netlify Error:

```<code>info  - Collecting page data...
info  - Generating static pages (0/1002)
info  - Generating static pages (250/1002)
info  - Generating static pages (500/1002)
info  - Generating static pages (751/1002)
info  - Generating static pages (1002/1002)
info  - Finalizing page optimization...
> Build error occurred
[Error: ENOENT: no such file or directory, rename '/vercel/path0/.next/export/404.html' -> '/vercel/path0/.next/server/pages/404.html'] {
</code>```

Body:
Generating a 1000 static paths fails to build in both Vercel and Netlify using the below code, but works on localhost. If I change to const paths = Array.from({ length: 250 } within getStaticPaths() it then builds successfully in Netlify and also Vercel I assume.

How can I update the code to generate 1000 static paths so it works in Vercel and Netlify just like it works on localhost currently

import Head from 'next/head'
function Home({ id }) {
  return (
    <>
       <title>Test</title>

{id}

    </>
  )
}

export async function getStaticPaths() {
// Generate a list of 1000 paths for the dynamic routes
const paths = Array.from({ length: 1000 }, (_, i) => ({
    params: { id: (i + 1).toString() },
}));

return {
  paths,
  fallback: false,
};

}

export async function getStaticProps({ params }) {
// Pass the id parameter to the Home function
return {
    props: {
    id: params.id,
    },
};
}

export default Home

Vercel and Netlify Error:

info  - Collecting page data...
info  - Generating static pages (0/1002)
info  - Generating static pages (250/1002)
info  - Generating static pages (500/1002)
info  - Generating static pages (751/1002)
info  - Generating static pages (1002/1002)
info  - Finalizing page optimization...
> Build error occurred
[Error: ENOENT: no such file or directory, rename '/vercel/path0/.next/export/404.html' -> '/vercel/path0/.next/server/pages/404.html'] {


问:
Spring Cloud Gateway always returning 404
I want to call a microservice through api-gateway which is developed by spring cloud gateway. When I hit the microservice directly it is returning the response correctly but when I hit through gateway it is returning 404.

Below is application.yml of api-gateway

```<code>spring:
  cloud:
    gateway:
      routes:
       - id: merchant
         uri: http://localhost:8095/
         predicates:
           - Path=/webstore/**
</code>```

so my main service is running in port 8095. when I hit to the endpoint "http://localhost:8095/productsTest" it returns me the response but when I hit through the api-gateway "http://localhost:8066/webstore/productsTest" it returns my 404.

Body:
I want to call a microservice through api-gateway which is developed by spring cloud gateway. When I hit the microservice directly it is returning the response correctly but when I hit through gateway it is returning 404.

Below is application.yml of api-gateway

spring:
  cloud:
    gateway:
      routes:
       - id: merchant
         uri: http://localhost:8095/
         predicates:
           - Path=/webstore/**

so my main service is running in port 8095. when I hit to the endpoint "http://localhost:8095/productsTest" it returns me the response but when I hit through the api-gateway "http://localhost:8066/webstore/productsTest" it returns my 404.


问:
Pretty URL mask for address bar url
Is there a way to provide a 'pretty URL' mask for the URL in the browser address bar that goes back to its actual value when copied?

Modern browsers do something like this by hiding https://www. visually but if you copy the URL it's actually there. I want this behaviour but with text of my choosing covering parts of the url of my choosing.

Title: Pretty URL mask for address bar url


问:
Tensorflow InvalidArgumentError: Integer division by zero
I'm trying to implement a Policy Network using a PPO loss function.

I have the following code for the output layer:

```<code># Output
    musig = tf.keras.layers.concatenate([mu, sig], axis=-1)
    add_y = tf.keras.layers.Lambda(lambda x: tf.math.round(10 *
(tf.clip_by_value(tfp.distributions.MultivariateNormalTriL(x[0:a_dim], tf.linalg.diag(x[a_dim:])).sample(),-a_bound, a_bound))))(musig)

</code>```

The following code is part of the execution:

```<code>for step in range(steps):
    ID = np.array([state[0][4], state[1][4], state[2][4], state[3][4]])

    out = agent.policy.predict((np.array([state_st_b]), DUMMY_VALUE, DUMMY_ACTION))[0]

    action = out + ID
    action = np.where(action < 0, 0, action)

</code>```

However, when I run this, I get the following error:

```<code>tensorflow.python.framework.errors_impl.InvalidArgumentError: Integer division by zero
     [[{{node lambda_2/MultivariateNormalTriL/sample/BatchBroadcastSampleNormal/sample/floordiv}}]]
</code>```

To be quite frank, I have no idea where I would divide by zero. My initial thought was that it might have to do with the loss function since this is the only part of the code in which I have a fraction. But since I only use the .predict() function the loss fuction should not be relevant and therefore not be called. So I am wondering where else my mistake is since the code works perfectly if I would leave the last lambda layer "add_y" out.

Hope somebody might help.

Body:
I'm trying to implement a Policy Network using a PPO loss function.

I have the following code for the output layer:

# Output
    musig = tf.keras.layers.concatenate([mu, sig], axis=-1)
    add_y = tf.keras.layers.Lambda(lambda x: tf.math.round(10 *
(tf.clip_by_value(tfp.distributions.MultivariateNormalTriL(x[0:a_dim], tf.linalg.diag(x[a_dim:])).sample(),-a_bound, a_bound))))(musig)

The following code is part of the execution:

for step in range(steps):
    ID = np.array([state[0][4], state[1][4], state[2][4], state[3][4]])

    out = agent.policy.predict((np.array([state_st_b]), DUMMY_VALUE, DUMMY_ACTION))[0]

    action = out + ID
    action = np.where(action < 0, 0, action)

However, when I run this, I get the following error:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Integer division by zero
     [[{{node lambda_2/MultivariateNormalTriL/sample/BatchBroadcastSampleNormal/sample/floordiv}}]]

To be quite frank, I have no idea where I would divide by zero. My initial thought was that it might have to do with the loss function since this is the only part of the code in which I have a fraction. But since I only use the .predict() function the loss fuction should not be relevant and therefore not be called. So I am wondering where else my mistake is since the code works perfectly if I would leave the last lambda layer "add_y" out.

Hope somebody might help.


问:
Build Visual Studio Code With 8GB RAM Fails Regarding Heap
The short question is, can the build process be forced to run sequentially/serially rather than parallel?
I know when I've encountered builds that ran in parallel, causing memory issues, I'd be able to do something like -j 1 (depending on the build type), to just use one core, and spare me memory issues.

The last time I built vscode was a few months ago.
I've done the standard:

```<code>$ yarn
$ yarn gulp vscode-linux-x64
</code>```

In order for that to even succeed, I'd have to close out every application on my system because of the memory pressure.
I'd even change --max_old_space_size from 8192 to 4096 in package.json.
But now that isn't even enough. I'll get the error FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory.

From ./build/gulpfile.vscode.js, I can see it calls compile-build from ./build/gulpfile.compile.js.
So I thought I'd just run $ node --max_old_space_size=4096 gulp compile-build, but that didn't work.
I saw there was a --series argument for gulp, so I tried $ node --max_old_space_size=4096 ./node_modules/gulp/bin/gulp.js --series vscode-linux-x64`, but surprisingly, all cores were still being used and I'd run out of memory.

So far, I've narrowed it down to the compilation.compileTask('src', 'out-build', true) step in ./build/gulpfile.compile.js.
When I change true to false, I am able to get further. Although all cores are still being used, my RAM doesn't get choked out.

But even that isn't enough, because optimizeVSCodeTask in vscodeTask ./build/gulpfile.vscode.js will fail because of some longfilename error.

So then I comment out that step, but then vscodeTaskCI will fail because it's expecting files from the optimize step in out-vscode. When I changed sourceFolderName to out-build instead, the vscode dir was created.

But when I ran ../VSCode-linux-x64/code-oss, it opened up blank.
But when I add VSCODE_DEV=0 to the command at the bottom of ../VSCode-linux-x64/bin/code-oss, it runs.

It shouldn't have to be this way.
I know I could "solve" this issue by getting more RAM, but I think it could also be solved if I could somehow figure out a way to keep node/yarn to a single thread.

EDIT0: I tried setting the cpu affinity, and got it to use a single thread, but the RAM usage still climbed unreasonably.

EDIT1: Just for shiggles, I went ahead with the swap suggestion.
Since I start out with a base usage of 1.5GB, I set the swap to 2GB.
That wasn't enough. So I set it to 3GB. That too wasn't enough, my system would still hang, and I'd have to force a kernel oom check/call.

Finally, I set it to 4GB. That was just enough, but barely. It did end up hanging for maybe 5 seconds (right before I was about to kill it), before releasing and continuing on.

It got to 6.8/7.2GB RAM used, and 3.6/4GB of swap according to htop, as I sweated while watching it.

Swap would peak at one point, then drop back to ~1.5GB (my baseline RAM usage?), before climbing back up.

So what I can surmise from the excess usage, is that the build process IS using more RAM than it needs to (in that it's being swapped out).

I don't have memory issues like this with other build systems, and I've experienced this with other node projects.

I think even dotnet's webapps that use node, also end up using a good deal of memory when building.

So it'd still be nice to find a way to constrain node's memory usage.

Body:
The short question is, can the build process be forced to run sequentially/serially rather than parallel?
I know when I've encountered builds that ran in parallel, causing memory issues, I'd be able to do something like -j 1 (depending on the build type), to just use one core, and spare me memory issues.

The last time I built vscode was a few months ago.
I've done the standard:

$ yarn
$ yarn gulp vscode-linux-x64

In order for that to even succeed, I'd have to close out every application on my system because of the memory pressure.
I'd even change --max_old_space_size from 8192 to 4096 in package.json.
But now that isn't even enough. I'll get the error FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory.

From ./build/gulpfile.vscode.js, I can see it calls compile-build from ./build/gulpfile.compile.js.
So I thought I'd just run $ node --max_old_space_size=4096 gulp compile-build, but that didn't work.
I saw there was a --series argument for gulp, so I tried $ node --max_old_space_size=4096 ./node_modules/gulp/bin/gulp.js --series vscode-linux-x64`, but surprisingly, all cores were still being used and I'd run out of memory.

So far, I've narrowed it down to the compilation.compileTask('src', 'out-build', true) step in ./build/gulpfile.compile.js.
When I change true to false, I am able to get further. Although all cores are still being used, my RAM doesn't get choked out.

But even that isn't enough, because optimizeVSCodeTask in vscodeTask ./build/gulpfile.vscode.js will fail because of some longfilename error.

So then I comment out that step, but then vscodeTaskCI will fail because it's expecting files from the optimize step in out-vscode. When I changed sourceFolderName to out-build instead, the vscode dir was created.

But when I ran ../VSCode-linux-x64/code-oss, it opened up blank.
But when I add VSCODE_DEV=0 to the command at the bottom of ../VSCode-linux-x64/bin/code-oss, it runs.

It shouldn't have to be this way.
I know I could "solve" this issue by getting more RAM, but I think it could also be solved if I could somehow figure out a way to keep node/yarn to a single thread.

EDIT0: I tried setting the cpu affinity, and got it to use a single thread, but the RAM usage still climbed unreasonably.

EDIT1: Just for shiggles, I went ahead with the swap suggestion.
Since I start out with a base usage of 1.5GB, I set the swap to 2GB.
That wasn't enough. So I set it to 3GB. That too wasn't enough, my system would still hang, and I'd have to force a kernel oom check/call.

Finally, I set it to 4GB. That was just enough, but barely. It did end up hanging for maybe 5 seconds (right before I was about to kill it), before releasing and continuing on.

It got to 6.8/7.2GB RAM used, and 3.6/4GB of swap according to htop, as I sweated while watching it.

Swap would peak at one point, then drop back to ~1.5GB (my baseline RAM usage?), before climbing back up.

So what I can surmise from the excess usage, is that the build process IS using more RAM than it needs to (in that it's being swapped out).

I don't have memory issues like this with other build systems, and I've experienced this with other node projects.

I think even dotnet's webapps that use node, also end up using a good deal of memory when building.

So it'd still be nice to find a way to constrain node's memory usage.


问:
Minimal popup in Javascript without any controls except X to close and _ to minimize
I used the following to create a popup in Javascript:

```<code>var parms   = 'status=no,location=0,toolbar=0,menubar=no,dependent=yes,left=1000,top=100,';

var wh      = 'width=700,height=600';
popUpWin    = window.open("PopUpForImage.html", "imageWindow", parms + wh);
popUpWin.focus();
</code>```

It creates a black (pop title) and a gray (webpage addres) area on top using Opera and Chrome

How can I get rid of them?

Body:
I used the following to create a popup in Javascript:

var parms   = 'status=no,location=0,toolbar=0,menubar=no,dependent=yes,left=1000,top=100,';

var wh      = 'width=700,height=600';
popUpWin    = window.open("PopUpForImage.html", "imageWindow", parms + wh);
popUpWin.focus();

It creates a black (pop title) and a gray (webpage addres) area on top using Opera and Chrome

How can I get rid of them?


问:
Nextjs13 internalization with lingui/react
I would like to know if it's possible to use Nextjs13 with lingui/react? I want to achieve it using the app folder with server components. If anyone has done it or have any clue it would be great!</p>