问:
How to change variable after checking controller.userData
I'm working with Three.js on a project. I just started working with it and mostly tried my luck with picking different things from the examples.
In short: I'm loading a volume and want to show another layer of it after the event listener for one of the controllers fired.

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <title>three.js vr - dragging</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <link type="text/css" rel="stylesheet" href="main.css">
</head>

<body>

    <div id="info">
        <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> nrrd
    </div>

    <!-- Import maps polyfill -->
    <!-- Remove this when import maps will be widely supported -->
    <script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

    <script type="importmap">
            {
                "imports": {
                    "three": "../build/three.module.js",
                    "three/addons/": "./jsm/"
                }
            }
        </script>

    <script type="module">

        import * as THREE from 'three';
        import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
        import { VRButton } from 'three/addons/webxr/VRButton.js';
        import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
        import { NRRDLoader } from 'three/addons/loaders/NRRDLoader.js';

        let camera, scene, renderer;

        let controller1, controller2;

        let raycaster;

        let xlayer ;
        const intersected = [];
        const tempMatrix = new THREE.Matrix4();

        let controls, group, array;

        init();
        animate();

        function init() {

            const container = document.createElement('div');
            document.body.appendChild(container);

            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x808080);

            camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 40);
            camera.position.set(0, 1.6, 3);

            controls = new OrbitControls(camera, container);
            controls.target.set(0, 1.6, 0);
            controls.update();

            scene.add(new THREE.HemisphereLight(0x808080, 0x606060));

            group = new THREE.Group();
            array = [];
            scene.add(group);

            var holder = new THREE.Group();
            const loader = new NRRDLoader();
            loader.load('models/nrrd/retina.nrrd', function (volume) {

                const a = volume.xLength;
                const b = volume.yLength;
                const c = volume.zLength;

                //box helper to see the extend of the volume
                const geometry = new THREE.BoxGeometry(volume.xLength, volume.yLength, volume.zLength);
                const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
                const cube = new THREE.Mesh(geometry, material);
                cube.visible = false;
                const box = new THREE.BoxHelper(cube);
                holder.add(box);
                box.applyMatrix4(volume.matrix);
                holder.add(cube);

                //z plane
                const sliceZ = volume.extractSlice('z', xlayer);
                holder.add(sliceZ.mesh);

                holder.scale.set((1 / a) * 10, (1 / b) * 6, (1 / c) * 5);
                holder.position.set(0, 0, -15);
                scene.add(holder);
            });

            //l-left, r-right, t-top, b-bottom
            const planegeometrylr = new THREE.PlaneGeometry(5, 6);
            const planegeometrytb = new THREE.PlaneGeometry(10, 5);
            const planematerial = new THREE.MeshBasicMaterial({ color: 'blue', side: THREE.DoubleSide });
            const planel = new THREE.Mesh(planegeometrylr, planematerial);
            const planer = new THREE.Mesh(planegeometrylr, planematerial);
            const planet = new THREE.Mesh(planegeometrytb, planematerial);
            const planeb = new THREE.Mesh(planegeometrytb, planematerial);
            planel.rotateY(Math.PI / 2);
            planel.position.set(-(10 / 2), 0, -15);
            array.push(planel);
            group.add(planel);
            planer.rotateY(Math.PI / 2);
            planer.position.set((10 / 2), 0, -15);
            array.push(planer);
            group.add(planer);
            planet.rotateX(Math.PI / 2);
            planet.position.set(0, (6 / 2), -15);
            array.push(planet);
            group.add(planet);
            planeb.rotateX(Math.PI / 2);
            planeb.position.set(0, -(6 / 2), -15);
            array.push(planeb);
            group.add(planeb);

            //

            renderer = new THREE.WebGLRenderer({ antialias: true });
            renderer.setPixelRatio(window.devicePixelRatio);
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.outputEncoding = THREE.sRGBEncoding;
            renderer.shadowMap.enabled = true;
            renderer.xr.enabled = true;
            container.appendChild(renderer.domElement);

            document.body.appendChild(VRButton.createButton(renderer));

            // controllers

            controller1 = renderer.xr.getController(0);
            controller1.addEventListener('selectstart', onSelectStart);
            controller1.addEventListener('selectend', onSelectEnd);
            controller1.userData.selected = false;
            scene.add(controller1);

            controller2 = renderer.xr.getController(1);
            controller2.addEventListener('selectstart', onSelectStart);
            controller2.addEventListener('selectend', onSelectEnd);
            controller2.userData.selected = false;
            scene.add(controller2);

            const controllerModelFactory = new XRControllerModelFactory();

            //

            const geometry = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, - 1)]);

            const line = new THREE.Line(geometry);
            line.name = 'line';
            line.scale.z = 5;

            controller1.add(line.clone());
            controller2.add(line.clone());

            raycaster = new THREE.Raycaster();

            //

            window.addEventListener('resize', onWindowResize);

            function onSelectStart() {

                this.userData.selected = true;

            }

            function onSelectEnd(event) {
                const controller = event.target;
                controller.userData.selected = false;

            }

        }

        function onWindowResize() {

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize(window.innerWidth, window.innerHeight);

        }

        function handle(controller) {

            if (controller.userData.selected){

                scene.background = new THREE.Color( 'green' );
                xlayer=60;

            }

        }

        function animate() {

            renderer.setAnimationLoop(render);

        }

        function render() {

            handle(controller1);
            handle(controller2);

            renderer.render(scene, camera);

        }

    </script>
</body>

</html>
</code>```

xlayer=60 works in handle()(shows layer 60 other than defined in init()):

when its before the if clause of the controller.UserData

when its in it and I set it true right above the if clause

it doesn't work

whenever its in the if clause, even if something else in the if clause worked (like setting the background green)

I wonder if I did something wrong or if it just doesn't work like that.

Body:
I'm working with Three.js on a project. I just started working with it and mostly tried my luck with picking different things from the examples.
In short: I'm loading a volume and want to show another layer of it after the event listener for one of the controllers fired.

<!DOCTYPE html>

    <title>three.js vr - dragging</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <link type="text/css" rel="stylesheet" href="main.css">

        three.js nrrd

xlayer=60 works in handle()(shows layer 60 other than defined in init()):

when its before the if clause of the controller.UserData

when its in it and I set it true right above the if clause

it doesn't work

whenever its in the if clause, even if something else in the if clause worked (like setting the background green)

I wonder if I did something wrong or if it just doesn't work like that.


来源: stackexchange

问:
an error occurs when starting the server : Bad state: Package file
aqueduct serve
-- Aqueduct CLI Version: 3.3.0+1
-- Aqueduct project version: 3.3.0+1
-- Preparing...
*** Uncaught error
Bad state: Package file 'file:///home/superuserfucker/Documents/Code/Flutter/srvrs/server/.packages' not found. Run 'pub get' and retry.
**** Stacktrace

#0      IsolateExecutor.execute (package:isolate_executor/src/executor.dart:25:7)

#1      IsolateExecutor.run (package:isolate_executor/src/executor.dart:94:21)

#2      CLIServer.deriveApplicationLibraryDetails (package:aqueduct/src/cli/commands/serve.dart:183:40)

#3      CLIServer.prepare (package:aqueduct/src/cli/commands/serve.dart:206:32)

#4      CLIServer.handle (package:aqueduct/src/cli/commands/serve.dart:87:11)

#5      CLICommand.process (package:aqueduct/src/cli/command.dart:159:20)

#6      main (file:///home/superuserfucker/.pub-cache/hosted/pub.dartlang.org/aqueduct-3.3.0+1/bin/aqueduct.dart:9:14)

ContentLicense: CC BY-SA 4.0


问:
In Fortify how to exclude all java classes in a folder
I want to exclude all java classes that are underneath test folder from translations and scans. I have tried to use the -exclude parameter but it doesn't seem to work.

```<code># This is a basic workflow to help you get started with running Fortify scans using ScanCentral into Fortify SSC
name: Fortify Scan
on:
  workflow_dispatch:
jobs:
  Fortify:
    runs-on: windows-latest
    steps:
      - uses: actions/checkout@v2
      # Run ScanCentral scan on application
      - name: Run ScanCentral Scan
        run: |
          scancentral arguments -targs "-exclude ${{ github.workspace }}\**\test\**\*"
          scancentral -sscurl https://fortify.hello.com/ssc -ssctoken ${{ secrets.FORTIFY_SCANCENTRAL_TOKEN }} start -bt none -upload -uptoken ${{ secrets.FORTIFY_SCANCENTRAL_TOKEN }} -versionid 101
</code>```

I tried multiple ways to exclude but none of them worked. Few of the exclude arguments used are as below.

Using full Path

```<code>scancentral arguments -targs "-exclude ${{ github.workspace }}\src\test\java\com\Testwalk.java"
</code>```

Using Path with "/" instead ""

```<code>scancentral arguments -targs "-exclude ${{ github.workspace }}/**/test/**/*"
</code>```

Using the file extension format

```<code>scancentral arguments -targs "-exclude ${{ github.workspace }}\**\test\**\*.java"
</code>```

But None of the above ways worked. Please let me know where I am doing wrong or any suggestions to resolve this issue.

Body:
I want to exclude all java classes that are underneath test folder from translations and scans. I have tried to use the -exclude parameter but it doesn't seem to work.

# This is a basic workflow to help you get started with running Fortify scans using ScanCentral into Fortify SSC
name: Fortify Scan
on:
  workflow_dispatch:
jobs:
  Fortify:
    runs-on: windows-latest
    steps:
      - uses: actions/checkout@v2
      # Run ScanCentral scan on application
      - name: Run ScanCentral Scan
        run: |
          scancentral arguments -targs "-exclude ${{ github.workspace }}\**\test\**\*"
          scancentral -sscurl https://fortify.hello.com/ssc -ssctoken ${{ secrets.FORTIFY_SCANCENTRAL_TOKEN }} start -bt none -upload -uptoken ${{ secrets.FORTIFY_SCANCENTRAL_TOKEN }} -versionid 101

I tried multiple ways to exclude but none of them worked. Few of the exclude arguments used are as below.

Using full Path

scancentral arguments -targs "-exclude ${{ github.workspace }}\src\test\java\com\Testwalk.java"

Using Path with "/" instead ""

scancentral arguments -targs "-exclude ${{ github.workspace }}/**/test/**/*"

Using the file extension format

scancentral arguments -targs "-exclude ${{ github.workspace }}\**\test\**\*.java"

But None of the above ways worked. Please let me know where I am doing wrong or any suggestions to resolve this issue.


问:
Transfrer file from raspberry pi to file server on same network with python
I have a raspberry pi taking pictures, that is connected to the LAN. I want to automatically upload each picture file to a samba ubuntu file server I have on my network, so I can easily view them.

I have tried to get the command "curl" with no luck. (which I would run with subprocess in python)
This is my command that doesn't work (trying to copy test.png to destination directory):

curl -T "/home/pi/Desktop/test.png" "smb://10.51.112.128/home/thomas/thomasdrive/destination" -u thomas:87651234

I get:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current Dload  Upload   Total   Spent    Left  Speed 0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0 curl: (7) Couldn't connect to server

I've been searching the internet for a solution, but nothing I try seems to work


问:
Error No bean named 'mvcConversionService' available
I am upgrading springboot 2.7 from 1.5 and using springdoc.
I can compile and generate war file but when running it in webserver, there is this error:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webConversionServiceProvider' defined in class path resource [org/springdoc/core/SpringDocConfiguration$WebConversionServiceConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mvcConversionService' available

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mvcConversionService' available
</code>```

I am running the springboot in tomcat version 8.5.

Body:
I am upgrading springboot 2.7 from 1.5 and using springdoc.
I can compile and generate war file but when running it in webserver, there is this error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webConversionServiceProvider' defined in class path resource [org/springdoc/core/SpringDocConfiguration$WebConversionServiceConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mvcConversionService' available

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mvcConversionService' available

I am running the springboot in tomcat version 8.5.


问:
How can I use Authorize attribute in .net core 6 razor pages?
I have 2 projects.

1- Web
2- Api

In my login web page, I am hitting the API authinticate method.

here is my code:

```<code> var userName = Request.Form["UserName"].ToString();
            var password = Request.Form["Password"].ToString();
            var login = new Models.Login();
            login.UserName = userName;
            login.Password = password;
            // Hit the api and check user name and password the request.
            var apiUrl = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("AppSettings")["BaseUrl"] +
                "/api/Authenticate/Authenticate";
            using (WebClient client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                string Json = JsonConvert.SerializeObject(login);
                var response = client.UploadString(apiUrl, Json);
                var result = JsonConvert.DeserializeObject<Models.LoginResponseModel>(response);
                if(result.code != 200)
                {
                    InvalidLogin = true;
                    return this.Page();
                }
                else
                {
                    var s = string.Format($"Bearer {0}", result.Message);
                    Response.Headers.Add("Authorization",s);
                    return  new RedirectToPageResult("/Employees");
                }

            }
</code>```

Now if things went fine.

I am redirecting users to Employees Page.

now if I use Authorize attribute in Employees page

```<code>   [Authorize]
    public class EmployeesModel : PageModel
    {
        public void OnGet()
        {
        }
    }
</code>```

I know as a workaround, I can check if token is there in the get of employees page like this:

```<code>  public void OnGet()
   {
     if (Request.Headers["Authorization"])
     {

     }
   }
</code>```

Any ideas ?

I did this workaround:

```<code>HttpContext.Session.SetString("Token", result.Message);
</code>```

in my controller api logout:

```<code>        [Route("[action]")]
        [HttpGet]
        public void Logout()
        {
            // Remove Token;
            HttpContext.Session.SetString("Token", "");
        }
</code>```

Body:
I have 2 projects.

1- Web
2- Api

In my login web page, I am hitting the API authinticate method.

here is my code:

 var userName = Request.Form["UserName"].ToString();
            var password = Request.Form["Password"].ToString();
            var login = new Models.Login();
            login.UserName = userName;
            login.Password = password;
            // Hit the api and check user name and password the request.
            var apiUrl = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("AppSettings")["BaseUrl"] +
                "/api/Authenticate/Authenticate";
            using (WebClient client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                string Json = JsonConvert.SerializeObject(login);
                var response = client.UploadString(apiUrl, Json);
                var result = JsonConvert.DeserializeObject<Models.LoginResponseModel>(response);
                if(result.code != 200)
                {
                    InvalidLogin = true;
                    return this.Page();
                }
                else
                {
                    var s = string.Format($"Bearer {0}", result.Message);
                    Response.Headers.Add("Authorization",s);
                    return  new RedirectToPageResult("/Employees");
                }

            }

Now if things went fine.

I am redirecting users to Employees Page.

now if I use Authorize attribute in Employees page

   [Authorize]
    public class EmployeesModel : PageModel
    {
        public void OnGet()
        {
        }
    }

I know as a workaround, I can check if token is there in the get of employees page like this:

  public void OnGet()
   {
     if (Request.Headers["Authorization"])
     {

     }
   }

Any ideas ?

I did this workaround:

HttpContext.Session.SetString("Token", result.Message);

in my controller api logout:

        [Route("[action]")]
        [HttpGet]
        public void Logout()
        {
            // Remove Token;
            HttpContext.Session.SetString("Token", "");
        }


问:
External source script not working while knitting the rmarkdown into document
I have large function in another R script. when I used it as a source and call the function, it is working fine but it does not work if I try to knit it into document.

```<code>    line73 source('PATH\\function.R', local = knitr::knit_global())
    line74 table1 <- demograph(arg1, arg2)
</code>```

here , demograph() is the function from external R scriptfunction.R
I can get the results in the console but while trying to knit it to document I got following error:

Quitting from lines 73-81 (vision_rmd.Rmd)
Error in eval(x, envir = envir) : object 'False' not found
Calls: <Anonymous> ... eval_lang -> in_input_dir -> in_dir -> eval -> eval
Execution halted

