问:
Unix socket is sending stop request to the worker from time to time
I'm using Workerman to create a UNIX socket to which I'm connecting and searching keywords.  The problem is that from time to time (it could be after 1 second, or after 1 min, or even not all) stop signal is send to the workers and seems like the connection is closed and the program exits with error 500.

For example

```<code>  200    GET /keyword/keyword1 ................................... 1.08 ms
  200    GET /keyword/keyword2134 .............................. 1.02 ms
  200    GET /keyword/keyword343 .................................... 0.98 ms
  200    GET /keyword/keyword22 .................................... 1.12 ms
  200    GET /keyword/keywordkeyword ................................... 1.10 ms
worker stopped, and will be restarted
worker stopped
  500    GET /keyword/keyword1111111111 ................... 30003.81 ms
sending stop request to the worker
</code>```

This is how I start the server. The server loads Database and searches for keywords.

```<code>use Workerman\Worker;

require 'vendor/autoload.php';

$worker = new Worker('unix://' . __DIR__ . '/tmp.sock');
$worker->count = 2; // processes count

$DB = new DB();
$DB->load();

$worker->onWorkerStart = function ($worker)  use ($DB) {

    $worker->onConnect = function ($connection) {
    };

    $worker->onMessage = function ($connection, $data) use ($DB) {
        $res  = $DB->get_db($data);
        $connection->send($res);
    };
};

// Run worker
Worker::runAll();
</code>```

This is the client

```<code>    public function search($search)
    {
        try {
            $d = explode("\r\n", $search);

            $socket = 'unix://' . __DIR__ . '/tmp.sock';
            $instance = stream_socket_client($socket);
            $keys = [];

            foreach ($d as $keys) {
                fwrite($instance, $keys);
                $resp = fread($instance, 4096);
                $keys[] = $resp;
            }
        } catch (\Exception $e) {
            return response($e->getMessage(), 500);
        }

        foreach ($keys as $res) {
            return $res;
        }
    }
</code>```

It takes simple keywords from a search form.

Is that the correct way to connect to the Unix sockets?

I have the same setup but where it searches through HTTP and there is no issue only through tcp/unix sockets is the problem.

Body:
I'm using Workerman to create a UNIX socket to which I'm connecting and searching keywords.  The problem is that from time to time (it could be after 1 second, or after 1 min, or even not all) stop signal is send to the workers and seems like the connection is closed and the program exits with error 500.

For example

  200    GET /keyword/keyword1 ................................... 1.08 ms
  200    GET /keyword/keyword2134 .............................. 1.02 ms
  200    GET /keyword/keyword343 .................................... 0.98 ms
  200    GET /keyword/keyword22 .................................... 1.12 ms
  200    GET /keyword/keywordkeyword ................................... 1.10 ms
worker stopped, and will be restarted
worker stopped
  500    GET /keyword/keyword1111111111 ................... 30003.81 ms
sending stop request to the worker

This is how I start the server. The server loads Database and searches for keywords.

use Workerman\Worker;

require 'vendor/autoload.php';

$worker = new Worker('unix://' . __DIR__ . '/tmp.sock');
$worker->count = 2; // processes count

$DB = new DB();
$DB->load();

$worker->onWorkerStart = function ($worker)  use ($DB) {

    $worker->onConnect = function ($connection) {
    };

    $worker->onMessage = function ($connection, $data) use ($DB) {
        $res  = $DB->get_db($data);
        $connection->send($res);
    };
};

// Run worker
Worker::runAll();

This is the client

    public function search($search)
    {
        try {
            $d = explode("\r\n", $search);

            $socket = 'unix://' . __DIR__ . '/tmp.sock';
            $instance = stream_socket_client($socket);
            $keys = [];

            foreach ($d as $keys) {
                fwrite($instance, $keys);
                $resp = fread($instance, 4096);
                $keys[] = $resp;
            }
        } catch (\Exception $e) {
            return response($e->getMessage(), 500);
        }

        foreach ($keys as $res) {
            return $res;
        }
    }

It takes simple keywords from a search form.

Is that the correct way to connect to the Unix sockets?

I have the same setup but where it searches through HTTP and there is no issue only through tcp/unix sockets is the problem.


来源: stackexchange

问:
How to use Database login and Azure AD Authentication both in a react app at same time?
I have created a react app in which I have a login page as the first page and there are two ways to login into it, first one is using Azure AD and second is database login.
I have implemented the Azure ad login part with the help of protected routes and all the stuff.

Now in the same app I want to implement the Database Login but I'm unable to do so.
So how it can be done. If anyone can help me in this?

App.tsx code:-

```<code>import './css/App.css';
import { AuthenticatedTemplate, UnauthenticatedTemplate } from '@azure/msal-react';
import { Login } from './auth/Login';
import Routers from './components/Router/Routers';

function App() {
  return (
    <div>
        <Routers />
    </div>
  );
}

export default App;
</code>```

index.tsx code:-

```<code>import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { msalConfig } from "./auth/authConfig";

const msalInstance = new PublicClientApplication(msalConfig);
const container = document.getElementById("root");
const root = createRoot(container!);

root.render(
  <React.StrictMode>
    <MsalProvider instance={msalInstance}>
      <App />
    </MsalProvider>
  </React.StrictMode>
);

module.hot?.accept();
</code>```

Auth.tsx code:-

```<code>import { Navigate, Outlet, useLocation } from 'react-router-dom';
import {
    AuthenticatedTemplate,
    UnauthenticatedTemplate,
} from "@azure/msal-react";
import { useIsAuthenticated } from "@azure/msal-react";

export const PrivateRoutes = () => {
    const location = useLocation();
    const isAuthenticated = useIsAuthenticated();

    return isAuthenticated
        ? (
            <AuthenticatedTemplate>
                <Outlet />
            </AuthenticatedTemplate>
        )
        : <Navigate to="/Login" replace state={{ from: location }} />;
}

export const AnonymousRoutes = () => {

    const isAuthenticated = useIsAuthenticated();

    return isAuthenticated
        ? <Navigate to="/Home" replace />
        : (
            <UnauthenticatedTemplate>
                <Outlet />
            </UnauthenticatedTemplate>
        );
}

</code>```

Router.tsx code:-

```<code>import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Contact from "../pages/Contact";
import { Login } from "./pages/Login";
import { AnonymousRoutes, PrivateRoutes } from '../components/auth';

function Routers() {
  return (
    <div className="Routers">
      <BrowserRouter>
        <Routes>
          <Route element={<PrivateRoutes />}>
            <Route path="/" element={<Home />} />
            <Route path="/Home" element={<Home />} />
            <Route path="/About" element={<About />} />
            <Route path="/Contact" element={<Contact />} />
          </Route>
          <Route element={<AnonymousRoutes />}>
            <Route path="/login" element={<Login />} />
          </Route>
        </Routes>
        <Outlet />
      </BrowserRouter>
    </div>
  );
}
</code>```

So now with this code I want to implement database login also. Please suggest the possible way.

ContentLicense: CC BY-SA 4.0

Body:
I have created a react app in which I have a login page as the first page and there are two ways to login into it, first one is using Azure AD and second is database login.
I have implemented the Azure ad login part with the help of protected routes and all the stuff.

Now in the same app I want to implement the Database Login but I'm unable to do so.
So how it can be done. If anyone can help me in this?

App.tsx code:-

import './css/App.css';
import { AuthenticatedTemplate, UnauthenticatedTemplate } from '@azure/msal-react';
import { Login } from './auth/Login';
import Routers from './components/Router/Routers';

function App() {
  return (

        <Routers />

  );
}

export default App;

index.tsx code:-

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
import { msalConfig } from "./auth/authConfig";

const msalInstance = new PublicClientApplication(msalConfig);
const container = document.getElementById("root");
const root = createRoot(container!);

root.render(
  <React.StrictMode>
    <MsalProvider instance={msalInstance}>
      <App />
    </MsalProvider>
  </React.StrictMode>
);

module.hot?.accept();

Auth.tsx code:-

import { Navigate, Outlet, useLocation } from 'react-router-dom';
import {
    AuthenticatedTemplate,
    UnauthenticatedTemplate,
} from "@azure/msal-react";
import { useIsAuthenticated } from "@azure/msal-react";

export const PrivateRoutes = () => {
    const location = useLocation();
    const isAuthenticated = useIsAuthenticated();

    return isAuthenticated
        ? (
            <AuthenticatedTemplate>
                <Outlet />
            </AuthenticatedTemplate>
        )
        : <Navigate to="/Login" replace state={{ from: location }} />;
}

export const AnonymousRoutes = () => {

    const isAuthenticated = useIsAuthenticated();

    return isAuthenticated
        ? <Navigate to="/Home" replace />
        : (
            <UnauthenticatedTemplate>
                <Outlet />
            </UnauthenticatedTemplate>
        );
}

Router.tsx code:-

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Contact from "../pages/Contact";
import { Login } from "./pages/Login";
import { AnonymousRoutes, PrivateRoutes } from '../components/auth';

function Routers() {
  return (

      <BrowserRouter>
        <Routes>
          <Route element={<PrivateRoutes />}>
            <Route path="/" element={<Home />} />
            <Route path="/Home" element={<Home />} />
            <Route path="/About" element={<About />} />
            <Route path="/Contact" element={<Contact />} />
          </Route>
          <Route element={<AnonymousRoutes />}>
            <Route path="/login" element={<Login />} />
          </Route>
        </Routes>
        <Outlet />
      </BrowserRouter>

  );
}

So now with this code I want to implement database login also. Please suggest the possible way.


问:
How to change Author name list in typo3
Screenshot

Hello,

I have taken over the website from my colleague, I do not have much programming experience. I am used to wix or wordpress, but not with programming in typo3. I cannot find the option to change the names in the Author name list. I like to add some of my colleagues, so when I post something from them their name is displayed. How do I change or add names to this Author Name list?

thanks

Searching in google I find programme languages I do not understand. Is there a way to just change settings? Is see no option in typo3.

Title: How to change Author name list in typo3


问:
org.springframework.security.core.userdetails.User cannot be cast
```<code>@RestController
public class ChangePasswordController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/change-password")
    public Response processChangePassword(@RequestParam String newPassword, @RequestParam String oldPass,
            @RequestParam long tenantId) throws ServletException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        CustomUserDetails details = (CustomUserDetails) authentication
                .getPrincipal();
        User user = details.getUser();

        if (oldPass.equals(newPassword)) {
            return new Response("Your new password must be different than the old one.", null, new Date(),
                    HttpStatus.BAD_REQUEST.value());
        }
        if (!passwordEncoder.matches(oldPass, user.getPassword())) {
            return new Response("Your old password is incorrect.", null, new Date(), HttpStatus.BAD_REQUEST.value());

        } else {
            userService.changePassword(user, newPassword, tenantId);
            return new Response("password change sucessfully !", null, new Date(), HttpStatus.OK.value());
        }

    }
}
</code>```