Body:
I have large function in another R script. when I used it as a source and call the function, it is working fine but it does not work if I try to knit it into document.

    line73 source('PATH\\function.R', local = knitr::knit_global())
    line74 table1 <- demograph(arg1, arg2)

here , demograph() is the function from external R scriptfunction.R
I can get the results in the console but while trying to knit it to document I got following error:

Quitting from lines 73-81 (vision_rmd.Rmd)
Error in eval(x, envir = envir) : object 'False' not found
Calls: <Anonymous> ... eval_lang -> in_input_dir -> in_dir -> eval -> eval
Execution halted


问:
Getting the Fetch API error with GoogleLogin OAuth
I'm using GoogleLogin in the @react-oauth/google package in my React app running on port 3000. When I'm fetching http://localhost:30001/auth/google I'm getting the error in the Chrome dev tools:

```<code>POST http://localhost:3001/auth/google net::ERR_CONNECTION_REFUSED
TypeError: Failed to fetch
</code>```

And in the Safari dev tools:

```<code>Fetch API cannot load http://localhost:3001/auth/google due to access control checks.
</code>```

I suspect the error is due to the CORS policy. How can I be absolutely sure of that?

I don't have access to the server, so I can't update the CORS policy from there. Is there anything at this point that I can do?

Note: The Response in the Network tab in the Chrome dev tools is empty & the Headers has Referrer Policy: strict-origin-when-cross-origin

Body:
I'm using GoogleLogin in the @react-oauth/google package in my React app running on port 3000. When I'm fetching http://localhost:30001/auth/google I'm getting the error in the Chrome dev tools:

POST http://localhost:3001/auth/google net::ERR_CONNECTION_REFUSED
TypeError: Failed to fetch

And in the Safari dev tools:

Fetch API cannot load http://localhost:3001/auth/google due to access control checks.

I suspect the error is due to the CORS policy. How can I be absolutely sure of that?

I don't have access to the server, so I can't update the CORS policy from there. Is there anything at this point that I can do?

Note: The Response in the Network tab in the Chrome dev tools is empty & the Headers has Referrer Policy: strict-origin-when-cross-origin


问:
Common tile layer settings for multiple vue2-leaflet maps
In my Vue (2.x) application, I have a number of places where I use vue2-leaflet maps.

There are a few common features of these maps, but they are otherwise completely different, so it doesn't make sense to have all of them use a single component that contains an <l-map> (and all other relevant map components).

In order to reduce copying an pasting, I have created a few mixins with common features. For example, I have written a mixin for any maps that need to be able to auto-fit to their contents, so the only thing I need to do in each component that uses it is add :bounds="autofitBounds" to the <l-map> component.

I wanted to do create something similar for the <l-tile-layer> component, because all of our maps use the same layers.

I created a mixin that provides the url and attribution for the tile layer like this:

```<code>export default {
    data () {
        return {
            url: process.env.VUE_APP_MAP_TILE_URL || 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
            attribution: process.env.VUE_APP_MAP_TILE_COPYRIGHT || '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors',
        };
    },
};
</code>```

I can use it by adding the mixin to my component and then adding the <l-tile-layer> component inside the <l-map> like this:

```<code><l-tile-layer :url="url" :attribution="attribution" />
</code>```

I wanted to see if there was a way to reduce the boilerplate further.

First, I tried to create it as a component instead, like this:

```<code><template>
    <l-tile-layer :url="url" :attribution="attribution" />
</template>

<script>
import { LTileLayer } from 'vue2-leaflet';

export default {
    name: 'MyTileLayer',
    components: {
        LTileLayer,
    },
    data () {
        return {
            url: process.env.VUE_APP_MAP_TILE_URL || 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
            attribution: process.env.VUE_APP_MAP_TILE_COPYRIGHT || '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors',
        };
    },
};
</script>
</code>```

Then I can use that component inside my <l-map> without needing to add any attributes to it, like this:

```<code><my-tile-layer>
</code>```

The problem is that this doesn't render properly. Here are two screenshots - the <l-tile-layer> used directly on the left, and the <my-tile-layer> wrapper on the right.

Is there a better way to create a tile layer component with default values? Or is there a way I can fix the rendering of <my-tile-layer>?

Body:
In my Vue (2.x) application, I have a number of places where I use vue2-leaflet maps.

There are a few common features of these maps, but they are otherwise completely different, so it doesn't make sense to have all of them use a single component that contains an <l-map> (and all other relevant map components).

In order to reduce copying an pasting, I have created a few mixins with common features. For example, I have written a mixin for any maps that need to be able to auto-fit to their contents, so the only thing I need to do in each component that uses it is add :bounds="autofitBounds" to the <l-map> component.

I wanted to do create something similar for the <l-tile-layer> component, because all of our maps use the same layers.

I created a mixin that provides the url and attribution for the tile layer like this:

export default {
    data () {
        return {
            url: process.env.VUE_APP_MAP_TILE_URL || 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
            attribution: process.env.VUE_APP_MAP_TILE_COPYRIGHT || '© OpenStreetMap contributors',
        };
    },
};

I can use it by adding the mixin to my component and then adding the <l-tile-layer> component inside the <l-map> like this:

<l-tile-layer :url="url" :attribution="attribution" />

I wanted to see if there was a way to reduce the boilerplate further.

First, I tried to create it as a component instead, like this:

<template>
    <l-tile-layer :url="url" :attribution="attribution" />
</template>

Then I can use that component inside my <l-map> without needing to add any attributes to it, like this:

<my-tile-layer>

The problem is that this doesn't render properly. Here are two screenshots - the <l-tile-layer> used directly on the left, and the <my-tile-layer> wrapper on the right.

Is there a better way to create a tile layer component with default values? Or is there a way I can fix the rendering of <my-tile-layer>?


问:
Ckeditor unable to generate pdf of large text file while changing fonts in some cases
when i changing the font in ckeditor of large text file more than 20 pages, unable to generate the document of texts this issue is with only 2 fonts for rest fonts it is working. If i add image file along with same text then able to generate the documentdocument.
Need help to resolve this.

How to fix this while changibg fonts or font size it should visible.


问:
How do you use the higher order reducer pattern to dynamically create new reducers?
https://github.com/wecreatesoftware/redux-higher-order-reducers

```<code>import {
    listReducer,
    objectReducer,
    stringReducer,
    booleanReducer,
    numberReducer,
} from "@wecreatesoftware/redux-higher-order-reducers"
import {
    LIST_A,
    LIST_B,
    LIST_C,
    OBJECT_A,
    OBJECT_B,
    STRING_A,
    STRING_B,
    BOOLEAN_A,
    NUMBER_A,
} from "../some/constant/file"

export const reducers = combineReducers({
    [ LIST_A ]: listReducer({ reducerName: LIST_A }),
    [ LIST_B ]: listReducer({ reducerName: LIST_B }),
    [ LIST_C ]: listReducer({
        reducerName: LIST_C,
        key: "id",
    }),
    [ OBJECT_A ]: objectReducer({ reducerName: OBJECT_A }),
    [ OBJECT_B ]: objectReducer({ reducerName: OBJECT_B }),
    [ STRING_A ]: stringReducer({ reducerName: STRING_A }),
    [ STRING_B ]: stringReducer({ reducerName: STRING_B }),
    [ BOOLEAN_A ]: booleanReducer({ reducerName: BOOLEAN_A }),
    [ NUMBER_A ]: numberReducer({ reducerName: NUMBER_A }),
})
</code>```

How do we add new Object reducers for example OBJECT_C, OBJECT_D, ... OBJECT_Z without preinstantiating them, and how do we give them a random reducer name (ex: 1a1290y7h83t_reducer)? I am trying to understand how to use this design pattern to be able to dynamically add and delete new reducer as I see fit using the higher-order-reducers pattern.

Body:
https://github.com/wecreatesoftware/redux-higher-order-reducers

import {
    listReducer,
    objectReducer,
    stringReducer,
    booleanReducer,
    numberReducer,
} from "@wecreatesoftware/redux-higher-order-reducers"
import {
    LIST_A,
    LIST_B,
    LIST_C,
    OBJECT_A,
    OBJECT_B,
    STRING_A,
    STRING_B,
    BOOLEAN_A,
    NUMBER_A,
} from "../some/constant/file"

export const reducers = combineReducers({
    [ LIST_A ]: listReducer({ reducerName: LIST_A }),
    [ LIST_B ]: listReducer({ reducerName: LIST_B }),
    [ LIST_C ]: listReducer({
        reducerName: LIST_C,
        key: "id",
    }),
    [ OBJECT_A ]: objectReducer({ reducerName: OBJECT_A }),
    [ OBJECT_B ]: objectReducer({ reducerName: OBJECT_B }),
    [ STRING_A ]: stringReducer({ reducerName: STRING_A }),
    [ STRING_B ]: stringReducer({ reducerName: STRING_B }),
    [ BOOLEAN_A ]: booleanReducer({ reducerName: BOOLEAN_A }),
    [ NUMBER_A ]: numberReducer({ reducerName: NUMBER_A }),
})

How do we add new Object reducers for example OBJECT_C, OBJECT_D, ... OBJECT_Z without preinstantiating them, and how do we give them a random reducer name (ex: 1a1290y7h83t_reducer)? I am trying to understand how to use this design pattern to be able to dynamically add and delete new reducer as I see fit using the higher-order-reducers pattern.


问:
Unable to convert numpy array into a tensor for model.fit
I am a beginner to ML and I am having trouble converting a numpy array into a tensor when fitting the model.

The error I get when I try

```<code>    test_audio_class(x_train.values, y_train.values, x_test.values, y_test.values)
</code>```

is

```<code>Traceback (most recent call last):
  File "classifier.py", line 51, in <module>
    test_audio_class(x_train.values, y_train.values, x_test.values, y_test.values)
  File "classifier.py", line 28, in test_audio_class
    history = model.fit(x_train, y_train, epochs = 10, validation_data = (x_test, y_test))

line 102, in convert_to_eager_tensor
    return ops.EagerTensor(value, ctx.device_name, dtype)
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type tensorflow.python.framework.ops.EagerTensor).

</code>```

I tried some print statements to figure out the error.

```<code>type of x_train = <class 'numpy.ndarray'>, values in x_train = <class 'tensorflow.python.framework.ops.EagerTensor'>
type of y_train = <class 'numpy.ndarray'>, values in y_train = <class 'str'>
</code>```

I know it has something to do with the EagerTensor that I am doing but not sure how to fix it.

Body:
I am a beginner to ML and I am having trouble converting a numpy array into a tensor when fitting the model.

The error I get when I try

    test_audio_class(x_train.values, y_train.values, x_test.values, y_test.values)

is

Traceback (most recent call last):
  File "classifier.py", line 51, in <module>
    test_audio_class(x_train.values, y_train.values, x_test.values, y_test.values)
  File "classifier.py", line 28, in test_audio_class
    history = model.fit(x_train, y_train, epochs = 10, validation_data = (x_test, y_test))

line 102, in convert_to_eager_tensor
    return ops.EagerTensor(value, ctx.device_name, dtype)
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type tensorflow.python.framework.ops.EagerTensor).

I tried some print statements to figure out the error.

type of x_train = <class 'numpy.ndarray'>, values in x_train = <class 'tensorflow.python.framework.ops.EagerTensor'>
type of y_train = <class 'numpy.ndarray'>, values in y_train = <class 'str'>

I know it has something to do with the EagerTensor that I am doing but not sure how to fix it.


问:
Specific container's class name causing children to disappear?
I have encountered this weird event when creating social media icons.
My original code is:

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
        integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>Document</title>
</head>

<body>
    <h3>Follow Us</h3>
    <div class="socials-container">
        <i class="fab fa-facebook"></i>
        <i class="fab fa-youtube"></i>
        <i class="fab fa-instagram"></i>
    </div>
</body>

</html>
</code>```

At first the icons inside the "socials-container" div did not appear. But they showed up when I removed the container.

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
        integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>Document</title>
</head>

<body>
    <h3>Follow Us</h3>
    <i class="fab fa-facebook"></i>
    <i class="fab fa-youtube"></i>
    <i class="fab fa-instagram"></i>
</body>

</html>
</code>```

Then I tried to rename the div's class to something like "social-container" (without the 's') the icons showed up.

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
        integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>Document</title>
</head>

<body>
    <h3>Follow Us</h3>
    <div class="social-container">
        <i class="fab fa-facebook"></i>
        <i class="fab fa-youtube"></i>
        <i class="fab fa-instagram"></i>
    </div>
</body>

</html>
</code>```

Does HTML have rules for class names that I don't know? Why is a specific class name causing children to not appear as usual?

Body:
I have encountered this weird event when creating social media icons.
My original code is:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
        integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>Document</title>

Follow Us

At first the icons inside the "socials-container" div did not appear. But they showed up when I removed the container.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
        integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>Document</title>

Follow Us

Then I tried to rename the div's class to something like "social-container" (without the 's') the icons showed up.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
        integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>Document</title>

Follow Us

Does HTML have rules for class names that I don't know? Why is a specific class name causing children to not appear as usual?


问:
Need to Find Number of returning user on big query
I have Transaction table contains (user_id and date).
I was wondering how to create a query to find number of returning user for each month during 2022.
In context, returning user on month X is a user that transacts on Month X and not transacts in Month X-1 But ever transact in < Month X - 1

I have tried this query

```<code> WITH raw as
(SELECT month, user_id as customer_id FROM table_a
WHERE month <= date("2022-12-31")),

last_month as (
  SELECT DATE_SUB(a.month, INTERVAL 1 MONTH) as last_month,customer_id FROM raw a
  WHERE a.month = DATE_SUB(a.month, INTERVAL 1 MONTH)
  AND a.month >= date('2022-01-01')
),

returning as (
  SELECT a.month, COUNT(DISTINCT a.customer_id) AS returning_users
  FROM rawa
  LEFT JOIN last_month b
  ON a.customer_id = b.customer_id
  AND a.month = b.last_month
  WHERE EXISTS (
    SELECT *
    FROM raw c
    WHERE
        c.customer_id = a.customer_id AND
        DATE(c.month) <= DATE_SUB(a.month, INTERVAL 2 MONTH)
    )
  AND a.month >= date('2022-01-01')
  GROUP BY 1
  ORDER BY 1
)

SELECT * FROM returning
</code>```

Body:
I have Transaction table contains (user_id and date).
I was wondering how to create a query to find number of returning user for each month during 2022.
In context, returning user on month X is a user that transacts on Month X and not transacts in Month X-1 But ever transact in < Month X - 1

I have tried this query

 WITH raw as
(SELECT month, user_id as customer_id FROM table_a
WHERE month <= date("2022-12-31")),

last_month as (
  SELECT DATE_SUB(a.month, INTERVAL 1 MONTH) as last_month,customer_id FROM raw a
  WHERE a.month = DATE_SUB(a.month, INTERVAL 1 MONTH)
  AND a.month >= date('2022-01-01')
),

returning as (
  SELECT a.month, COUNT(DISTINCT a.customer_id) AS returning_users
  FROM rawa
  LEFT JOIN last_month b
  ON a.customer_id = b.customer_id
  AND a.month = b.last_month
  WHERE EXISTS (
    SELECT *
    FROM raw c
    WHERE
        c.customer_id = a.customer_id AND
        DATE(c.month) <= DATE_SUB(a.month, INTERVAL 2 MONTH)
    )
  AND a.month >= date('2022-01-01')
  GROUP BY 1
  ORDER BY 1
)

SELECT * FROM returning


问:
Why is my ReactTooltip changing padding size after revisiting a webpage?
When just visiting my main webpage, the tooltip when hovering over the countries in my react-simple-maps map looks pretty normal:
tooltip

However, after going to a different webpage, and then promptly returning to the map-containing webpage (same URL), the tooltip's padding changes:
changed tooltip

Here is the code behind my tooltip:

```<code><ReactTooltip>
  <div className="bg-gray-800 text-white rounded p-[8px]">
    <div className="text-[16px] font-bold">
      {Name}
    </div>
    <div className="text-[14px]">
      No information available right now
    </div>
  </div>