Above is my code and when I Call the API /change password. It give me an  error java.lang.ClassCastException:

the error details is bellow

ERROR

```<code>2023-01-09 16:43:13 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/api/tenant-service] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: class org.springframework.security.core.userdetails.User cannot be cast to class com.shopwaala.tenant.master.service.CustomUserDetails (org.springframework.security.core.userdetails.User and com.shopwaala.tenant.master.service.CustomUserDetails are in unnamed module of loader 'app')] with root cause
java.lang.ClassCastException: class org.springframework.security.core.userdetails.User cannot be cast to class com.ABC.tenant.master.service.CustomUserDetails (org.springframework.security.core.userdetails.User and com.shopwaala.tenant.master.service.CustomUserDetails are in unnamed module of loader 'app')
    at com.shopwaala.auth.controller.ChangePasswordController.processChangePassword(ChangePasswordController.java:32)
</code>```

Body:
@RestController
public class ChangePasswordController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/change-password")
    public Response processChangePassword(@RequestParam String newPassword, @RequestParam String oldPass,
            @RequestParam long tenantId) throws ServletException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        CustomUserDetails details = (CustomUserDetails) authentication
                .getPrincipal();
        User user = details.getUser();

        if (oldPass.equals(newPassword)) {
            return new Response("Your new password must be different than the old one.", null, new Date(),
                    HttpStatus.BAD_REQUEST.value());
        }
        if (!passwordEncoder.matches(oldPass, user.getPassword())) {
            return new Response("Your old password is incorrect.", null, new Date(), HttpStatus.BAD_REQUEST.value());

        } else {
            userService.changePassword(user, newPassword, tenantId);
            return new Response("password change sucessfully !", null, new Date(), HttpStatus.OK.value());
        }

    }
}

Above is my code and when I Call the API /change password. It give me an  error java.lang.ClassCastException:

the error details is bellow

ERROR

2023-01-09 16:43:13 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/api/tenant-service] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: class org.springframework.security.core.userdetails.User cannot be cast to class com.shopwaala.tenant.master.service.CustomUserDetails (org.springframework.security.core.userdetails.User and com.shopwaala.tenant.master.service.CustomUserDetails are in unnamed module of loader 'app')] with root cause
java.lang.ClassCastException: class org.springframework.security.core.userdetails.User cannot be cast to class com.ABC.tenant.master.service.CustomUserDetails (org.springframework.security.core.userdetails.User and com.shopwaala.tenant.master.service.CustomUserDetails are in unnamed module of loader 'app')
    at com.shopwaala.auth.controller.ChangePasswordController.processChangePassword(ChangePasswordController.java:32)


问:
Flutter - tightly coupling of Widget lifecycle and Stream Subscription
I'm using BLoC architecture and my app structure is as following

Route A with List of Users and appropriate BLoC

Route B (User Details)

When someone taps on User item, there is a redirection to Route B.

I want to fetch new list of User every 5 seconds therefore I made StreamSubscribtions in BLoC

```<code>  final Stream<int> refreshStream = Stream.periodic((const Duration(seconds: 5)), (val) {
    return val;
  });
</code>```

and I've made Stream subscription in the same Bloc

```<code> refreshStream.take(50).listen((event) {

      add(const FetchUsersList());

    });
</code>```

And this works brilliant, but stream is still running even if widget is not visible because I am on User Details screen. It's making a lot of unnecessary API calls.

My next step was to tightly couple Stream mechanism to any Stateful widget and setup stream subscription in onInit and close/pause stream in deactivate or dispose lifecycle method. However it never stops when Route B is pushed.

My goal is: Do not trigger FetchUser when Route A is not a current route or when app is paused or in the background. I don't want to use any 3rd party libraries.

Body:
I'm using BLoC architecture and my app structure is as following

Route A with List of Users and appropriate BLoC

Route B (User Details)

When someone taps on User item, there is a redirection to Route B.

I want to fetch new list of User every 5 seconds therefore I made StreamSubscribtions in BLoC

  final Stream<int> refreshStream = Stream.periodic((const Duration(seconds: 5)), (val) {
    return val;
  });

and I've made Stream subscription in the same Bloc

 refreshStream.take(50).listen((event) {

      add(const FetchUsersList());

    });

And this works brilliant, but stream is still running even if widget is not visible because I am on User Details screen. It's making a lot of unnecessary API calls.

My next step was to tightly couple Stream mechanism to any Stateful widget and setup stream subscription in onInit and close/pause stream in deactivate or dispose lifecycle method. However it never stops when Route B is pushed.

My goal is: Do not trigger FetchUser when Route A is not a current route or when app is paused or in the background. I don't want to use any 3rd party libraries.


问:
Run-time error "1004": Macro "getUnits" can not be run. macro must not be accessible in this worksheet or all the macros are forbidden
i have created a macro via recording that works perfectely on my comp, but when i send it to other colleagues, they can not run it for the issue described in the title (I have translated the issue from Slovak to English). Below is the VBN code (there will be some text in Slovak):

```<code>Sub Makro1()
'
' Makro1 Makro
' Výpočet doby návratnosti
'
' Klávesová skratka: Ctrl+r
'
ActiveWindow.ScrollWorkbookTabs Sheets:=1
ActiveWindow.ScrollWorkbookTabs Sheets:=1
ActiveWindow.ScrollWorkbookTabs Sheets:=1
ActiveWindow.ScrollWorkbookTabs Sheets:=1
Sheets("Doba návratnosti").Select
Application.Run "getUnits"
Range("G24").Select
Application.CutCopyMode = False
Application.CutCopyMode = False
Application.CutCopyMode = False
Range("G24").GoalSeek Goal:=0, ChangingCell:=Range("D24")
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
Sheets("Výsledky").Select
Application.Run "getUnits"
End Sub
</code>```

I have already tried the Open and Repair option, there is not a GWXL97.XLA file, "Trust access to the VBA project object model" is marked and my sheet is anprotected, Stellar Repair shut after scanning my document, openAI couldnt help. i am not advanced in macros, but  dont get it why (while creating a macro via recording) the automatically generated name of the macro is getUnits while in the Name Field it is Makro1.

I am looking forward to your solutions.

Body:
i have created a macro via recording that works perfectely on my comp, but when i send it to other colleagues, they can not run it for the issue described in the title (I have translated the issue from Slovak to English). Below is the VBN code (there will be some text in Slovak):

Sub Makro1()
'
' Makro1 Makro
' Výpočet doby návratnosti
'
' Klávesová skratka: Ctrl+r
'
ActiveWindow.ScrollWorkbookTabs Sheets:=1
ActiveWindow.ScrollWorkbookTabs Sheets:=1
ActiveWindow.ScrollWorkbookTabs Sheets:=1
ActiveWindow.ScrollWorkbookTabs Sheets:=1
Sheets("Doba návratnosti").Select
Application.Run "getUnits"
Range("G24").Select
Application.CutCopyMode = False
Application.CutCopyMode = False
Application.CutCopyMode = False
Range("G24").GoalSeek Goal:=0, ChangingCell:=Range("D24")
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
Sheets("Výsledky").Select
Application.Run "getUnits"
End Sub

I have already tried the Open and Repair option, there is not a GWXL97.XLA file, "Trust access to the VBA project object model" is marked and my sheet is anprotected, Stellar Repair shut after scanning my document, openAI couldnt help. i am not advanced in macros, but  dont get it why (while creating a macro via recording) the automatically generated name of the macro is getUnits while in the Name Field it is Makro1.

I am looking forward to your solutions.


问:
Java - CMIS query - WHERE IN
I have my connection to SP through open CMIS.

I am trying to get cmis:contentStreamLength based on many cmis:objectId.

This select, for all documents works fine.

SELECT cmis:contentStreamLength FROM cmis:document

But this query with where cond. doesn't.

SELECT cmis:contentStreamLength FROM cmis:document d WHERE ANY d.cmis:objectId IN ('id',...)

OR

SELECT * FROM cmis:document d WHERE d.cmis:objectId = '"+contentId+"'" (just one id in form "id")

Here is the code in Java (1.4).

```<code>public int getSizeInBytes(String contentIds) {
           String query = "SELECT * FROM cmis:document d WHERE ANY d.cmis:objectId IN ("+contentIds+")";
           ItemIterable results = session.query(query,false);
           int size=0;
           Iterator iterator = results.iterator();

           while (iterator.hasNext()) {
               QueryResult res = (QueryResult) iterator.next();
               size +=   Integer.parseInt(res.getPropertyById("cmis:contentStreamLength").getFirstValue().toString());
           }

           return size;
       }
</code>```

contetntIds are in the form of string like so - "'id','id',..." - id as xxxx:xxxx

It breaks on  while (iterator.hasNext())

exception :

```<code>CmisInvalidArgumentException: One or more of the input parameters to the service method is missing or invalid.
</code>```

When I did

where d.cmis:createdBy = "nonsens/non existent"

It just worked, like it didn't show a thing, so empty result is ok.

What seems to be the problem ?

Everything I tried is in details of my problem.
I expect to get size of all documents with inputed ids.

Title: Java - CMIS query - WHERE IN

Body:
I have my connection to SP through open CMIS.

I am trying to get cmis:contentStreamLength based on many cmis:objectId.

This select, for all documents works fine.

SELECT cmis:contentStreamLength FROM cmis:document

But this query with where cond. doesn't.

SELECT cmis:contentStreamLength FROM cmis:document d WHERE ANY d.cmis:objectId IN ('id',...)

OR

SELECT * FROM cmis:document d WHERE d.cmis:objectId = '"+contentId+"'" (just one id in form "id")

Here is the code in Java (1.4).

public int getSizeInBytes(String contentIds) {
           String query = "SELECT * FROM cmis:document d WHERE ANY d.cmis:objectId IN ("+contentIds+")";
           ItemIterable results = session.query(query,false);
           int size=0;
           Iterator iterator = results.iterator();

           while (iterator.hasNext()) {
               QueryResult res = (QueryResult) iterator.next();
               size +=   Integer.parseInt(res.getPropertyById("cmis:contentStreamLength").getFirstValue().toString());
           }

           return size;
       }