</ReactTooltip>
</code>```

I assume the issue lies in server/client-side rendering, since the strange border (which I assume to be the p-[8px] only appears after re-entering the webpage). However, I am still inexperienced. Any ways to fix this?

Thanks!

I tried putting the className directly into , but that resulted in a clear background... Then I just tried moving different stylings around but nothing seemed to do the trick.

Body:
When just visiting my main webpage, the tooltip when hovering over the countries in my react-simple-maps map looks pretty normal:
tooltip

However, after going to a different webpage, and then promptly returning to the map-containing webpage (same URL), the tooltip's padding changes:
changed tooltip

Here is the code behind my tooltip:

<ReactTooltip>

      {Name}

      No information available right now

</ReactTooltip>

I assume the issue lies in server/client-side rendering, since the strange border (which I assume to be the p-[8px] only appears after re-entering the webpage). However, I am still inexperienced. Any ways to fix this?

Thanks!

I tried putting the className directly into , but that resulted in a clear background... Then I just tried moving different stylings around but nothing seemed to do the trick.


问:
How can I compute the nullspace of a matrix where the nullspace contains elements which are NON ZERO and WHOLE numbers
First id like to say I know that some matrices will not be able to have a nullspace that fits my qualifications. Im looking for an algorithm that could produce a matrix with non zero whole integer values in the first columns of the nullspace matrix computed.

import numpy as np
from sympy import Matrix

A = np.array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [1, 0, 1, 0, 1], [1, 1, 1, 0, 0]])
N = np.array([[1], [1], [-2], [1], [1]]) # <==== i want to get a result like this

M = Matrix(A)
print(M * Matrix(N))
print(M.nullspace())
```
<p>Output:</p>
```Matrix([[0], [0], [0], [0]])

[Matrix([
[ 1],
[ 0],
[-1],
[ 1],
[ 0]]), Matrix([
[ 0],
[ 1],
[-1],
[ 0],
[ 1]])]
```

I tried to get the nullspace of a matrix but the results were either 0 or non integer values.

Body:
First id like to say I know that some matrices will not be able to have a nullspace that fits my qualifications. Im looking for an algorithm that could produce a matrix with non zero whole integer values in the first columns of the nullspace matrix computed.

import numpy as np
from sympy import Matrix

A = np.array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [1, 0, 1, 0, 1], [1, 1, 1, 0, 0]])
N = np.array([[1], [1], [-2], [1], [1]]) # <==== i want to get a result like this

M = Matrix(A)
print(M * Matrix(N))
print(M.nullspace())

Output:

Matrix([[0], [0], [0], [0]])

[Matrix([
[ 1],
[ 0],
[-1],
[ 1],
[ 0]]), Matrix([
[ 0],
[ 1],
[-1],
[ 0],
[ 1]])]

I tried to get the nullspace of a matrix but the results were either 0 or non integer values.


问:
How to prevent memory leakage while converting from UIImage to CIImage
I am trying to convert UIImage to CIImage, but it increases the memory by 80-100 MB. Is this a memory leakage? If so, is there any possible way to reduce the memory leakage on converting UIImage to CIImage?

Here's my code:

```<code>extension UIImage {
  func toCIImage() -> CIImage {
    return CIImage(cgImage: self.cgImage!)
  }
}
</code>```

Also, I am looking for a better solution that wouldn't result in a memory spike converting UIImage to CIImage.

Body:
I am trying to convert UIImage to CIImage, but it increases the memory by 80-100 MB. Is this a memory leakage? If so, is there any possible way to reduce the memory leakage on converting UIImage to CIImage?

Here's my code:

extension UIImage {
  func toCIImage() -> CIImage {
    return CIImage(cgImage: self.cgImage!)
  }
}

Also, I am looking for a better solution that wouldn't result in a memory spike converting UIImage to CIImage.


问:
Commas thousand separator to a float number
I have a software which reads excels fields in nodejs, captures the value and parse it to float, i want to print the result of the float number, Example: 1200.00 -> 1,200.00, any idea?

parseFloat(excelFileSheets.Hoja1[i]["TOTAL DE ING."]).toFixed(2);

I just tried

parseFloat(excelFileSheets.Hoja1[i]["TOTAL DE ING."]).toFixed(2).toLocaleString("DE-de");


问:
Plot Python data frame over multiple columns
I have a very huge Dataframe which I want to plot. I created a smaller one for demonstration here:
How can I plot this dataframe, I would like the columns to be the x axis and sum up all the values in bars


问:
AttributeError: 'numpy.ndarray' object has no attribute 'values' explored the existing solutions
```<code>AttributeError                            Traceback (most recent call last)

<ipython-input-113-4215b6c9f2c9> in <module>
      7     #kfold  = StratifiedShuffleSplit(n_splits=2, random_state=2, test_size=.25)
      8     #kf = KFold(n_splits=5, random_state=3,shuffle=True )
----> 9     cv_results = cross_val_score(model, X_train, Y_train.values.ravel(), cv=kfold, scoring='accuracy')
     10     results.append(cv_results)
     11     names.append(name)
</code>```
```<code>for name, model in models:
    kfold = StratifiedKFold(n_splits=3, random_state=1, shuffle=True)

    cv_results = cross_val_score(model, X_train, Y_train.values.ravel(), cv=kfold, scoring='accuracy')
    results.append(cv_results)
    names.append(name)
    print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))
</code>```

Body:
AttributeError                            Traceback (most recent call last)

<ipython-input-113-4215b6c9f2c9> in <module>
      7     #kfold  = StratifiedShuffleSplit(n_splits=2, random_state=2, test_size=.25)
      8     #kf = KFold(n_splits=5, random_state=3,shuffle=True )
----> 9     cv_results = cross_val_score(model, X_train, Y_train.values.ravel(), cv=kfold, scoring='accuracy')
     10     results.append(cv_results)
     11     names.append(name)

for name, model in models:
    kfold = StratifiedKFold(n_splits=3, random_state=1, shuffle=True)

    cv_results = cross_val_score(model, X_train, Y_train.values.ravel(), cv=kfold, scoring='accuracy')
    results.append(cv_results)
    names.append(name)
    print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))


问:
In Flutter how do I read an asset that's in a Deferred Component using rootBundle.load()?
I have a Flutter app with some assets arriving via Deferred Components. The YAML looks something like this:

```<code>deferred-components:
     - name: arBlock11
       assets:
          - assets/unity/ch1/1/
          - assets/unity/ch1/2/
          - assets/unity/ch1/3/
</code>```

And I'm attempting to read the files like this:

```<code>ByteData assetFile = await rootBundle.load('assets/unity/ch1/1/big.file.ecm');
</code>```

When I test locally, this works. But when I test in the Play Store with real Deferred Components downloading, I get this error:

```<code>01-10 19:19:32.552 15229 15267 E flutter : [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unable to load asset: assets/unity/ch1/1/big.file.ecm
</code>```

What gives? How do I access the actual file of an asset in a Deferred Component?

Thank you!

Body:
I have a Flutter app with some assets arriving via Deferred Components. The YAML looks something like this:

deferred-components:
     - name: arBlock11
       assets:
          - assets/unity/ch1/1/
          - assets/unity/ch1/2/
          - assets/unity/ch1/3/

And I'm attempting to read the files like this:

ByteData assetFile = await rootBundle.load('assets/unity/ch1/1/big.file.ecm');

When I test locally, this works. But when I test in the Play Store with real Deferred Components downloading, I get this error:

01-10 19:19:32.552 15229 15267 E flutter : [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unable to load asset: assets/unity/ch1/1/big.file.ecm

What gives? How do I access the actual file of an asset in a Deferred Component?

Thank you!


问:
AWS Cognito with federated social provider(Google,Facebook,Apple) android java
How to insert the Credentials (Token, E- mail ID) fetched from Social media Login account in AWS Cognito Database?

Tried using following code

```<code> AWSMobileClient.getInstance().initialize(this, new Callback<UserStateDetails>() {
                @Override
                public void onResult(UserStateDetails userStateDetails) {
                    Log.i("INIT", String.valueOf(userStateDetails.getUserState()));
                    AWSMobileClient.getInstance().federatedSignIn(IdentityProvider.GOOGLE.toString(), account.getIdToken(), new Callback<UserStateDetails>() {
                        @Override
                        public void onResult(final UserStateDetails userStateDetails) {
                            //Handle the result
                            Log.i(TAG, "mobileClient Google login result: " + userStateDetails.getUserState().toString());
                         //   AWSCredentials credentials = mobileClient.getCredentials();
                           // Log.i(TAG, "mobileClient Google login, posting credentials event..."+credentials.getAWSSecretKey());
                        }

                        @Override
                        public void onError(Exception e) {
                            Log.e(TAG, "sign-in error", e);
                        }
                    });
</code>```

Expectation : Need to insert data in AWS Cognito user pool

Body:
How to insert the Credentials (Token, E- mail ID) fetched from Social media Login account in AWS Cognito Database?

Tried using following code

 AWSMobileClient.getInstance().initialize(this, new Callback<UserStateDetails>() {
                @Override
                public void onResult(UserStateDetails userStateDetails) {
                    Log.i("INIT", String.valueOf(userStateDetails.getUserState()));
                    AWSMobileClient.getInstance().federatedSignIn(IdentityProvider.GOOGLE.toString(), account.getIdToken(), new Callback<UserStateDetails>() {
                        @Override
                        public void onResult(final UserStateDetails userStateDetails) {
                            //Handle the result
                            Log.i(TAG, "mobileClient Google login result: " + userStateDetails.getUserState().toString());
                         //   AWSCredentials credentials = mobileClient.getCredentials();
                           // Log.i(TAG, "mobileClient Google login, posting credentials event..."+credentials.getAWSSecretKey());
                        }

                        @Override
                        public void onError(Exception e) {
                            Log.e(TAG, "sign-in error", e);
                        }
                    });

Expectation : Need to insert data in AWS Cognito user pool


问:
Imverse software not finishing instqalling
I am having an issue with installing imverse software, I have downloaded the necessary prerequisite resources to run the software, but every time I try to install it it halts halfway and directs me to a dump file for error report, but cant read the error report too
Can anyone guide me on how to go about installing the software?
I am a beginner and would appreciate it if you can keep the instructions as simple as possible
Thanks, in advanceenter image description here

I tried reading the dump file for the error report, but not sure how to open it


问:
How to display a file instead of downloading it with react
I use nx to build react apps and deploy it to vercel. I am able to generate .well-known folder with stellar.toml file inside it and then reference it in index.html like this:

```<code><!DOCTYPE html>
<html
    lang="en"
    clasName="h-full">
    <head>
        ...

        <meta
            name="viewport"
            content="width=device-width, initial-scale=1" />
        <link
            rel="stellar.toml file"
            href="%PUBLIC_URL%/.well-known/stellar.toml" />

        ...

    </head>
    <body className="h-full">
        <div id="root"></div>
    </body>
</html>
</code>```

The deployment is successful, but any time I want to display the file when entering {domain}/.well-known/stellar.toml it's prompting me to download it instead of displaying it in the tab.

I am using react-router also in case it's better to do it with react-router. Is there a way to just display it instead of the download prompt?

Body:
I use nx to build react apps and deploy it to vercel. I am able to generate .well-known folder with stellar.toml file inside it and then reference it in index.html like this:

<!DOCTYPE html>

        ...

        <meta
            name="viewport"
            content="width=device-width, initial-scale=1" />
        <link
            rel="stellar.toml file"
            href="%PUBLIC_URL%/.well-known/stellar.toml" />

        ...

The deployment is successful, but any time I want to display the file when entering {domain}/.well-known/stellar.toml it's prompting me to download it instead of displaying it in the tab.

I am using react-router also in case it's better to do it with react-router. Is there a way to just display it instead of the download prompt?


问:
How to setNavigationBarHidden only on two of the three viewControllers under one tabBar controller
I'm using a tabBar controller to control three viewControllers and want to set the navigationBar hidden only on two viewControllers, but it's not working.

picture of the structure of the tabBarController and three controllers
This is the current tabBarController and viewControllers. I have a viewController for my tabBar Controller, and I set a navigationBar on that viewController

```<code>class PlayerTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        configureNavBar()
    }

    func configureNavBar() {
        let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 10))
        backButton.setImage(UIImage(named: "leave 1"), for: .normal)
        backButton.addTarget(self, action: #selector(onBackPressed), for: .touchUpInside)
        let barBackButton = UIBarButtonItem(customView: backButton)
        self.navigationItem.leftBarButtonItem = barBackButton
    }

    @objc func onBackPressed() {
        self.navigationController?.popViewController(animated: true)
    }
}
</code>```

TeamViewController is the screen that I want to show the navBar, so I'm not doing anything to that viewController, and I'm using this code to hide the navBar in other two controllers(timerView and rankingView)

```<code>override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
</code>```

The problem is that when I go to one of the two controllers, the navBar is hidden, but the navBar is visible when I move between the two screens(timer and ranking). For example, when I go to the timer or ranking screen from team screen, it works. But when I move from timer to ranking, the navBar is visible on the ranking screen and vice versa. How can I fix this problem?

Body:
I'm using a tabBar controller to control three viewControllers and want to set the navigationBar hidden only on two viewControllers, but it's not working.

picture of the structure of the tabBarController and three controllers
This is the current tabBarController and viewControllers. I have a viewController for my tabBar Controller, and I set a navigationBar on that viewController

class PlayerTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        configureNavBar()
    }

    func configureNavBar() {
        let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 10))
        backButton.setImage(UIImage(named: "leave 1"), for: .normal)
        backButton.addTarget(self, action: #selector(onBackPressed), for: .touchUpInside)
        let barBackButton = UIBarButtonItem(customView: backButton)
        self.navigationItem.leftBarButtonItem = barBackButton
    }

    @objc func onBackPressed() {
        self.navigationController?.popViewController(animated: true)
    }
}

TeamViewController is the screen that I want to show the navBar, so I'm not doing anything to that viewController, and I'm using this code to hide the navBar in other two controllers(timerView and rankingView)

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }

The problem is that when I go to one of the two controllers, the navBar is hidden, but the navBar is visible when I move between the two screens(timer and ranking). For example, when I go to the timer or ranking screen from team screen, it works. But when I move from timer to ranking, the navBar is visible on the ranking screen and vice versa. How can I fix this problem?


问:
Spring boot Multi threaded Scheduler
I want to run 3 different scheduled tasks.

```<code>    @Scheduled(cron = "00 30 05 * * *")
    public void task1(){
    }

    @Scheduled(initialDelay = 20, fixedDelay = 2700000)
    public void task2(){
    }

    @Scheduled(cron = "00 45 05 * * *")
    public void task3(){
    }
</code>```

Task 2 will run for at least 25 minutes. if task 2 started at 05:25, the other two tasks were not executed as planned.

So, I updated the ThreadPoolTaskScheduler as follows

```<code>    final ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

    threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
    threadPoolTaskScheduler.setThreadNamePrefix("custom-scheduled-task-pool-");
    threadPoolTaskScheduler.initialize();

    scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
</code>```

Even after modifying, it is not executing as expected.

Could you please tell me what is the problem?

Title: Spring boot Multi threaded Scheduler

Body:
I want to run 3 different scheduled tasks.

    @Scheduled(cron = "00 30 05 * * *")
    public void task1(){
    }

    @Scheduled(initialDelay = 20, fixedDelay = 2700000)
    public void task2(){
    }

    @Scheduled(cron = "00 45 05 * * *")
    public void task3(){
    }

Task 2 will run for at least 25 minutes. if task 2 started at 05:25, the other two tasks were not executed as planned.

So, I updated the ThreadPoolTaskScheduler as follows

    final ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

    threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
    threadPoolTaskScheduler.setThreadNamePrefix("custom-scheduled-task-pool-");
    threadPoolTaskScheduler.initialize();

    scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);