contetntIds are in the form of string like so - "'id','id',..." - id as xxxx:xxxx

It breaks on  while (iterator.hasNext())

exception :

CmisInvalidArgumentException: One or more of the input parameters to the service method is missing or invalid.

When I did

where d.cmis:createdBy = "nonsens/non existent"

It just worked, like it didn't show a thing, so empty result is ok.

What seems to be the problem ?

Everything I tried is in details of my problem.
I expect to get size of all documents with inputed ids.


问:
The command php artisan key:generate cause error when using in Github action CI flow (The laravel version is v9.46.0)
This is the error screenshot when I use GitHub action for CI. It seems something is wrong with the composer autoload file at step "Generate key" but I am not sure how to fix it.

This error doesn't occur in my local when I follow the same step in github action config file.

This is laravel.yml config for github action

```<code>name: Laravel

on:
  push:
    branches: [ "master" ]
  pull_request:
    branches: [ "master" ]

jobs:
  laravel-tests:

    runs-on: ubuntu-latest

    steps:
    - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e
      with:
        php-version: '8.0'
    - uses: actions/checkout@v3
    - name: Copy .env
      run: php -r "file_exists('.env') || copy('.env.example', '.env');"
    - name: Install Dependencies
      run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
    - name: Generate key
      run: php artisan key:generate
    - name: Directory Permissions
      run: chmod -R 777 storage bootstrap/cache
    - name: Create Database
      run: |
        mkdir -p database
        touch database/database.sqlite
    - name: Execute tests (Unit and Feature tests) via PHPUnit
      env:
        DB_CONNECTION: sqlite
        DB_DATABASE: database/database.sqlite
      run: vendor/bin/phpunit
</code>```

I try the same config above for another laravel project (v8) and this error doesn't occur

This is my composer.json file

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.0.2",
        "algolia/algoliasearch-client-php": "^3.3",
        "fico7489/laravel-pivot": "^3.0",
        "guzzlehttp/guzzle": "^7.2",
        "laravel/framework": "^9.19",
        "laravel/sanctum": "^3.0",
        "laravel/scout": "^9.4",
        "laravel/tinker": "^2.7",
        "livewire/livewire": "^2.10",
        "predis/predis": "^2.0",
        "stevebauman/purify": "^5.0"
    },
    "require-dev": {
        "barryvdh/laravel-debugbar": "^3.7",
        "fakerphp/faker": "^1.9.1",
        "laravel/breeze": "^1.14",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^6.1",
        "pestphp/pest": "^1.22",
        "pestphp/pest-plugin-laravel": "^1.3",
        "phpunit/phpunit": "^9.5.10",
        "spatie/laravel-ignition": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        },
        "files": [
            "Tests\\Utility\\function.php"
        ]
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}
</code>```

Thanks in advance!

Body:
This is the error screenshot when I use GitHub action for CI. It seems something is wrong with the composer autoload file at step "Generate key" but I am not sure how to fix it.

This error doesn't occur in my local when I follow the same step in github action config file.

This is laravel.yml config for github action

name: Laravel

on:
  push:
    branches: [ "master" ]
  pull_request:
    branches: [ "master" ]

jobs:
  laravel-tests:

    runs-on: ubuntu-latest

    steps:
    - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e
      with:
        php-version: '8.0'
    - uses: actions/checkout@v3
    - name: Copy .env
      run: php -r "file_exists('.env') || copy('.env.example', '.env');"
    - name: Install Dependencies
      run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
    - name: Generate key
      run: php artisan key:generate
    - name: Directory Permissions
      run: chmod -R 777 storage bootstrap/cache
    - name: Create Database
      run: |
        mkdir -p database
        touch database/database.sqlite
    - name: Execute tests (Unit and Feature tests) via PHPUnit
      env:
        DB_CONNECTION: sqlite
        DB_DATABASE: database/database.sqlite
      run: vendor/bin/phpunit

I try the same config above for another laravel project (v8) and this error doesn't occur

This is my composer.json file

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.0.2",
        "algolia/algoliasearch-client-php": "^3.3",
        "fico7489/laravel-pivot": "^3.0",
        "guzzlehttp/guzzle": "^7.2",
        "laravel/framework": "^9.19",
        "laravel/sanctum": "^3.0",
        "laravel/scout": "^9.4",
        "laravel/tinker": "^2.7",
        "livewire/livewire": "^2.10",
        "predis/predis": "^2.0",
        "stevebauman/purify": "^5.0"
    },
    "require-dev": {
        "barryvdh/laravel-debugbar": "^3.7",
        "fakerphp/faker": "^1.9.1",
        "laravel/breeze": "^1.14",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^6.1",
        "pestphp/pest": "^1.22",
        "pestphp/pest-plugin-laravel": "^1.3",
        "phpunit/phpunit": "^9.5.10",
        "spatie/laravel-ignition": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        },
        "files": [
            "Tests\\Utility\\function.php"
        ]
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

Thanks in advance!


问:
Group values in one column and list in row the values of other column
I apologize in advance if my entry will lack in any way and/or if my question has already been answered previously.

I am using Excel and I need to remove the duplicates of column A without losing the values of column B.
This is what i have:

```<code>A    B
------
a    x
a    y
a    z
b    y
b    z
c    x
c    z
</code>```

What I need is something like this:

```<code>A    B
------
a    x,y,z
b    y,z
c    x,z
</code>```

By using the remove duplicate function I and up with the following:

```<code>A    B
------
a    x
b    y
c    x
</code>```

Excel keeps only the value in the first row and deletes the values of all other duplicates of column A.

Body:
I apologize in advance if my entry will lack in any way and/or if my question has already been answered previously.

I am using Excel and I need to remove the duplicates of column A without losing the values of column B.
This is what i have:

A    B
------
a    x
a    y
a    z
b    y
b    z
c    x
c    z

What I need is something like this:

A    B
------
a    x,y,z
b    y,z
c    x,z

By using the remove duplicate function I and up with the following:

A    B
------
a    x
b    y
c    x

Excel keeps only the value in the first row and deletes the values of all other duplicates of column A.


问:
Create map of functions in another file with Go
How can I create a map from all of the functions found in another file in Go? It's pretty easy to get the names of them using the following code, but I haven't found a way to get the actual functions, or for the desired code to work.

```<code>fileSet := token.NewFileSet()
ast, err := parser.ParseFile(fileSet, "funcFile.go", nil, 0)
if err != nil {
    panic(err)
}
for key := range ast.Scope.Objects {
    fmt.Println(key) //
}
</code>```

Desired result:

funcFile.go

```<code>imports ...

func returnTrue () bool {return true}
</code>```

mapFile.go

```<code>func CreateFuncMap () {

    fns := make(map[string]func(bars []Types.MarketData) bool)
    otherFuncs := getFuncsFromFile("funcFile.go")
    for _, fn := range otherFuncs {
        fns[fn.Name] = fn
    }
}
</code>```

Body:
How can I create a map from all of the functions found in another file in Go? It's pretty easy to get the names of them using the following code, but I haven't found a way to get the actual functions, or for the desired code to work.

fileSet := token.NewFileSet()
ast, err := parser.ParseFile(fileSet, "funcFile.go", nil, 0)
if err != nil {
    panic(err)
}
for key := range ast.Scope.Objects {
    fmt.Println(key) //
}

Desired result:

funcFile.go

imports ...

func returnTrue () bool {return true}

mapFile.go

func CreateFuncMap () {

    fns := make(map[string]func(bars []Types.MarketData) bool)
    otherFuncs := getFuncsFromFile("funcFile.go")
    for _, fn := range otherFuncs {
        fns[fn.Name] = fn
    }
}


问:
How do I scale text according to screen size in android studio?
I am trying to create a calculator app on android studio but I can't figure out how to adjust the numbers which users types into the calculator and which are shown on their screen according to their screen size. I want the numbers to have enough space for longer equations and also for everything to look proportional. I have tried adding textview autosize to my code:

```<code>app:autoSizeTextType="uniform"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeMaxTextSize="55sp"
        android:autoSizeStepGranularity="2sp"
</code>```

but this does not adjust the text size according to the screen size.

What is the most appropriate code to add to my app to solve this problem?

Here is the code for my output section.

```<code><TextView
        android:id="@+id/tvmain"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#000"
        android:text=""
        android:textColor="#fff"
        app:autoSizeTextType="uniform"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeMaxTextSize="55sp"
        android:autoSizeStepGranularity="2sp"
        android:textAlignment="viewEnd"
        android:padding="10dp"
        android:gravity="bottom"
        android:maxLines="1"
        android:layout_weight="2">

    </TextView>
</code>```

If anymore information is needed to help me in solving this problem then please let me know.

Body:
I am trying to create a calculator app on android studio but I can't figure out how to adjust the numbers which users types into the calculator and which are shown on their screen according to their screen size. I want the numbers to have enough space for longer equations and also for everything to look proportional. I have tried adding textview autosize to my code:

app:autoSizeTextType="uniform"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeMaxTextSize="55sp"
        android:autoSizeStepGranularity="2sp"

but this does not adjust the text size according to the screen size.

What is the most appropriate code to add to my app to solve this problem?

Here is the code for my output section.

<TextView
        android:id="@+id/tvmain"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#000"
        android:text=""
        android:textColor="#fff"
        app:autoSizeTextType="uniform"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeMaxTextSize="55sp"
        android:autoSizeStepGranularity="2sp"
        android:textAlignment="viewEnd"
        android:padding="10dp"
        android:gravity="bottom"
        android:maxLines="1"
        android:layout_weight="2">

    </TextView>

If anymore information is needed to help me in solving this problem then please let me know.


问:
hibernate criteria query for one to many relationship with error when selecting children values
I have an error when selecting the children values of the installer entity which name it infoRges

installer entity:

```<code>    @Entity
    @Table(name = "installer")
    public class Installer implements Serializable {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<InfoRge> infoRges;

    @Column(name = "enterprise_name", length = 50)
    private String name;
    //with getter and setter

    }
</code>```

InstallerListDto class :

```<code>private Set<InfoRge> infoRges;
private string name;
constructor(Long id, Set<InfoRge> infoRges, String name);
//setters and getters
</code>```

criteria query for selecting list of infoRge :

```<code>    // Creating the criteria builder
    CriteriaBuilder cb = em.getCriteriaBuilder();

    // Creating the query from Installer Class
    CriteriaQuery<InstallerListDto> criteriaQuery = cb.createQuery(InstallerListDto.class);

    Root<Installer> from = criteriaQuery.from(Installer.class);
    criteriaQuery.select(cb.construct(InstallerListDto.class, from.get("id"),
                                          from.get("infoRges"),
                                          from.get("name")));
</code>```

error messages :

```<code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '. as col_5_0_, installer0_.enterprise_name as col_6_0_ from installer installer0' at line 1
</code>```

Body:
I have an error when selecting the children values of the installer entity which name it infoRges

installer entity:

    @Entity
    @Table(name = "installer")
    public class Installer implements Serializable {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<InfoRge> infoRges;

    @Column(name = "enterprise_name", length = 50)
    private String name;
    //with getter and setter

    }

InstallerListDto class :

private Set<InfoRge> infoRges;
private string name;
constructor(Long id, Set<InfoRge> infoRges, String name);
//setters and getters

criteria query for selecting list of infoRge :

    // Creating the criteria builder
    CriteriaBuilder cb = em.getCriteriaBuilder();

    // Creating the query from Installer Class
    CriteriaQuery<InstallerListDto> criteriaQuery = cb.createQuery(InstallerListDto.class);

    Root<Installer> from = criteriaQuery.from(Installer.class);
    criteriaQuery.select(cb.construct(InstallerListDto.class, from.get("id"),
                                          from.get("infoRges"),
                                          from.get("name")));

error messages :

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '. as col_5_0_, installer0_.enterprise_name as col_6_0_ from installer installer0' at line 1


问:
Find pages that are written in a process after a fork()
I have a fork-based server. After the fork, the server basically just moves data from one socket to another: I expect it to write only to one memory buffer. With Linux' copy-on-write system, I therefore expect each new forked process to only use up a small amount of RAM.
Yet, that's not what happens and I observe a very large amount of RAM used by the sum of the processes (the issue is described here)

I would want to investigate where a process writes after the fork, as I assume the process is writing to unexpected parts of memory. Ideally I'd request a memory status on a PID, and it would tell me which pages are shared between processes, which pages are specific to that one process, and which symbols are contained in the pages. Valgrind's Massif, nor Memcheck, seem to help. I am not completely sure how to interpret pmap's output, but I don't think it does what I need either.

Is there a method or a tool to help with this?


问:
Web Scraping in an AJAX page with "Load more" button without Selenium
I'm trying to scrape some data of this website: https://fminside.net/players As you can see, at the bottom of the web there is a button "Load more players.." that if you click it automatically shows 50 more players in the table. I've managed to automate the process of opening the web, navigate by clicking the button and the players are displayed with Selenium, but I would like to know if it is possible to find an alternative to extract the data without automating a browser and go by clicking on the button, as the process is very slow.

As far as I know, this is an AJAX page and maybe there would be some way to access the information that loads when the button is clicked in some other way. any suggestions? Thank you very much.


问:
FacesContext.getCurrentInstance() returns null in Quartz scheduler
I´m trying to get an application attribute inside the Quartz Job, but I´m getting always a NPE:

```<code>import java.util.List;

import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.SubjectThreadState;
import org.apache.shiro.util.ThreadState;
import org.omnifaces.util.Faces;
import org.omnifaces.util.FacesLocal;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ApplicationScoped
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class DisallowConcurrentQuartzJob implements Job {

@Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        FacesContext facesContext = FacesContext.getCurrentInstance();
        // -> IS NULL

             List<Object> customActionTypeClasses = Faces.getApplicationAttribute("TEST");
// -> IS NULL

    }
</code>```

Any ideas why this is not working?
I´ve created also a CDI Factory:

```<code>   @ApplicationScoped
    public class SchedulerQuartzServiceBean {

    @Inject
    private CdiSchedulerJobFactory cdiSchedulerJobFactory;

          // Start
         public void startSchedule() {
            Scheduler scheduler = schedulerFactory.getScheduler(defaultSchedulerName);
           scheduler.setJobFactory(cdiSchedulerJobFactory);
          }
     }

@ApplicationScoped
public class CdiSchedulerJobFactory implements JobFactory {

    @Inject
    private BeanManager beanManager;