Even after modifying, it is not executing as expected.

Could you please tell me what is the problem?


问:
Jenkins Pipeline script : Is there a way to call credentials() helper function from within another function
My Jenkins script is calling the credentials() helper function from outside of the environment section as below

```<code>environment {
    VAULT_NONPROD = getVaultCredentialsNonProd(vaultConfig)
}
</code>```

and then the function is defined as

```<code>def getVaultCredentialsNonProd(vaultConfig) {
    if (vaultConfig) {
        return credentials("${vaultConfig.appRoleCredentialsIdNonProd}")
}
</code>```

But in this case, the value of vaultConfig.appRoleCredentialsIdNonProd is NULL.

The other way is to call the credentials() function from within the environment block itself

```<code>VAULT_NONPROD = credentials("${vaultConfig.appRoleCredentialsIdNonProd}")
</code>```

This works, but here the problem is that if any of the applications that use this Jenkins script doesn't have the vaultConfig defined, then the script fails.
Is there a solution to this problem?

Body:
My Jenkins script is calling the credentials() helper function from outside of the environment section as below

environment {
    VAULT_NONPROD = getVaultCredentialsNonProd(vaultConfig)
}

and then the function is defined as

def getVaultCredentialsNonProd(vaultConfig) {
    if (vaultConfig) {
        return credentials("${vaultConfig.appRoleCredentialsIdNonProd}")
}

But in this case, the value of vaultConfig.appRoleCredentialsIdNonProd is NULL.

The other way is to call the credentials() function from within the environment block itself

VAULT_NONPROD = credentials("${vaultConfig.appRoleCredentialsIdNonProd}")

This works, but here the problem is that if any of the applications that use this Jenkins script doesn't have the vaultConfig defined, then the script fails.
Is there a solution to this problem?


问:
Angular 15 global not defined
I am trying to configure CognitoAuth with Angular v15. I was following this tutorial

This is the error I am getting.

```<code>Uncaught ReferenceError: global is not defined
    at 4768 (index.js:43:30)
    at __webpack_require__ (bootstrap:19:1)
    at 2634 (AuthenticationDetails.js:65:4)
    at __webpack_require__ (bootstrap:19:1)
    at 3843 (UserAgent.js:19:25)
    at __webpack_require__ (bootstrap:19:1)
    at 8562 (vendor.js:26:84)
    at __webpack_require__ (bootstrap:19:1)
    at 8139 (app.module.ts:20:16)
    at __webpack_require__ (bootstrap:19:1)
</code>```

All the solutions for this error point to adding (window as any).global = window; to polyfills.ts file. Since polyfills has been removed since v15 of Angular, I tried creating the file manually and adding it, but still it gives me the same error.

Can someone help me how to solve this in the latest Angular version. Thanks.

Title: Angular 15 global not defined

Body:
I am trying to configure CognitoAuth with Angular v15. I was following this tutorial

This is the error I am getting.

Uncaught ReferenceError: global is not defined
    at 4768 (index.js:43:30)
    at __webpack_require__ (bootstrap:19:1)
    at 2634 (AuthenticationDetails.js:65:4)
    at __webpack_require__ (bootstrap:19:1)
    at 3843 (UserAgent.js:19:25)
    at __webpack_require__ (bootstrap:19:1)
    at 8562 (vendor.js:26:84)
    at __webpack_require__ (bootstrap:19:1)
    at 8139 (app.module.ts:20:16)
    at __webpack_require__ (bootstrap:19:1)

All the solutions for this error point to adding (window as any).global = window; to polyfills.ts file. Since polyfills has been removed since v15 of Angular, I tried creating the file manually and adding it, but still it gives me the same error.

Can someone help me how to solve this in the latest Angular version. Thanks.


问:
How to add comments in particular text in the Docs file using python
i want to add comments in particular text in my microsoft document using python Bayoo-docx and python-docx can anyone please help me. I am using Bayoo-docx.

I want some help with the bayoo-docx and python-docx code.


问:
Run a test in React
I'm trying to run my test in a react project created with "npx create-react-app my-app --template typescript".
but I'm geting this error:

```<code>SyntaxError: Cannot use import statement outside a module

      1 | import { useState } from "react";
    > 2 | import axios, { RawAxiosRequestHeaders, AxiosResponse } from "axios";
        | ^
</code>```

what can I do to solve it?
here is my test code:

```<code>import useAxios from "./useAxios";
import axios from "axios";

describe("useAxios", () => {
    test("should make a request and return data", async () => {
        const mockData = { name: "John", age: 25 };
        const mockUrl = "some/url";
        const mockMethod = "GET";

        const spy = jest
            .spyOn(axios, "request")
            .mockResolvedValue({ data: mockData });

        const hook = useAxios();
        const promise = hook.request({ url: mockUrl, method: mockMethod });

        await promise;

        expect(hook.data).toEqual(mockData);
        expect(hook.error).toBe(null);
        expect(hook.loading).toBe(false);
        expect(spy).toHaveBeenCalledWith({
            url: mockUrl,
            method: mockMethod,
            headers: { "Content-Type": "application/json" },
            data: null,
        });
        spy.mockRestore();
    });

    test("should make a request and return error", async () => {
        const mockError = new Error("network error");
        const mockUrl = "some/url";
        const mockMethod = "GET";

        const spy = jest.spyOn(axios, "request").mockRejectedValue(mockError);

        const hook = useAxios();
        const promise = hook.request({ url: mockUrl, method: mockMethod });

        await expect(promise).rejects.toEqual(mockError);

        expect(hook.data).toBe(null);
        expect(hook.error).toEqual(mockError);
        expect(hook.loading).toBe(false);
        expect(spy).toHaveBeenCalledWith({
            url: mockUrl,
            method: mockMethod,
            headers: { "Content-Type": "application/json" },
            data: null,
        });
        spy.mockRestore();
    });
});
</code>```

and here is my hook code:

```<code>import { useState } from "react";
import axios, { RawAxiosRequestHeaders, AxiosResponse } from "axios";

export type RequestStates = {
    data: object | null;
    error: object | null;
    loading: boolean | null;
};

type Request = {
    url: string;
    method: string;
    body?: object | null;
    headers?: RawAxiosRequestHeaders;
};

const API = "............";
axios.defaults.baseURL = API;

const useAxios = () => {
    const [data, setData] = useState<RequestStates["data"]>(null);
    const [error, setError] = useState<RequestStates["error"]>(null);
    const [loading, setLoading] = useState<RequestStates["loading"]>(null);

    const request = async ({
        url,
        method,
        body = null,
        headers = {
            "Content-Type": "application/json",
        },
    }: Request) => {
        let successRequest: boolean;
        try {
            setLoading(true);
            setError(null)
            setData(null);
            const response: AxiosResponse<any, any> = await axios(url, {
                method: method,
                headers: headers,
                data: body,
            });
            setData(response.data);
            successRequest = true;
        } catch (err: any) {
            successRequest = false;
            setError(err);
        } finally {
            setLoading(false);
            return successRequest!;
        }
    };
    return { data, error, loading, request, setData, setError, setLoading };
};

export default useAxios;

</code>```

I'm trying to run the test, and it works if I use "require", but I wanna use Import.
It's about a custom hook called "useAXios"

Title: Run a test in React

Body:
I'm trying to run my test in a react project created with "npx create-react-app my-app --template typescript".
but I'm geting this error:

SyntaxError: Cannot use import statement outside a module

      1 | import { useState } from "react";
    > 2 | import axios, { RawAxiosRequestHeaders, AxiosResponse } from "axios";
        | ^

what can I do to solve it?
here is my test code:

import useAxios from "./useAxios";
import axios from "axios";

describe("useAxios", () => {
    test("should make a request and return data", async () => {
        const mockData = { name: "John", age: 25 };
        const mockUrl = "some/url";
        const mockMethod = "GET";

        const spy = jest
            .spyOn(axios, "request")
            .mockResolvedValue({ data: mockData });

        const hook = useAxios();
        const promise = hook.request({ url: mockUrl, method: mockMethod });

        await promise;

        expect(hook.data).toEqual(mockData);
        expect(hook.error).toBe(null);
        expect(hook.loading).toBe(false);
        expect(spy).toHaveBeenCalledWith({
            url: mockUrl,
            method: mockMethod,
            headers: { "Content-Type": "application/json" },
            data: null,
        });
        spy.mockRestore();
    });

    test("should make a request and return error", async () => {
        const mockError = new Error("network error");
        const mockUrl = "some/url";
        const mockMethod = "GET";

        const spy = jest.spyOn(axios, "request").mockRejectedValue(mockError);

        const hook = useAxios();
        const promise = hook.request({ url: mockUrl, method: mockMethod });

        await expect(promise).rejects.toEqual(mockError);

        expect(hook.data).toBe(null);
        expect(hook.error).toEqual(mockError);
        expect(hook.loading).toBe(false);
        expect(spy).toHaveBeenCalledWith({
            url: mockUrl,
            method: mockMethod,
            headers: { "Content-Type": "application/json" },
            data: null,
        });
        spy.mockRestore();
    });
});

and here is my hook code:

import { useState } from "react";
import axios, { RawAxiosRequestHeaders, AxiosResponse } from "axios";

export type RequestStates = {
    data: object | null;
    error: object | null;
    loading: boolean | null;
};

type Request = {
    url: string;
    method: string;
    body?: object | null;
    headers?: RawAxiosRequestHeaders;
};

const API = "............";
axios.defaults.baseURL = API;

const useAxios = () => {
    const [data, setData] = useState<RequestStates["data"]>(null);
    const [error, setError] = useState<RequestStates["error"]>(null);
    const [loading, setLoading] = useState<RequestStates["loading"]>(null);

    const request = async ({
        url,
        method,
        body = null,
        headers = {
            "Content-Type": "application/json",
        },
    }: Request) => {
        let successRequest: boolean;
        try {
            setLoading(true);
            setError(null)
            setData(null);
            const response: AxiosResponse<any, any> = await axios(url, {
                method: method,
                headers: headers,
                data: body,
            });
            setData(response.data);
            successRequest = true;
        } catch (err: any) {
            successRequest = false;
            setError(err);
        } finally {
            setLoading(false);
            return successRequest!;
        }
    };
    return { data, error, loading, request, setData, setError, setLoading };
};

export default useAxios;

I'm trying to run the test, and it works if I use "require", but I wanna use Import.
It's about a custom hook called "useAXios"


问:
I have some issue about using useRouter | Next js
This is my first time using useRouter and i really dont know how it works.
I want to take props.indexUrl and added dynamiacally into the url below, i have done several ways but always getting error.

import { useRouter } from "next/router";

const Component = () => {
    const router = useRouter();

    const {
        query: { indexUrl },
    } = router;

    const props = {
        indexUrl,
    };

    return props.indexUrl;
};

export const urls = [
    {
        url:
            "click.myyellowlocal.com/k.php?ai=19202&url=http%3a%2f%2f" +
            Component,
    },
    {
        url: "cse.google.vu/url?q=https%3A%2F%2",
    },
    {
        url: "sazhs.co.kr/member/login.html?noMemberOrder=&returnUrl=http%3a%2f%2",
    },
];

```
<p>I have try like this before</p>
<pre class="lang-js prettyprint-override"><code>import { useRouter } from "next/router";

const router = useRouter();

const {
    query: { indexUrl },
} = router;

const props = {
    indexUrl,
};

export const urls = [
    {
        url:
            "click.myyellowlocal.com/k.php?ai=19202&url=http%3a%2f%2f" +
            props.indexUrl,
    },
    {
        url: "cse.google.vu/url?q=https%3A%2F%2",
    },
    {
        url: "sazhs.co.kr/member/login.html?noMemberOrder=&returnUrl=http%3a%2f%2",
    },
];
</code>```

and give an error Cannot read properties of null (reading 'useContext')

so i make like this

const Component = () => {
    const router = useRouter();

    const {
        query: { indexUrl },
    } = router;

    const props = {
        indexUrl,
    };
};

```
<p>but i dont know how to get props.indexUrl to url like in the top code.</p>
<p>more detail, the router indexUrl is from other file</p>
<pre class="lang-js prettyprint-override"><code>    function sendProps() {
        Router.push({
            // pathname: "/processUrl",
            pathname: "/urlList",
            query: { indexUrl },
        });
    }
</code>```

how to get the value of props.indexUrl and add it into the list of url dynamiacally ??

Body:
This is my first time using useRouter and i really dont know how it works.
I want to take props.indexUrl and added dynamiacally into the url below, i have done several ways but always getting error.

import { useRouter } from "next/router";

const Component = () => {
    const router = useRouter();

    const {
        query: { indexUrl },
    } = router;

    const props = {
        indexUrl,
    };

    return props.indexUrl;
};

export const urls = [
    {
        url:
            "click.myyellowlocal.com/k.php?ai=19202&url=http%3a%2f%2f" +
            Component,
    },
    {
        url: "cse.google.vu/url?q=https%3A%2F%2",
    },
    {
        url: "sazhs.co.kr/member/login.html?noMemberOrder=&returnUrl=http%3a%2f%2",
    },
];

I have try like this before

import { useRouter } from "next/router";

const router = useRouter();

const {
    query: { indexUrl },
} = router;

const props = {
    indexUrl,
};

export const urls = [
    {
        url:
            "click.myyellowlocal.com/k.php?ai=19202&url=http%3a%2f%2f" +
            props.indexUrl,
    },
    {
        url: "cse.google.vu/url?q=https%3A%2F%2",
    },
    {
        url: "sazhs.co.kr/member/login.html?noMemberOrder=&returnUrl=http%3a%2f%2",
    },
];

and give an error Cannot read properties of null (reading 'useContext')

so i make like this

const Component = () => {
    const router = useRouter();

    const {
        query: { indexUrl },
    } = router;

    const props = {
        indexUrl,
    };
};

but i dont know how to get props.indexUrl to url like in the top code.

more detail, the router indexUrl is from other file

    function sendProps() {
        Router.push({
            // pathname: "/processUrl",
            pathname: "/urlList",
            query: { indexUrl },
        });
    }

how to get the value of props.indexUrl and add it into the list of url dynamiacally ??


问:
How to add a new repo on GitHub Desktop without it's local path changing to it's parent directory?
When attempting to add an existing local repo on GitHub Desktop it will only create a repo for it's parent directory instead.

After choosing the desired local path of the repo i.e "/home/mk/Documents/dev/projects/random-password-generator", the local path of the new repo reverts to "/home/mk/Documents/dev/projects".

The new repo contains all of the projects contained in the directory "projects" rather than creating a repo for the specific directory that I am targeting, please help :).