    @Override
    public Job newJob(final TriggerFiredBundle bundle, final Scheduler scheduler) throws SchedulerException {

        Class<? extends Job> jobClass = bundle.getJobDetail().getJobClass();
        Set<Bean<?>> beans = beanManager.getBeans(jobClass);

        if (beans.isEmpty()) {
            throw new SchedulerException("No job instance found for job class: " + jobClass.getName());
        }

        Bean<?> bean = beanManager.getBeans(jobClass).iterator().next();
        CreationalContext<?> ctx = beanManager.createCreationalContext(bean);

        return (Job) beanManager.getReference(bean, jobClass, ctx);
    }
}
</code>```

Does anybody have an idea what´s wrong here?
The Faces.getApplicationAttribute will throw a NPE because FacesContext is null.

Body:
I´m trying to get an application attribute inside the Quartz Job, but I´m getting always a NPE:

import java.util.List;

import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.SubjectThreadState;
import org.apache.shiro.util.ThreadState;
import org.omnifaces.util.Faces;
import org.omnifaces.util.FacesLocal;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ApplicationScoped
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class DisallowConcurrentQuartzJob implements Job {

@Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        FacesContext facesContext = FacesContext.getCurrentInstance();
        // -> IS NULL

             List<Object> customActionTypeClasses = Faces.getApplicationAttribute("TEST");
// -> IS NULL

    }

Any ideas why this is not working?
I´ve created also a CDI Factory:

   @ApplicationScoped
    public class SchedulerQuartzServiceBean {

    @Inject
    private CdiSchedulerJobFactory cdiSchedulerJobFactory;

          // Start
         public void startSchedule() {
            Scheduler scheduler = schedulerFactory.getScheduler(defaultSchedulerName);
           scheduler.setJobFactory(cdiSchedulerJobFactory);
          }
     }

@ApplicationScoped
public class CdiSchedulerJobFactory implements JobFactory {

    @Inject
    private BeanManager beanManager;

    @Override
    public Job newJob(final TriggerFiredBundle bundle, final Scheduler scheduler) throws SchedulerException {

        Class<? extends Job> jobClass = bundle.getJobDetail().getJobClass();
        Set<Bean<?>> beans = beanManager.getBeans(jobClass);

        if (beans.isEmpty()) {
            throw new SchedulerException("No job instance found for job class: " + jobClass.getName());
        }

        Bean<?> bean = beanManager.getBeans(jobClass).iterator().next();
        CreationalContext<?> ctx = beanManager.createCreationalContext(bean);

        return (Job) beanManager.getReference(bean, jobClass, ctx);
    }
}

Does anybody have an idea what´s wrong here?
The Faces.getApplicationAttribute will throw a NPE because FacesContext is null.


问:
Django smart fiter transfers
I have a model Book and there are duplicated rows in that table.
One of the duplicates was changed during duplicate operation.

The differences between that rows are in two fields (special_id and state). E.g.:

Name
special_id
state

Idiot
"0107"
1

Idiot
"0106"
2

During filtering by state if i write Book.objects.filter(state=2), i'll get the books with value of state 2, So i want to exclude this book if there is the book with the same name and with the state 1

Is there any way to do this without for loop and looking by the name of every book in QuerySet?

Now when quantity of books is not big the delay of for loop is not noticeable. But when they'll be enormous i think it's going to be really long delay.

Title: Django smart fiter transfers


问:
terminal showing "zsh: killed ls"
While installing mongodb-community on my m1 mac, I could not start the service as it showed the error
"Error: Failure while executing; /usr/local/bin/launchctl enable gui/501/homebrew.mxcl.mongodb-community was terminated by uncaught signal KILL."

Searching for the solution to this problem, I realized it might be homebrew causing the problem.

When i tried to uninstall homebrew(using homebrew official uninstalling script), it showed the error
"/bin/bash: line 49: 15817 Killed: 9               mkdir -p "${tmpdir}"
Unable to create temp dir '/tmp/uninstall.15816'"

Soon after this I realised that even the "ls" command is not working on the terminal.

p.s - I am new to development so not sure what actually went wrong.

I tried to uninstall homebrew as someone suggested that homebrew may be responsible for the error. It again did not work and the error popped.
Also tried to update homebrew, reinstall mongodb-community using homebrew but nothing worked.

Title: terminal showing "zsh: killed ls"


问:
How to disable right click in windows desktop using c#
I'm using c# form, I have two button just like on, off. When I click on/off button I need to enable/disable mouse right button on windows desktop. How can I do that?

I try the registry, but not work well as I expect.


问:
500 error on running commands on kibana console
Version
OpenSearch 1.3

Service software version
R20221114 (latest)

on Kibana after running

```<code>GET _snapshot/my-snapshot-repo/_all?pretty
</code>```

its gives 500 error

```<code>{
"error" : {
"root_cause" : [
{
"type" : "repository_exception",
"reason" : "[my-snapshot-repo] Unexpected exception when loading repository data"
}
],
"type" : "repository_exception",
"reason" : "[my-snapshot-repo] Unexpected exception when loading repository data",
"caused_by" : {
"type" : "amazon_s3_exception",
"reason" : "The ciphertext refers to a customer master key that does not exist, does not exist in this region, or you are not allowed to access. (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: EMYFDJVYSXYJP0MS; S3 Extended Request ID: Sr5RAl41ANCJbOQOD3xAXgec6YMO+8Hr8lOq/oHUP4gKphd0olF4aMk6TQKsFhHcKAAKBSf4p1j+p/AUb8Pf1A==)"
}
},
"status" : 500
}
</code>```

followed https://www.youtube.com/watch?v=A_eFCpyl_Fg

Body:
Version
OpenSearch 1.3

Service software version
R20221114 (latest)

on Kibana after running

GET _snapshot/my-snapshot-repo/_all?pretty

its gives 500 error

{
"error" : {
"root_cause" : [
{
"type" : "repository_exception",
"reason" : "[my-snapshot-repo] Unexpected exception when loading repository data"
}
],
"type" : "repository_exception",
"reason" : "[my-snapshot-repo] Unexpected exception when loading repository data",
"caused_by" : {
"type" : "amazon_s3_exception",
"reason" : "The ciphertext refers to a customer master key that does not exist, does not exist in this region, or you are not allowed to access. (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: EMYFDJVYSXYJP0MS; S3 Extended Request ID: Sr5RAl41ANCJbOQOD3xAXgec6YMO+8Hr8lOq/oHUP4gKphd0olF4aMk6TQKsFhHcKAAKBSf4p1j+p/AUb8Pf1A==)"
}
},
"status" : 500
}

followed https://www.youtube.com/watch?v=A_eFCpyl_Fg


问:
Fetching credentials from AWS EC2 Parameter store and Set the Value in Configuration file
I am fetching the value from aws parameter store and try to set the value in root env and Using the env file try to set it to config file.

** retrieveCredentials.js
**

```<code>const fetchCredentialsFromAWS = () => {
    return new Promise(async (resolve, reject) => {
        try {
            logger.info("AWS KMS Credentials")
            const ssmClient = new aws.SSM({
                region: 'region name'
            });
            const environment = 'stage'
            ssmClient.getParametersByPath({
                Path: `name/${stage}`,
                Recursive: true,
                WithDecryption: true,
            }, (err, data) => {
                if (data) {
        data.data.Parameters.forEach(item => {
        if (item.Name == 'username') {
         process.env.username = item.Valu
        }
           if (item.Name == 'password') {
         process.env.password=item.Value
           }
        if (item.Name == 'database') {
           process.env.database=item.Value
        }
    })
                    resolve({ status: "Success", code: 200, message: "Sucess" })
                } else {
                    resolve({ status: "NOT Valid", code: 202, message: "Validation Failed", data: err })
                }
            });
        } catch (error) {
            resolve({ status: "NOT Valid", code: 202, message: "Validation Failed", data: null })
        }

    })
</code>```

//config.js

```<code>
        username: process.env.username,
        password: process.env.password,
        database: process.env.database,
        host: "localhost",
</code>```

**Issues -
**Values are set in env and it is also set to the config file but it will set after the config file is read from the server and therefore it was read undefined before the value is set.

So, how to set the value so that config gets the details?

I try to set the value in the environment file and update the config file credentials using process.env.

Body:
I am fetching the value from aws parameter store and try to set the value in root env and Using the env file try to set it to config file.

** retrieveCredentials.js
**

const fetchCredentialsFromAWS = () => {
    return new Promise(async (resolve, reject) => {
        try {
            logger.info("AWS KMS Credentials")
            const ssmClient = new aws.SSM({
                region: 'region name'
            });
            const environment = 'stage'
            ssmClient.getParametersByPath({
                Path: `name/${stage}`,
                Recursive: true,
                WithDecryption: true,
            }, (err, data) => {
                if (data) {
        data.data.Parameters.forEach(item => {
        if (item.Name == 'username') {
         process.env.username = item.Valu
        }
           if (item.Name == 'password') {
         process.env.password=item.Value
           }
        if (item.Name == 'database') {
           process.env.database=item.Value
        }
    })
                    resolve({ status: "Success", code: 200, message: "Sucess" })
                } else {
                    resolve({ status: "NOT Valid", code: 202, message: "Validation Failed", data: err })
                }
            });
        } catch (error) {
            resolve({ status: "NOT Valid", code: 202, message: "Validation Failed", data: null })
        }

    })

//config.js

        username: process.env.username,
        password: process.env.password,
        database: process.env.database,
        host: "localhost",

**Issues -
**Values are set in env and it is also set to the config file but it will set after the config file is read from the server and therefore it was read undefined before the value is set.

So, how to set the value so that config gets the details?

I try to set the value in the environment file and update the config file credentials using process.env.


问:
Generic class that can inherti from more than one base abstract class
so I am trying to build a flexible system for ScriptableVariables and ScriptableEvents (inspired by Ryan Hipple's Unite talk from 2017) in Unity and am running into some issues.

What I want to do is make class that takes in a generic which can inherit from 2 different abstract classes which both have the same base abstract class, but I am not sure if it is possible.

Example:

```<code>public abstract class BaseClass : ScriptableObject {}

public class ClassA : BaseClass {}
public class ClassB<T> : BaseClass {}
</code>```

Then I want to have a separate class which takes in a Generic that can be either ClassA OR ClassB.

```<code>public class NewClass<T1> where T1 : ClassA **OR** ClassB {}
</code>```

Is this possible? If so - what is the syntax for it? If not - what alternatives would be there to achieve something of this nature?

JetBrains Rider does not allow this stating that there's inherit conflicting constraints (which makes sense since both ClassA & ClassB would have the methods derived from BaseClass, however this suggests that T1 would inherit from both ClassA AND ClassB, whereas I want it to be one or the other.

It seems something of this nature is possible with interfaces, however when going about it this way - I am running into issues down the chain which seem to break my entire system, so I wanted to know if it is solvable like this before resorting to rehauling the lower systems.

Body:
so I am trying to build a flexible system for ScriptableVariables and ScriptableEvents (inspired by Ryan Hipple's Unite talk from 2017) in Unity and am running into some issues.

What I want to do is make class that takes in a generic which can inherit from 2 different abstract classes which both have the same base abstract class, but I am not sure if it is possible.

Example:

public abstract class BaseClass : ScriptableObject {}

public class ClassA : BaseClass {}
public class ClassB<T> : BaseClass {}

Then I want to have a separate class which takes in a Generic that can be either ClassA OR ClassB.

public class NewClass<T1> where T1 : ClassA **OR** ClassB {}

Is this possible? If so - what is the syntax for it? If not - what alternatives would be there to achieve something of this nature?

JetBrains Rider does not allow this stating that there's inherit conflicting constraints (which makes sense since both ClassA & ClassB would have the methods derived from BaseClass, however this suggests that T1 would inherit from both ClassA AND ClassB, whereas I want it to be one or the other.

It seems something of this nature is possible with interfaces, however when going about it this way - I am running into issues down the chain which seem to break my entire system, so I wanted to know if it is solvable like this before resorting to rehauling the lower systems.


问:
Modifying API Endpoint to Support Chunking
I am trying to add chunking support to an existing API that is published to power automate connector.

I have an API that accepts files from Power Automate flows, modifies and returns them (an example would be to combine multiple files into a single one).

I have modified the json for the published api to include

"x-ms-capabilities": { "chunkTransfer": true }
-- as suggested by https://learn.microsoft.com/en-gb/connectors/custom-connectors/openapi-extensions#x-ms-capabilities

I am using PowerAutomate to send and receive files. The exposed Apis in my connector then have Content Transfer->Allow chunking set to On.

When I send large files to the api with chunking thus enabled, it fails. The same is true for the endpoint which is called to return a file after processing.

There seems little documentation on what else (if anything) I need to change on the Api side.

Has anyone tried to add chunking support to an existing API?


问:
Number of actual printed lines in code blocks output console (fortran compiler)
Why the output console of code blocks displays only the last 25 printed lines, although my code is written to print "hello world" for 60 times for example? This is my code:</p>
```<code>program hello

implicit none
integer i

do i=1,60
print *, i, "hello world"
end do

end program
</code>```

Body:
Why the output console of code blocks displays only the last 25 printed lines, although my code is written to print "hello world" for 60 times for example? This is my code:

program hello

implicit none
integer i

do i=1,60
print *, i, "hello world"
end do

end program


问:
Could not resolve project :react-native-custom-keyboard-kit
I'm having a problem generating a release APK but the debug version is working fine. I keep getting the error below with different packages such as react-native-vectors-icons and others

Could not determine the dependencies of task ':app:mergeLintOptionsNativeLibs'.

Could not resolve all task dependencies for configuration ':app:lintOptionsRuntimeClasspath'.
Could not resolve project :react-native-custom-keyboard-kit.
Required by:
project :app
> No matching variant of project :react-native-custom-keyboard-kit was found. The consumer was configured to find a runtime of a component, as well as attribute 'com.android.build.api.attributes.BuildTypeAttr' with value 'lintOptions' but:


问:
SELECT from One-to-many relationship
I'm trying to get a user's first name and last name, as well as all bank accounts associated with that user. This is what I'm getting:

[
    {
        "FirstName": "X",
        "LastName": "Y",
        "RIB": "ABC123456789"
    },
    {
        "FirstName": "X",
        "LastName": "Y",
        "RIB": "BZE123456789"
    },
    {
        "FirstName": "X",
        "LastName": "Y",
        "RIB": "DFG123456789"
    }
]
```
<p>Where RIB is the user's bank account. While I was expecting it to return the first and last names once, then a list of all users' bank accounts instead of repeating the user full names...</p>
<pre class="lang-py prettyprint-override"><code>db.query(
    Users.FirstName,
    Users.LastName,
    models.UserLocalBankAccounts.RIB,
).join(models.UserLocalBankAccounts).filter(Users.UserId == 1).all()
</code>```

Title: SELECT from One-to-many relationship

Body:
I'm trying to get a user's first name and last name, as well as all bank accounts associated with that user. This is what I'm getting:

[
    {
        "FirstName": "X",
        "LastName": "Y",
        "RIB": "ABC123456789"
    },
    {
        "FirstName": "X",
        "LastName": "Y",
        "RIB": "BZE123456789"
    },
    {
        "FirstName": "X",
        "LastName": "Y",
        "RIB": "DFG123456789"
    }
]

Where RIB is the user's bank account. While I was expecting it to return the first and last names once, then a list of all users' bank accounts instead of repeating the user full names...

db.query(
    Users.FirstName,
    Users.LastName,
    models.UserLocalBankAccounts.RIB,
).join(models.UserLocalBankAccounts).filter(Users.UserId == 1).all()


问:
how to remove search bar from WordPress theme
I want to remove the search bar next to the menu. I tried the Disable Search Bar utility, but to no avail. I also went through the theme's code in the style.css file. As it's a long code, I had to copy it in Word and search for something like form.search or search.form but I was not able to find anything relevant to it. Tried to get in touch with the company that made this theme, but they require a buy code which I don't have because the theme was offered as a freemium through the hosting company.

Went in the site’s admin Dashboard and selected Appearance → Customize → Additional CSS. In the CSS textbox I added the following code:

```<code>.site-search {
  display: none;
}
</code>```

Still, the search bar is still there. I guess the code is in the website's theme.

If you want to inspect the code, here's the website URL: https://nadeshikoyoriai.site/

Many thanks in advance for your help.

Body:
I want to remove the search bar next to the menu. I tried the Disable Search Bar utility, but to no avail. I also went through the theme's code in the style.css file. As it's a long code, I had to copy it in Word and search for something like form.search or search.form but I was not able to find anything relevant to it. Tried to get in touch with the company that made this theme, but they require a buy code which I don't have because the theme was offered as a freemium through the hosting company.

Went in the site’s admin Dashboard and selected Appearance → Customize → Additional CSS. In the CSS textbox I added the following code:

.site-search {
  display: none;
}

Still, the search bar is still there. I guess the code is in the website's theme.

If you want to inspect the code, here's the website URL: https://nadeshikoyoriai.site/

Many thanks in advance for your help.


问:
Not able to run django app with Apache server in Mac Ventura
I am new to django app development.

I am trying to use apache server for my django app in Mac OS Ventura. For this I am using mod_wsgi module to make the integration between Apache server and django app. I followed the required steps to do the setup, by making changes in httpd.conf and httpd-vhost.conf file.
After the setup, I started the apache server but in the app log I am getting below error:

```<code>[wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Failed to exec Python script file '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'.
[Mon Jan 09 16:16:41.752524 2023] [wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Exception occurred processing WSGI script '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'.
[Mon Jan 09 16:16:41.752667 2023] [wsgi:error] [pid 30317] [remote ::1:62168] Traceback (most recent call last):
[Mon Jan 09 16:16:41.752707 2023] [wsgi:error] [pid 30317] [remote ::1:62168]   File "/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py", line 12, in <module>
[Mon Jan 09 16:16:41.752719 2023] [wsgi:error] [pid 30317] [remote ::1:62168]     from django.core.wsgi import get_wsgi_application
[Mon Jan 09 16:16:41.752731 2023] [wsgi:error] [pid 30317] [remote ::1:62168]   File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/__init__.py", line 1, in <module>
[Mon Jan 09 16:16:41.752740 2023] [wsgi:error] [pid 30317] [remote ::1:62168]     from django.utils.version import get_version
[Mon Jan 09 16:16:41.752751 2023] [wsgi:error] [pid 30317] [remote ::1:62168]   File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/utils/version.py", line 1, in <module>
[Mon Jan 09 16:16:41.752761 2023] [wsgi:error] [pid 30317] [remote ::1:62168]     import datetime
[Mon Jan 09 16:16:41.752771 2023] [wsgi:error] [pid 30317] [remote ::1:62168]   File "/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/datetime.py", line 12, in <module>
[Mon Jan 09 16:16:41.752780 2023] [wsgi:error] [pid 30317] [remote ::1:62168]     import math as _math
[Mon Jan 09 16:16:41.752805 2023] [wsgi:error] [pid 30317] [remote ::1:62168] ImportError: dlopen(/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so, 0x0002): tried: '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' (code signature in <0122F4AE-8D49-3E40-832E-E54BABAE20DB> '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' not valid for use in process: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?)), '/System/Volumes/Preboot/Cryptexes/OS/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' (no such file), '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' (code signature in <0122F4AE-8D49-3E40-832E-E54BABAE20DB> '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' not valid for use in process: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?))
</code>```

what is the actual issue? I am totally new to django development.

Body:
I am new to django app development.

I am trying to use apache server for my django app in Mac OS Ventura. For this I am using mod_wsgi module to make the integration between Apache server and django app. I followed the required steps to do the setup, by making changes in httpd.conf and httpd-vhost.conf file.
After the setup, I started the apache server but in the app log I am getting below error:

[wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Failed to exec Python script file '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'.
[Mon Jan 09 16:16:41.752524 2023] [wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Exception occurred processing WSGI script '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'.
[Mon Jan 09 16:16:41.752667 2023] [wsgi:error] [pid 30317] [remote ::1:62168] Traceback (most recent call last):
[Mon Jan 09 16:16:41.752707 2023] [wsgi:error] [pid 30317] [remote ::1:62168]   File "/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py", line 12, in <module>
[Mon Jan 09 16:16:41.752719 2023] [wsgi:error] [pid 30317] [remote ::1:62168]     from django.core.wsgi import get_wsgi_application
[Mon Jan 09 16:16:41.752731 2023] [wsgi:error] [pid 30317] [remote ::1:62168]   File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/__init__.py", line 1, in <module>
[Mon Jan 09 16:16:41.752740 2023] [wsgi:error] [pid 30317] [remote ::1:62168]     from django.utils.version import get_version
[Mon Jan 09 16:16:41.752751 2023] [wsgi:error] [pid 30317] [remote ::1:62168]   File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/utils/version.py", line 1, in <module>
[Mon Jan 09 16:16:41.752761 2023] [wsgi:error] [pid 30317] [remote ::1:62168]     import datetime
[Mon Jan 09 16:16:41.752771 2023] [wsgi:error] [pid 30317] [remote ::1:62168]   File "/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/datetime.py", line 12, in <module>
[Mon Jan 09 16:16:41.752780 2023] [wsgi:error] [pid 30317] [remote ::1:62168]     import math as _math
[Mon Jan 09 16:16:41.752805 2023] [wsgi:error] [pid 30317] [remote ::1:62168] ImportError: dlopen(/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so, 0x0002): tried: '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' (code signature in <0122F4AE-8D49-3E40-832E-E54BABAE20DB> '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' not valid for use in process: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?)), '/System/Volumes/Preboot/Cryptexes/OS/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' (no such file), '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' (code signature in <0122F4AE-8D49-3E40-832E-E54BABAE20DB> '/Users/yadavv2/.pyenv/versions/3.9.5/lib/python3.9/lib-dynload/math.cpython-39-darwin.so' not valid for use in process: mapped file has no Team ID and is not a platform binary (signed with custom identity or adhoc?))

what is the actual issue? I am totally new to django development.


问:
Garbage value problem , I want to get a garbage value but I am getting zero...Why is it so
If we simply declare an integer variable in C++ , and print it why am I getting 0 instead of garbage value  every time. How to declare each element of array as 1 without using loop.</p>
```<code>#include<iostream>
using namespace std;
int main()
{
    int a;
    cout<<a;    // displays zero
}
</code>```

Body:
If we simply declare an integer variable in C++ , and print it why am I getting 0 instead of garbage value  every time. How to declare each element of array as 1 without using loop.

#include<iostream>
using namespace std;
int main()
{
    int a;
    cout<<a;    // displays zero
}


问:
Splashtop Streamer on Ubuntu Server
i am just wondering if it is possible to run Splashtop Streamer on Ubuntu Server ??

i have been able to install it, but, i get an invalid token when trying to connect, i was hoping that i could connect, and just get to a terminal.

i am pretty new to linux, but, am looking at moving across some of our project to linux from windows, but need to be able to remotely access them.  and we have a splashtop business account.

thanks in advance

i have tried the following :

installed splashtop streamer
deployed with our code
but when trying to connect, i get a invalid token error.

Title: Splashtop Streamer on Ubuntu Server


问:
how can I set file name of uploading file in react app instead of express?
I want to set the name of the file that will upload by multer,from client in react app.
my multer storage is this :

```<code>const storage = multer.diskStorage({
  destination : (req , file , cb)=>{
    cb(null , './images')
  },
  filename : (req , file , cb)=>{
    cb(null, req.body.name)

  }
})
</code>```

and my form handler function in react is this :

```<code> async function handle(e) {
    e.preventDefault()
    const data = new FormData()
    data.append('name' , 'something')
    data.append('avatar' , file )
   await axios.post('http://localhost:5000/api/upload' , data)
    .then(res => console.log(res.data))
  }
</code>```

I want to set the file name from the client.
I set name "something" in here.
But when I log req.body in the storage cb it shows an embpty object.
how can I do this?

Body:
I want to set the name of the file that will upload by multer,from client in react app.
my multer storage is this :

const storage = multer.diskStorage({
  destination : (req , file , cb)=>{
    cb(null , './images')
  },
  filename : (req , file , cb)=>{
    cb(null, req.body.name)

  }
})

and my form handler function in react is this :

 async function handle(e) {
    e.preventDefault()
    const data = new FormData()
    data.append('name' , 'something')
    data.append('avatar' , file )
   await axios.post('http://localhost:5000/api/upload' , data)
    .then(res => console.log(res.data))
  }

I want to set the file name from the client.
I set name "something" in here.
But when I log req.body in the storage cb it shows an embpty object.
how can I do this?


问:
Rbac superset enable role on dashboard
i want to disabled acces for some user to some dashboards.

i enable DASHBOARD_RBAC feature flag in my config.py configuration file but i dont see the role filter appear in the edit propreties

```<code>DASHBOARD_RBAC = True
</code>```

Title: Rbac superset enable role on dashboard

Body:
i want to disabled acces for some user to some dashboards.

i enable DASHBOARD_RBAC feature flag in my config.py configuration file but i dont see the role filter appear in the edit propreties

DASHBOARD_RBAC = True


问:
How to assign values & keys to a string from an associative array (foreach)
I am trying to assign a variable to each keys and values of an associate array so I can use it later on in php. The key values is dynamically generated

```<code>$keys= '';
$items= '';
foreach($_POST as $key => $item) {
$keys .= $key . '<br>';
$items .= $item . '<br>';
}
</code>```

when
echo $keys

item1
price1
unit1
btnsave

and when
echo $item

CFGreen
0.16
each
EDIT

what I want is to assign a variable to each one

```<code>$item1 = item1
$price1 = price1
$init1 = unit1
</code>```

and exclude the last btnsave

Body:
I am trying to assign a variable to each keys and values of an associate array so I can use it later on in php. The key values is dynamically generated

$keys= '';
$items= '';
foreach($_POST as $key => $item) {
$keys .= $key . '
';
$items .= $item . '
';
}

when
echo $keys

item1
price1
unit1
btnsave

and when
echo $item

CFGreen
0.16
each
EDIT

what I want is to assign a variable to each one

$item1 = item1
$price1 = price1
$init1 = unit1

and exclude the last btnsave


问:
Keras custom loss returning nan
I have the following model:

```<code>def make_model(lr_rate=0.001):
    inp = tf.keras.Input(shape=(height,width,depth))
    x = tf.keras.layers.Conv2D(64, (4, 4),strides=(1,1),use_bias=False,padding='same',name='Conv1')(inp)
    x = tf.keras.layers.BatchNormalization()(x)
    x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)
    x = tf.keras.layers.Conv2D(32, (3, 3),strides=(1,1),use_bias=False,padding='same',name='Conv2')(x)
    x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)
    x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)
    x = tf.keras.layers.Flatten()(x)
    x = tf.keras.layers.Dense(512)(x)
    x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)
    x = tf.keras.layers.Dense(S1 * S2 * 13,name='scores',activation = 'softmax')(x)
    x = tf.keras.layers.Reshape((S1,S2,13))(x)

    model = tf.keras.Model(inputs=inp,outputs = x)

    optimizer_ = tf.keras.optimizers.Adam(learning_rate=lr_rate)
    model.compile(loss=weighted_categorical_crossentropy(),#tf.keras.losses.CategoricalCrossentropy(axis=3),#yolo_loss_classification,
              optimizer=optimizer_,
              metrics=[
                      keras.metrics.TruePositives(name='tp'),
                      keras.metrics.FalsePositives(name='fp'),
                      keras.metrics.TrueNegatives(name='tn'),
                      keras.metrics.FalseNegatives(name='fn'),
                      keras.metrics.Precision(name='precision'),
                      keras.metrics.Recall(name='recall'),
                      keras.metrics.AUC(name='auc')
                      ])
    print(model.summary())
    return model
</code>```

Where I am using a custom weighted categorical crossentropy (CCC) loss, because the "normal" CCC does not work with weighting in my case because my output has too many dimensions. The loss itself seems to work fine when I call it on a test sample but for some reason it turns nan sometimes.:

```<code>def weighted_categorical_crossentropy(weights = the_weights):

    weights = K.variable(weights)

    def loss(y_true, y_pred):
        # scale predictions so that the class probas of each sample sum to 1
        y_pred /= K.sum(y_pred[...,:], axis=-1, keepdims=True)
        # clip to prevent NaN's and Inf's
        y_pred = K.clip(y_pred[...,:], K.epsilon(), 1 - K.epsilon())
        # calc
        loss = y_true[...,:] * K.log(y_pred[...,:]) * weights
        loss = K.sum(-K.sum(loss, 2))
        return loss

    return loss
</code>```

During training the first few epochs work fine, but at some point (usually between epoch 5-10) I suddenly get a nan loss and the training crashes and throws the following exception:

```<code>InvalidArgumentError: Graph execution error:
Detected at node 'assert_greater_equal/Assert/AssertGuard/Assert' defined at (most recent call last):
...
...
Node: 'assert_greater_equal/Assert/AssertGuard/Assert'
assertion failed: [predictions must be >= 0] [Condition x >= y did not hold element-wise:] [x (model_10/reshape_10/Reshape:0) = ] [[[[-nan -nan -nan...]]]...] [y (Cast_4/x:0) = ] [0]
     [[{{node assert_greater_equal/Assert/AssertGuard/Assert}}]] [Op:__inference_train_function_70732]