`Adding a new local repo
New repo with incorrect local path
New repo containing all projects


问:
Using srec_cat to merge OpenBLT bootloader with firmware for initial production flash
Attempting to combine OpenBLT bootloader image with a firmware image to make one flash for production using srec_cat.  "warning: no execution start address record" is evident in the firmware.srec.

Flashing the bootloader and using the Microboot utility over USB with the firmware srec works perfectly fine.  Would like to have one flash binary for production purposes.

srec_cat bootloader.srec firmware.srec -o combined.srec

Yields a "warning: no execution start address record".  Attempting to ignore the warning and flash the combined.srec to STM32 hardware creates a non-booting flash.

srec_info bootloader.srec output:

Format: Motorola S-Record
Header: "bin/bootloader.srec"
Execution Start Address: 080001D9
Data:   08000000 - 0800381F

srec_info firmware.srec output:

Format: Motorola S-Record
Header: "http://srecord.sourceforge.net/"
srec_info: fw-latest.srec: 12918: warning: no execution start address record
Data:   08008000 - 0806CE43


问:
Formula to Convert other currency to USD currency different rate in different month
I want to know the formula to Convert other currency to USD currency different rate in different month. Please refer to attached image

I had tried IF and INDEX function, but when I drag down, error appears, it works in the first cells.