</code>```

I think it has something to do with my activation functions, that the loss turns nan which is then crashing due to the metrics.
So I really need to find out how to stop my loss returning nan. I have this issue both with ReLU and LeakyReLU, but with LeakyReLU my model trains better (or atleast quicker in the first few epochs). I have already checked my data and there is no nan values in the data.

Title: Keras custom loss returning nan

Body:
I have the following model:

def make_model(lr_rate=0.001):
    inp = tf.keras.Input(shape=(height,width,depth))
    x = tf.keras.layers.Conv2D(64, (4, 4),strides=(1,1),use_bias=False,padding='same',name='Conv1')(inp)
    x = tf.keras.layers.BatchNormalization()(x)
    x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)
    x = tf.keras.layers.Conv2D(32, (3, 3),strides=(1,1),use_bias=False,padding='same',name='Conv2')(x)
    x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)
    x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)
    x = tf.keras.layers.Flatten()(x)
    x = tf.keras.layers.Dense(512)(x)
    x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)
    x = tf.keras.layers.Dense(S1 * S2 * 13,name='scores',activation = 'softmax')(x)
    x = tf.keras.layers.Reshape((S1,S2,13))(x)

    model = tf.keras.Model(inputs=inp,outputs = x)

    optimizer_ = tf.keras.optimizers.Adam(learning_rate=lr_rate)
    model.compile(loss=weighted_categorical_crossentropy(),#tf.keras.losses.CategoricalCrossentropy(axis=3),#yolo_loss_classification,
              optimizer=optimizer_,
              metrics=[
                      keras.metrics.TruePositives(name='tp'),
                      keras.metrics.FalsePositives(name='fp'),
                      keras.metrics.TrueNegatives(name='tn'),
                      keras.metrics.FalseNegatives(name='fn'),
                      keras.metrics.Precision(name='precision'),
                      keras.metrics.Recall(name='recall'),
                      keras.metrics.AUC(name='auc')
                      ])
    print(model.summary())
    return model

Where I am using a custom weighted categorical crossentropy (CCC) loss, because the "normal" CCC does not work with weighting in my case because my output has too many dimensions. The loss itself seems to work fine when I call it on a test sample but for some reason it turns nan sometimes.:

def weighted_categorical_crossentropy(weights = the_weights):

    weights = K.variable(weights)

    def loss(y_true, y_pred):
        # scale predictions so that the class probas of each sample sum to 1
        y_pred /= K.sum(y_pred[...,:], axis=-1, keepdims=True)
        # clip to prevent NaN's and Inf's
        y_pred = K.clip(y_pred[...,:], K.epsilon(), 1 - K.epsilon())
        # calc
        loss = y_true[...,:] * K.log(y_pred[...,:]) * weights
        loss = K.sum(-K.sum(loss, 2))
        return loss

    return loss

During training the first few epochs work fine, but at some point (usually between epoch 5-10) I suddenly get a nan loss and the training crashes and throws the following exception:

InvalidArgumentError: Graph execution error:
Detected at node 'assert_greater_equal/Assert/AssertGuard/Assert' defined at (most recent call last):
...
...
Node: 'assert_greater_equal/Assert/AssertGuard/Assert'
assertion failed: [predictions must be >= 0] [Condition x >= y did not hold element-wise:] [x (model_10/reshape_10/Reshape:0) = ] [[[[-nan -nan -nan...]]]...] [y (Cast_4/x:0) = ] [0]
     [[{{node assert_greater_equal/Assert/AssertGuard/Assert}}]] [Op:__inference_train_function_70732]

I think it has something to do with my activation functions, that the loss turns nan which is then crashing due to the metrics.
So I really need to find out how to stop my loss returning nan. I have this issue both with ReLU and LeakyReLU, but with LeakyReLU my model trains better (or atleast quicker in the first few epochs). I have already checked my data and there is no nan values in the data.


问:
Windows COM action invoke on UPNP
I'm working with COM UPnP. I'm trying to send SetAVTransportURI action to urn:upnp-org:serviceId:AVTransport.  SetAVTransportURI requires 3 params:

InstanceID: 0

CurrentURI: http://192.168.0.8/test/1.mp3

CurrentURIMetaData: empty string

after invoking action I'm receiving Failed to invoke action...

here is my code:

```<code>HRESULT ExtractServices(IUPnPDevice * pDevice)
{
    BSTR bstrServiceName = SysAllocString(L"urn:upnp-org:serviceId:AVTransport");

    if(NULL == bstrServiceName)
    {
        return E_OUTOFMEMORY;
    }

    IUPnPServices * pServices = NULL;
    HRESULT hr = pDevice->get_Services(&pServices);

    if(SUCCEEDED(hr))
    {
        IUPnPService * pAppService = NULL;
        hr = pServices->get_Item(bstrServiceName, &pAppService);

        if(SUCCEEDED(hr))
        {
            printf("got AVTransport\r\n");

            VARIANT vInArg;
            VARIANT vRetVal;
            VARIANT vOutVal;

            VariantInit(&vInArg);
            VariantInit(&vRetVal);
            VariantInit(&vOutVal);

            SAFEARRAYBOUND bounds[1];
            bounds[0].lLbound = 0;
            bounds[0].cElements = 3;

            SAFEARRAY* saInArgs = SafeArrayCreate(VT_VARIANT,3,bounds);
            LONG lArg;

            lArg = 0;
            SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"0"));

            lArg = 1;
            SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"http://192.168.0.8/test/1.mp3"));

            lArg = 2;
            SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"NOT_IMPLEMENTED"));

            vInArg.pparray = &saInArgs;
            vInArg.vt = VT_VARIANT | VT_ARRAY | VT_BYREF;

            //VARIANT varInArgs;
            //VariantInit(&varInArgs);
            //varInArgs.vt = VT_VARIANT | VT_ARRAY;
            //V_ARRAY(&varInArgs) = saInArgs;

            hr = pAppService->InvokeAction(SysAllocString(L"SetAVTransportURI"),vInArg,&vRetVal,&vOutVal);

            if(SUCCEEDED(hr))
            {
                printf("InvokeAction success");
            }
            else if(hr == UPNP_E_ACTION_REQUEST_FAILED)
            {
                printf("The device had an internal error; the request could not be executed.");
            }
            else if(hr == UPNP_E_DEVICE_ERROR)
            {
                printf("An unknown error occurred.");
            }
            else if(hr == UPNP_E_DEVICE_TIMEOUT)
            {
                printf("The device has not responded within the 30 second time-out period.");
            }
            else if(hr == UPNP_E_ERROR_PROCESSING_RESPONSE)
            {
                printf("The device has sent a response that cannot be processed; for example, the response was corrupted\n");
            }
            else if(hr == UPNP_E_INVALID_ACTION)
            {
                printf("The action is not supported by the device\n");
            }
            else if(hr == UPNP_E_INVALID_ARGUMENTS)
            {
                printf("One or more of the arguments passed in vInActionArgs is invalid\n");
            }
            else if(hr == UPNP_E_PROTOCOL_ERROR)
            {
                printf("An error occurred at the UPnP control-protocol level\n");
            }
            else if(hr == UPNP_E_TRANSPORT_ERROR)
            {
                printf("An HTTP error occurred. Use the IUPnPService::LastTransportStatus property to obtain the actual HTTP status code\n");
            }
            else
            {
                printf("Failed to invoke action...\n");
            }

            pAppService->Release();
        }

        pServices->Release();
    }
    SysFreeString(bstrServiceName);
    return hr;
}
</code>```

I think the problem is with passing params in VARIANT section, can anyone give me a hand with that?

I have changed my code:

```<code>HRESULT ExtractServices(IUPnPDevice * pDevice)
{
    BSTR bstrServiceName = SysAllocString(L"urn:upnp-org:serviceId:AVTransport");

    if(NULL == bstrServiceName)
    {
        return E_OUTOFMEMORY;
    }

    IUPnPServices * pServices = NULL;
    HRESULT hr = pDevice->get_Services(&pServices);

    if(SUCCEEDED(hr))
    {
        IUPnPService * pAppService = NULL;
        hr = pServices->get_Item(bstrServiceName, &pAppService);

        if(SUCCEEDED(hr))
        {
            printf("got AVTransport\r\n");

            VARIANT vInArg;
            VARIANT vRetVal;
            VARIANT vOutVal;

            VariantInit(&vInArg);
            VariantInit(&vRetVal);
            VariantInit(&vOutVal);

            SAFEARRAYBOUND bounds[1];
            bounds[0].lLbound = 0;
            bounds[0].cElements = 2;

            SAFEARRAY* saInArgs = SafeArrayCreate(VT_VARIANT,1,bounds);
            VARIANT vParam;
            LONG lParam[1];

            VariantInit(&vParam);
            vParam.vt = VT_BSTR;
            V_BSTR(&vParam) = SysAllocString(L"http://192.168.0.8/test/1.mp3");
            lParam[0] = 0;
            SafeArrayPutElement(saInArgs,lParam,&vParam);
            VariantClear(&vParam);

            VariantInit(&vParam);
            vParam.vt = VT_BSTR;
            V_BSTR(&vParam) = SysAllocString(L"");
            lParam[0] = 1;
            SafeArrayPutElement(saInArgs,lParam,&vParam);
            VariantClear(&vParam);

            vInArg.vt = VT_ARRAY | VT_VARIANT;
            V_ARRAY(&vInArg) = saInArgs;

            //VARIANT varInArgs;
            //VariantInit(&varInArgs);
            //varInArgs.vt = VT_VARIANT | VT_ARRAY | VT_BSTR;
            //V_ARRAY(&varInArgs) = saInArgs;

            hr = pAppService->InvokeAction(SysAllocString(L"SetAVTransportURI"),vInArg,&vRetVal,&vOutVal);

            if(SUCCEEDED(hr))
            {
                printf("InvokeAction success");
            }
            else if(hr == UPNP_E_ACTION_REQUEST_FAILED)
            {
                printf("The device had an internal error; the request could not be executed.");
            }
            else if(hr == UPNP_E_DEVICE_ERROR)
            {
                printf("An unknown error occurred.");
            }
            else if(hr == UPNP_E_DEVICE_TIMEOUT)
            {
                printf("The device has not responded within the 30 second time-out period.");
            }
            else if(hr == UPNP_E_ERROR_PROCESSING_RESPONSE)
            {
                printf("The device has sent a response that cannot be processed; for example, the response was corrupted\n");
            }
            else if(hr == UPNP_E_INVALID_ACTION)
            {
                printf("The action is not supported by the device\n");
            }
            else if(hr == UPNP_E_INVALID_ARGUMENTS)
            {
                printf("One or more of the arguments passed in vInActionArgs is invalid\n");
            }
            else if(hr == UPNP_E_PROTOCOL_ERROR)
            {
                printf("An error occurred at the UPnP control-protocol level\n");
            }
            else if(hr == UPNP_E_TRANSPORT_ERROR)
            {
                printf("An HTTP error occurred. Use the IUPnPService::LastTransportStatus property to obtain the actual HTTP status code\n");
            }
            else
            {
                printf("Failed to invoke action... %d\n",hr);
            }

            pAppService->Release();
        }

        pServices->Release();
    }
    SysFreeString(bstrServiceName);
    return hr;
}
</code>```

and I still have problem with the args: One or more of the arguments passed in vInActionArgs is invalid...

ContentLicense: CC BY-SA 3.0

Title: Windows COM action invoke on UPNP

Body:
I'm working with COM UPnP. I'm trying to send SetAVTransportURI action to urn:upnp-org:serviceId:AVTransport.  SetAVTransportURI requires 3 params:

InstanceID: 0

CurrentURI: http://192.168.0.8/test/1.mp3

CurrentURIMetaData: empty string

after invoking action I'm receiving Failed to invoke action...

here is my code:

HRESULT ExtractServices(IUPnPDevice * pDevice)
{
    BSTR bstrServiceName = SysAllocString(L"urn:upnp-org:serviceId:AVTransport");

    if(NULL == bstrServiceName)
    {
        return E_OUTOFMEMORY;
    }

    IUPnPServices * pServices = NULL;
    HRESULT hr = pDevice->get_Services(&pServices);

    if(SUCCEEDED(hr))
    {
        IUPnPService * pAppService = NULL;
        hr = pServices->get_Item(bstrServiceName, &pAppService);

        if(SUCCEEDED(hr))
        {
            printf("got AVTransport\r\n");

            VARIANT vInArg;
            VARIANT vRetVal;
            VARIANT vOutVal;

            VariantInit(&vInArg);
            VariantInit(&vRetVal);
            VariantInit(&vOutVal);

            SAFEARRAYBOUND bounds[1];
            bounds[0].lLbound = 0;
            bounds[0].cElements = 3;

            SAFEARRAY* saInArgs = SafeArrayCreate(VT_VARIANT,3,bounds);
            LONG lArg;

            lArg = 0;
            SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"0"));

            lArg = 1;
            SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"http://192.168.0.8/test/1.mp3"));

            lArg = 2;
            SafeArrayPutElement(saInArgs,&lArg,SysAllocString(L"NOT_IMPLEMENTED"));

            vInArg.pparray = &saInArgs;
            vInArg.vt = VT_VARIANT | VT_ARRAY | VT_BYREF;

            //VARIANT varInArgs;
            //VariantInit(&varInArgs);
            //varInArgs.vt = VT_VARIANT | VT_ARRAY;
            //V_ARRAY(&varInArgs) = saInArgs;

            hr = pAppService->InvokeAction(SysAllocString(L"SetAVTransportURI"),vInArg,&vRetVal,&vOutVal);

            if(SUCCEEDED(hr))
            {
                printf("InvokeAction success");
            }
            else if(hr == UPNP_E_ACTION_REQUEST_FAILED)
            {
                printf("The device had an internal error; the request could not be executed.");
            }
            else if(hr == UPNP_E_DEVICE_ERROR)
            {
                printf("An unknown error occurred.");
            }
            else if(hr == UPNP_E_DEVICE_TIMEOUT)
            {
                printf("The device has not responded within the 30 second time-out period.");
            }
            else if(hr == UPNP_E_ERROR_PROCESSING_RESPONSE)
            {
                printf("The device has sent a response that cannot be processed; for example, the response was corrupted\n");
            }
            else if(hr == UPNP_E_INVALID_ACTION)
            {
                printf("The action is not supported by the device\n");
            }
            else if(hr == UPNP_E_INVALID_ARGUMENTS)
            {
                printf("One or more of the arguments passed in vInActionArgs is invalid\n");
            }
            else if(hr == UPNP_E_PROTOCOL_ERROR)
            {
                printf("An error occurred at the UPnP control-protocol level\n");
            }
            else if(hr == UPNP_E_TRANSPORT_ERROR)
            {
                printf("An HTTP error occurred. Use the IUPnPService::LastTransportStatus property to obtain the actual HTTP status code\n");
            }
            else
            {
                printf("Failed to invoke action...\n");
            }

            pAppService->Release();
        }

        pServices->Release();
    }
    SysFreeString(bstrServiceName);
    return hr;
}

I think the problem is with passing params in VARIANT section, can anyone give me a hand with that?

I have changed my code:

HRESULT ExtractServices(IUPnPDevice * pDevice)
{
    BSTR bstrServiceName = SysAllocString(L"urn:upnp-org:serviceId:AVTransport");

    if(NULL == bstrServiceName)
    {
        return E_OUTOFMEMORY;
    }

    IUPnPServices * pServices = NULL;
    HRESULT hr = pDevice->get_Services(&pServices);

    if(SUCCEEDED(hr))
    {
        IUPnPService * pAppService = NULL;
        hr = pServices->get_Item(bstrServiceName, &pAppService);

        if(SUCCEEDED(hr))
        {
            printf("got AVTransport\r\n");

            VARIANT vInArg;
            VARIANT vRetVal;
            VARIANT vOutVal;

            VariantInit(&vInArg);
            VariantInit(&vRetVal);
            VariantInit(&vOutVal);

            SAFEARRAYBOUND bounds[1];
            bounds[0].lLbound = 0;
            bounds[0].cElements = 2;

            SAFEARRAY* saInArgs = SafeArrayCreate(VT_VARIANT,1,bounds);
            VARIANT vParam;
            LONG lParam[1];

            VariantInit(&vParam);
            vParam.vt = VT_BSTR;
            V_BSTR(&vParam) = SysAllocString(L"http://192.168.0.8/test/1.mp3");
            lParam[0] = 0;
            SafeArrayPutElement(saInArgs,lParam,&vParam);
            VariantClear(&vParam);

            VariantInit(&vParam);
            vParam.vt = VT_BSTR;
            V_BSTR(&vParam) = SysAllocString(L"");
            lParam[0] = 1;
            SafeArrayPutElement(saInArgs,lParam,&vParam);
            VariantClear(&vParam);

            vInArg.vt = VT_ARRAY | VT_VARIANT;
            V_ARRAY(&vInArg) = saInArgs;

            //VARIANT varInArgs;
            //VariantInit(&varInArgs);
            //varInArgs.vt = VT_VARIANT | VT_ARRAY | VT_BSTR;
            //V_ARRAY(&varInArgs) = saInArgs;

            hr = pAppService->InvokeAction(SysAllocString(L"SetAVTransportURI"),vInArg,&vRetVal,&vOutVal);

            if(SUCCEEDED(hr))
            {
                printf("InvokeAction success");
            }
            else if(hr == UPNP_E_ACTION_REQUEST_FAILED)
            {
                printf("The device had an internal error; the request could not be executed.");
            }
            else if(hr == UPNP_E_DEVICE_ERROR)
            {
                printf("An unknown error occurred.");
            }
            else if(hr == UPNP_E_DEVICE_TIMEOUT)
            {
                printf("The device has not responded within the 30 second time-out period.");
            }
            else if(hr == UPNP_E_ERROR_PROCESSING_RESPONSE)
            {
                printf("The device has sent a response that cannot be processed; for example, the response was corrupted\n");
            }
            else if(hr == UPNP_E_INVALID_ACTION)
            {
                printf("The action is not supported by the device\n");
            }
            else if(hr == UPNP_E_INVALID_ARGUMENTS)
            {
                printf("One or more of the arguments passed in vInActionArgs is invalid\n");
            }
            else if(hr == UPNP_E_PROTOCOL_ERROR)
            {
                printf("An error occurred at the UPnP control-protocol level\n");
            }
            else if(hr == UPNP_E_TRANSPORT_ERROR)
            {
                printf("An HTTP error occurred. Use the IUPnPService::LastTransportStatus property to obtain the actual HTTP status code\n");
            }
            else
            {
                printf("Failed to invoke action... %d\n",hr);
            }

            pAppService->Release();
        }

        pServices->Release();
    }
    SysFreeString(bstrServiceName);
    return hr;
}

and I still have problem with the args: One or more of the arguments passed in vInActionArgs is invalid...