问:
Wordpress: pre_get_posts with custom field doesn't order and no results found
after reading a lot of solutions and trying different ways I write here for help. I want to order with pre_reg_post custom post by custom field. By default all of it's perfect and all posts are sorted by date but I want to sort it by custom meta value added with ACF.

meta_key: ppa_data_ora_pubblicazione
meta_value: 2022-12-26 08:00:00

I tried:

```<code>function custom_meta_key_orderby( $query ) {
    // do not modify queries in the admin
    if( is_admin() ) {
          return $query;
    }

    $meta_query = array(
        'ppa_data_ora_pubblicazione' => array(
            'key'     => 'ppa_data_ora_pubblicazione',
            'compare' => 'EXISTS',
        )
    );
    $order_by = array(
        'ppa_data_ora_pubblicazione' => 'ASC',
    );

    $query->set( 'meta_query', $meta_query );
    $query->set( 'orderby', $order_by );

    return $query;
}
add_filter( 'pre_get_posts', 'custom_meta_key_orderby' );

</code>```

and

```<code>function custom_meta_key_orderby( $query ) {
    // do not modify queries in the admin
    if( is_admin() ) {
          return $query;
    }

    /*
    Do a meta query to ensure the end date is greater than today
    Order by meta_value_num (the value of a meta field)
    Set the 'meta_key' to the start date, so that's the meta field that posts are sorted by
    Put it in ascending order, so events starting sooner are before the later ones
    */
    $meta_query = array(
        'relation' => 'AND',
        'ppa_data_ora_pubblicazione' => array(
            'key'     => 'ppa_data_ora_pubblicazione',
            'type'    => 'CHAR',
            'compare' => 'EXISTS',
        )
    );

    $query->set( 'meta_query', $meta_query );
    $query->set( 'orderby', array( 'ppa_data_ora_pubblicazione' => 'ASC' ) );
    $query->set( 'meta_key', 'ppa_data_ora_pubblicazione' );
    $query->set( 'order', 'ASC' );

    return $query;
}
add_filter( 'pre_get_posts', 'custom_meta_key_orderby' );
</code>```

only with a new WP_Query I can resolve it. Why previous code doesn't work?

Thanks

Body:
after reading a lot of solutions and trying different ways I write here for help. I want to order with pre_reg_post custom post by custom field. By default all of it's perfect and all posts are sorted by date but I want to sort it by custom meta value added with ACF.

meta_key: ppa_data_ora_pubblicazione
meta_value: 2022-12-26 08:00:00

I tried:

function custom_meta_key_orderby( $query ) {
    // do not modify queries in the admin
    if( is_admin() ) {
          return $query;
    }

    $meta_query = array(
        'ppa_data_ora_pubblicazione' => array(
            'key'     => 'ppa_data_ora_pubblicazione',
            'compare' => 'EXISTS',
        )
    );
    $order_by = array(
        'ppa_data_ora_pubblicazione' => 'ASC',
    );

    $query->set( 'meta_query', $meta_query );
    $query->set( 'orderby', $order_by );

    return $query;
}
add_filter( 'pre_get_posts', 'custom_meta_key_orderby' );

and

function custom_meta_key_orderby( $query ) {
    // do not modify queries in the admin
    if( is_admin() ) {
          return $query;
    }

    /*
    Do a meta query to ensure the end date is greater than today
    Order by meta_value_num (the value of a meta field)
    Set the 'meta_key' to the start date, so that's the meta field that posts are sorted by
    Put it in ascending order, so events starting sooner are before the later ones
    */
    $meta_query = array(
        'relation' => 'AND',
        'ppa_data_ora_pubblicazione' => array(
            'key'     => 'ppa_data_ora_pubblicazione',
            'type'    => 'CHAR',
            'compare' => 'EXISTS',
        )
    );

    $query->set( 'meta_query', $meta_query );
    $query->set( 'orderby', array( 'ppa_data_ora_pubblicazione' => 'ASC' ) );
    $query->set( 'meta_key', 'ppa_data_ora_pubblicazione' );
    $query->set( 'order', 'ASC' );

    return $query;
}
add_filter( 'pre_get_posts', 'custom_meta_key_orderby' );

only with a new WP_Query I can resolve it. Why previous code doesn't work?

Thanks


来源: stackexchange

问:
IntelliJ - how to set livetemplates to search not only from left to right, but in whole word?
Let's say there is a custom live template with some triggers.

When I type for example "ment" -->
I want to see the code snippet as a suggestion which trigger is "comment".

But currently it can search only from left to right, not in the trigger string.

Tried to check settings, to search stackoverflow but no luck

ContentLicense: CC BY-SA 4.0


问:
Node JS stream sort big file
Thanks for helping!

I have a global task - i need to sort big file, for example its 1gb and .csv (strings in file).
Of course i must do it without using full memory, only via stream.

The method of sorting is not important, i want by string.length.

I divided the task to subtasks.

First is create the object mb Map collection which could contain infromantion:

key string.length = value is count of keys with the same lenght

Idea in that i can use this object in next read stream and write stream to write strings to file by their length.Search in big file this some range of length strigs ( up to 15 length for example) and write their to new sort file and etc.

I only learning how correctly use stream, so i need help:

1. global task - correct alorithm i selected or is there a better solution ?

2. i am stuck in read stream for adding information to object, thats my code:

```<code>    const fs = require('fs');
    const readline = require('readline');

    const readableStream = fs.createReadStream('input.csv', {highWaterMark: 8000});

    let fileStructure = {};

    let count = 1;

    readableStream.on('data', (chunk) => {

        if (!fileStructure[chunk.length]) {
            fileStructure[chunk.length] = count
        }
        fileStructure[chunk.length] = ++count

    });
console.log(fileStructure);
</code>```

if i create a console.log i will see that object fileStructure is empty

Thanks !

P.S please share the best practices for working with streams

Title: Node JS stream sort big file

Body:
Thanks for helping!

I have a global task - i need to sort big file, for example its 1gb and .csv (strings in file).
Of course i must do it without using full memory, only via stream.

The method of sorting is not important, i want by string.length.

I divided the task to subtasks.

First is create the object mb Map collection which could contain infromantion:

key string.length = value is count of keys with the same lenght

Idea in that i can use this object in next read stream and write stream to write strings to file by their length.Search in big file this some range of length strigs ( up to 15 length for example) and write their to new sort file and etc.

I only learning how correctly use stream, so i need help:

1. global task - correct alorithm i selected or is there a better solution ?

2. i am stuck in read stream for adding information to object, thats my code:

    const fs = require('fs');
    const readline = require('readline');

    const readableStream = fs.createReadStream('input.csv', {highWaterMark: 8000});

    let fileStructure = {};

    let count = 1;

    readableStream.on('data', (chunk) => {

        if (!fileStructure[chunk.length]) {
            fileStructure[chunk.length] = count
        }
        fileStructure[chunk.length] = ++count

    });
console.log(fileStructure);

if i create a console.log i will see that object fileStructure is empty

Thanks !

P.S please share the best practices for working with streams


问:
React Navbar account section is not dynamically switching dependent upon logged in status
I have been working on this program in react for a website that has a navigation bar at the top of the page. This navigation bar includes an accounts dropdown on the far right side and the dropdown contents are supposed to be dependent upon a user's logged in status. The pertinent codes are as follows:

My App.js file calls the navbar, which worked before attempting to add this new functionality.

```<code>export default function App() {
  return (
    <div className="App">
      <NavBar />
      <Container className="d-flex align-items-center justify-content-center" style={{ minHeight: "100vh" }}>
        <Router>
          <AuthProvider>
            <Routes>
              <Route exact path="/" element={<Home />} />
              {/* <Route path="/products" element={<Products />} />
              <Route path="/pricing" element={<Pricing />} /> */}
              <Route path="/about" element={<About />} />
              <Route path="/contact" element={<Contact />} />
              <Route path="/login" element={<Login />} />
              <Route path="/signup" element={<Signup />} />
              <Route path='/UpdateProfile' element={<UpdateProfile />} />
              <Route path='/forgot-password' element={<ForgotPassword />} />
              <Route path='/dashboard' element={<Dashboard />} />
            </Routes>
          </AuthProvider>
        </Router>
      </Container>
    </div>
  );
}
</code>```

The Navbar is called

```<code>export default function NavBar() {
  return (
    <>
      <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark" sticky="top">
        <Container>
          <Navbar.Brand href="/">
            <img
              alt=""
              src={logo}
              width="50"
              height="50"
              className="d-inline-block align-middle"
            />{' '}
            MedScanner
          </Navbar.Brand>
          <Navbar.Toggle aria-controls="responsive-navbar-nav" />
          <Navbar.Collapse id="responsive-navbar-nav">
            <Nav className="me-auto">
              <NavDropdown title="Products" id="collasible-nav-dropdown">
                <NavDropdown.Item href="#action/3.1">Scanner 1</NavDropdown.Item>
                <NavDropdown.Item href="#action/3.2">Scanner 2</NavDropdown.Item>
                <NavDropdown.Item href="#action/3.3">Scanner 3</NavDropdown.Item>
                <NavDropdown.Item href="#action/3.3">Scanner 4</NavDropdown.Item>
                <NavDropdown.Item href="#action/3.3">Scanner 5</NavDropdown.Item>
                <NavDropdown.Divider />
                <NavDropdown.Item href="#action/3.4">Compare Scanners</NavDropdown.Item>
              </NavDropdown>
              <NavDropdown title="Pricing" id="collasible-nav-dropdown" href="#subscriptions">
                <NavDropdown.Item href="#action/3.4">Subscriptions</NavDropdown.Item>
                <NavDropdown.Divider />
                <NavDropdown.Item href="#subscriptions/green">Green Tier</NavDropdown.Item>
                <NavDropdown.Item href="#subscriptions/green">Purple Tier</NavDropdown.Item>
              </NavDropdown>
              <Nav.Link href="#Security">Security</Nav.Link>
              <Nav.Link href="/about">About</Nav.Link>
              <Nav.Link href="/contact">Contact Us</Nav.Link>
            </Nav>
            <NavRight />
          </Navbar.Collapse>
        </Container>
      </Navbar>
    </>
  );
}
</code>```

The navbar file calls a NavbarRight function, which is supposed to house the contents of the dropdown and decide which to display.

```<code>import React, { useState } from 'react';
import { Nav, NavDropdown } from 'react-bootstrap';
import styled from 'styled-components';
import * as RiIcons from 'react-icons/ri';
import { useAuth } from '../../contexts/AuthContext';
import NavAccount from './NavAccount';
import NavLogin from './NavLogin';

const NavIcon = styled(NavDropdown)`
    font-size: 30px;
`;

export default function NavRight() {
    const accountTitle = (<RiIcons.RiAccountCircleLine></RiIcons.RiAccountCircleLine>);
    const currentUser = useAuth();
    const [logged, setLogged] = useState(false);

    function isLogged() {
        if (currentUser) {
            setLogged(true);
            return <NavAccount />
        }   else {
            setLogged(false);
            return <NavLogin />
        }

    }

    return (
        <>
            <Nav>
                <NavIcon title={accountTitle} id="collapsible-nav-dropdown" bg="dark" variant="darj" href="#subscriptions">
                    {isLogged}
                </NavIcon>
            </Nav>
        </>
    )
}
</code>```

At this point, dependant upon currentUser, defined in AuthContext, one of two things should be displayed.

```<code>import React from 'react';
import { NavDropdown } from 'react-bootstrap';

export default function NavLogin() {
    return (
        <>
            <NavDropdown.Item href="/login">Log in</NavDropdown.Item>
            <NavDropdown.Item href="/signup">Sign Up</NavDropdown.Item>
        </>
    )
}
</code>```

or

```<code>import React from 'react';
import { NavDropdown } from 'react-bootstrap';

export default function NavAccount() {
    return (
        <>
            <NavDropdown.Item href="/dashboard">Dashboard</NavDropdown.Item>
            <NavDropdown.Item href="/update-profile">Update Profile</NavDropdown.Item>
            <NavDropdown.Item href="/login">Log Out</NavDropdown.Item>
        </>
    )
}
</code>```

The AuthContext file is as follows, and worked previously.

```<code>import React, { useContext, useState, useEffect } from 'react'
import { auth } from '../data/Firebase'

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext);
}

export function AuthProvider({ children }) {
    const [currentUser, setCurrentUser] = useState();
    const [loading, setLoading] = useState(true);

    function signup(email, password) {
        return auth.createUserWithEmailAndPassword(email, password);
    }

    // function signup(email, password) {
    //     return auth.createUserWithEmailAndPassword(email, password).then(
    //         (userCredentials) => {
    //             userCredentials.user.sendEmailVerification();
    //             auth.signOut();
    //         }
    //     );
    // }

    function login(email, password) {
        return auth.signInWithEmailAndPassword(email, password);
    }

    function logout() {
        return auth.signOut();
    }

    function resetPassword(email) {
        return auth.sendPasswordResetEmail(email);
    }

    function updatePassword(email, password) {
        return currentUser.updatePassword(password);
    }

    useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
            setCurrentUser(user);
            setLoading(false);
        })
        return unsubscribe
    }, [])

    const value = {
        currentUser,
        login,
        signup,
        logout,
        resetPassword,
        updatePassword
    }

    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    )
}
</code>```

I am currently recieving the error

```<code>Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
</code>```

I have done a lot of troubleshooting and I think the issue has something to do with the way I am calling it, but I am not quite sure how to fix it. I was also wondering if it would be possible to make, instead of a dropdown, the right side of the screen pop out a new container with the login and/or account stuff? Would that be possible? Thanks for any replies!

Body:
I have been working on this program in react for a website that has a navigation bar at the top of the page. This navigation bar includes an accounts dropdown on the far right side and the dropdown contents are supposed to be dependent upon a user's logged in status. The pertinent codes are as follows:

My App.js file calls the navbar, which worked before attempting to add this new functionality.

export default function App() {
  return (

      <NavBar />
      <Container className="d-flex align-items-center justify-content-center" style={{ minHeight: "100vh" }}>
        <Router>
          <AuthProvider>
            <Routes>
              <Route exact path="/" element={<Home />} />
              {/* <Route path="/products" element={<Products />} />
              <Route path="/pricing" element={<Pricing />} /> */}
              <Route path="/about" element={<About />} />
              <Route path="/contact" element={<Contact />} />
              <Route path="/login" element={<Login />} />
              <Route path="/signup" element={<Signup />} />
              <Route path='/UpdateProfile' element={<UpdateProfile />} />
              <Route path='/forgot-password' element={<ForgotPassword />} />
              <Route path='/dashboard' element={<Dashboard />} />
            </Routes>
          </AuthProvider>
        </Router>
      </Container>

  );
}

The Navbar is called

export default function NavBar() {
  return (
    <>
      <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark" sticky="top">
        <Container>
          <Navbar.Brand href="/">
            {' '}
            MedScanner
          </Navbar.Brand>
          <Navbar.Toggle aria-controls="responsive-navbar-nav" />
          <Navbar.Collapse id="responsive-navbar-nav">

              <NavDropdown title="Products" id="collasible-nav-dropdown">
                <NavDropdown.Item href="#action/3.1">Scanner 1</NavDropdown.Item>
                <NavDropdown.Item href="#action/3.2">Scanner 2</NavDropdown.Item>
                <NavDropdown.Item href="#action/3.3">Scanner 3</NavDropdown.Item>
                <NavDropdown.Item href="#action/3.3">Scanner 4</NavDropdown.Item>
                <NavDropdown.Item href="#action/3.3">Scanner 5</NavDropdown.Item>
                <NavDropdown.Divider />
                <NavDropdown.Item href="#action/3.4">Compare Scanners</NavDropdown.Item>
              </NavDropdown>
              <NavDropdown title="Pricing" id="collasible-nav-dropdown" href="#subscriptions">
                <NavDropdown.Item href="#action/3.4">Subscriptions</NavDropdown.Item>
                <NavDropdown.Divider />
                <NavDropdown.Item href="#subscriptions/green">Green Tier</NavDropdown.Item>
                <NavDropdown.Item href="#subscriptions/green">Purple Tier</NavDropdown.Item>
              </NavDropdown>
              Security
              About
              Contact Us

            <NavRight />
          </Navbar.Collapse>
        </Container>
      </Navbar>
    </>
  );
}

The navbar file calls a NavbarRight function, which is supposed to house the contents of the dropdown and decide which to display.

import React, { useState } from 'react';
import { Nav, NavDropdown } from 'react-bootstrap';
import styled from 'styled-components';
import * as RiIcons from 'react-icons/ri';
import { useAuth } from '../../contexts/AuthContext';
import NavAccount from './NavAccount';
import NavLogin from './NavLogin';

const NavIcon = styled(NavDropdown)`
    font-size: 30px;
`;

export default function NavRight() {
    const accountTitle = (<RiIcons.RiAccountCircleLine></RiIcons.RiAccountCircleLine>);
    const currentUser = useAuth();
    const [logged, setLogged] = useState(false);

    function isLogged() {
        if (currentUser) {
            setLogged(true);
            return <NavAccount />
        }   else {
            setLogged(false);
            return <NavLogin />
        }

    }

    return (
        <>

                <NavIcon title={accountTitle} id="collapsible-nav-dropdown" bg="dark" variant="darj" href="#subscriptions">
                    {isLogged}
                </NavIcon>

        </>
    )
}

At this point, dependant upon currentUser, defined in AuthContext, one of two things should be displayed.

import React from 'react';
import { NavDropdown } from 'react-bootstrap';

export default function NavLogin() {
    return (
        <>
            <NavDropdown.Item href="/login">Log in</NavDropdown.Item>
            <NavDropdown.Item href="/signup">Sign Up</NavDropdown.Item>
        </>
    )
}

or

import React from 'react';
import { NavDropdown } from 'react-bootstrap';

export default function NavAccount() {
    return (
        <>
            <NavDropdown.Item href="/dashboard">Dashboard</NavDropdown.Item>
            <NavDropdown.Item href="/update-profile">Update Profile</NavDropdown.Item>
            <NavDropdown.Item href="/login">Log Out</NavDropdown.Item>
        </>
    )
}

The AuthContext file is as follows, and worked previously.

import React, { useContext, useState, useEffect } from 'react'
import { auth } from '../data/Firebase'

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext);
}

export function AuthProvider({ children }) {
    const [currentUser, setCurrentUser] = useState();
    const [loading, setLoading] = useState(true);

    function signup(email, password) {
        return auth.createUserWithEmailAndPassword(email, password);
    }

    // function signup(email, password) {
    //     return auth.createUserWithEmailAndPassword(email, password).then(
    //         (userCredentials) => {
    //             userCredentials.user.sendEmailVerification();
    //             auth.signOut();
    //         }
    //     );
    // }

    function login(email, password) {
        return auth.signInWithEmailAndPassword(email, password);
    }

    function logout() {
        return auth.signOut();
    }

    function resetPassword(email) {
        return auth.sendPasswordResetEmail(email);
    }

    function updatePassword(email, password) {
        return currentUser.updatePassword(password);
    }

    useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
            setCurrentUser(user);
            setLoading(false);
        })
        return unsubscribe
    }, [])

    const value = {
        currentUser,
        login,
        signup,
        logout,
        resetPassword,
        updatePassword
    }

    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    )
}

I am currently recieving the error

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

I have done a lot of troubleshooting and I think the issue has something to do with the way I am calling it, but I am not quite sure how to fix it. I was also wondering if it would be possible to make, instead of a dropdown, the right side of the screen pop out a new container with the login and/or account stuff? Would that be possible? Thanks for any replies!


问:
Get data from CollectionView to the ViewController
How to passs the data from collectionview to the next Viewcontroller?
I have a class

```<code>class Foods: Codable {
    var id : Int?
    var name : String?
    var image : String?
    var price : Int?
    var category : String?

    init(id: Int?, name: String?, image: String?, price: Int?, category: String?) {
       self.id = id
       self.name = name
       self.image = image
       self.price = price
       self.category = category
   }
}
</code>```

I need to know how to transfer the data from UICollectionView to the Detail Screen if I get all the data from JSON

Here's my code from ViewController

```<code>{
    class HomeScreen: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {

    var foodsList = [Foods]()

    @IBOutlet weak var collectionView: UICollectionView!

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "toDetail" {
                if let food = sender as? Foods {
                    let detailScreen = segue.destination as! DetailScreen
                    detailScreen.food = food
                }
            }
        }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return foodsList.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductsCollectionViewCell", for: indexPath) as? ProductsCollectionViewCell else {return UICollectionViewCell()}

    cell.configure(item: foodsList[indexPath.row])

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let food = foodsList[indexPath.row]

    performSegue(withIdentifier: "toDetail", sender: food)
    collectionView.deselectItem(at: indexPath, animated: true)
}

    }
</code>```

Body:
How to passs the data from collectionview to the next Viewcontroller?
I have a class

class Foods: Codable {
    var id : Int?
    var name : String?
    var image : String?
    var price : Int?
    var category : String?

    init(id: Int?, name: String?, image: String?, price: Int?, category: String?) {
       self.id = id
       self.name = name
       self.image = image
       self.price = price
       self.category = category
   }
}

I need to know how to transfer the data from UICollectionView to the Detail Screen if I get all the data from JSON

Here's my code from ViewController

{
    class HomeScreen: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {

    var foodsList = [Foods]()

    @IBOutlet weak var collectionView: UICollectionView!

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "toDetail" {
                if let food = sender as? Foods {
                    let detailScreen = segue.destination as! DetailScreen
                    detailScreen.food = food
                }
            }
        }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return foodsList.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductsCollectionViewCell", for: indexPath) as? ProductsCollectionViewCell else {return UICollectionViewCell()}

    cell.configure(item: foodsList[indexPath.row])

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let food = foodsList[indexPath.row]

    performSegue(withIdentifier: "toDetail", sender: food)
    collectionView.deselectItem(at: indexPath, animated: true)
}

    }


问:
(Problem resolved) The error text is replaced by the Specials symbol
(Problem resolved)
sadly that i don't remember what exactly helped. I changed language in whole system, installed postgres, and create new container from new image with postgres

Old question:
I would like to understand what is the problem to solve this, but because the error message is replaced with the specials symbol I can't.

Screenshot:

The database customer exists on server xsakonServer

Default encoding is set to UTF-8 (Screenshot)

here is application.yml file:

```<code>server:
  port: 8080

spring:
  application:
    name: customer
  datasource:
    password: password
    url: jdbc:postgresql://localhost:5432/customer
    username: xsakon
  jpa:
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        format_sql: 'true'
    show-sql: 'true'
</code>```

docker-compose.yml file:

```<code>services:
  postgres:
    container_name: postgres
    image: postgres
    environment:
      POSTGRES_USER: xsakon
      POSTGRES_PASSWORD: password
      PGDATA: /data/postgres
    volumes:
      - postgres:/data/postgres
    ports:
      - "5432:5432"
    networks:
      - postgres
    restart: unless-stopped

  pgadmin:
    container_name: pgadmin
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
      PGADMIN_CONFIG_SERVER_MODE: 'False'
    volumes:
      - pgadmin:/var/lib/pgadmin
    ports:
      - "5050:80"
    networks:
      - postgres
    restart: unless-stopped

networks:
  postgres:
    driver: bridge

volumes:
  postgres:
  pgadmin:
</code>```

I already tried replace

```<code>password: password
username: xsakon
</code>```

to

```<code>password: 'password'
username: 'xsakon'
</code>```

in application.yml file. But result is the same

Added parameter -Duser.language=en to Java VM options
(Screenshot) applied then restarted project but it didn't help

I hope somebody find out what is the error massage, then I'll fix the problem by myself

Body:
(Problem resolved)
sadly that i don't remember what exactly helped. I changed language in whole system, installed postgres, and create new container from new image with postgres

Old question:
I would like to understand what is the problem to solve this, but because the error message is replaced with the specials symbol I can't.

Screenshot:

The database customer exists on server xsakonServer

Default encoding is set to UTF-8 (Screenshot)

here is application.yml file:

server:
  port: 8080

spring:
  application:
    name: customer
  datasource:
    password: password
    url: jdbc:postgresql://localhost:5432/customer
    username: xsakon
  jpa:
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        format_sql: 'true'
    show-sql: 'true'

docker-compose.yml file:

services:
  postgres:
    container_name: postgres
    image: postgres
    environment:
      POSTGRES_USER: xsakon
      POSTGRES_PASSWORD: password
      PGDATA: /data/postgres
    volumes:
      - postgres:/data/postgres
    ports:
      - "5432:5432"
    networks:
      - postgres
    restart: unless-stopped

  pgadmin:
    container_name: pgadmin
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
      PGADMIN_CONFIG_SERVER_MODE: 'False'
    volumes:
      - pgadmin:/var/lib/pgadmin
    ports:
      - "5050:80"
    networks:
      - postgres
    restart: unless-stopped

networks:
  postgres:
    driver: bridge

volumes:
  postgres:
  pgadmin:

I already tried replace

password: password
username: xsakon

to

password: 'password'
username: 'xsakon'

in application.yml file. But result is the same

Added parameter -Duser.language=en to Java VM options
(Screenshot) applied then restarted project but it didn't help

I hope somebody find out what is the error massage, then I'll fix the problem by myself


问:
How to create a storybook arg that selects amongst a list of React Elements
One of my components, say a card component, takes an icon component as a child.
This icon component is selected from a fixed list of Icon componnents. I want to be able to create a select control type in the storybook page for the Card component such that I can choose a fixed icon from the list and display them in the Card.

Shape of  component:

<Card>
  {icon}

</Card>
```
<p><code>icon</code> here is a React component.</p>
<p>The Storybook file for <code><Card /></code> looks something like this:</p>
<pre class="lang-js prettyprint-override"><code>const CardTemplate: Story<CardProps> = (args) => <Card {...args} />

export default {
  title: 'Display/Card',
  component: Card,
  args: {
    title: 'fluff',
    description:
      'some description',
  },
  argTypes: {
    icon: {
      defaultValue: null,
      options: [] // How do I make this an array of objects: {label: key, value: value},
      control: {
        type: 'select',
      },
    },
  },
} as Meta

</code>```

In another file I am exporting an object which contains the names and values of each Icon react component:

export const IconsList = {
  Icon1: <Icon1 />,
  Icon2: <Icon2 />,
  Icon3: <Icon3 />,
}
```

How do I ensure that people can switch betweeen these components in the icon arg in the storybook page for <Card /> ?

Body:
One of my components, say a card component, takes an icon component as a child.
This icon component is selected from a fixed list of Icon componnents. I want to be able to create a select control type in the storybook page for the Card component such that I can choose a fixed icon from the list and display them in the Card.

Shape of  component:

<Card>
  {icon}

</Card>

icon here is a React component.

The Storybook file for <Card /> looks something like this:

const CardTemplate: Story<CardProps> = (args) => <Card {...args} />

export default {
  title: 'Display/Card',
  component: Card,
  args: {
    title: 'fluff',
    description:
      'some description',
  },
  argTypes: {
    icon: {
      defaultValue: null,
      options: [] // How do I make this an array of objects: {label: key, value: value},
      control: {
        type: 'select',
      },
    },
  },
} as Meta

In another file I am exporting an object which contains the names and values of each Icon react component:

export const IconsList = {
  Icon1: <Icon1 />,
  Icon2: <Icon2 />,
  Icon3: <Icon3 />,
}

How do I ensure that people can switch betweeen these components in the icon arg in the storybook page for <Card /> ?


问:
Trying to add the email subject, body, and name to an excel sheet from a c# application
As the title stated, I want to transfer data from an email to an excel sheet. But when I run the program it doesn't run with the Microsoft.Office.Interop.Excel namespace included. I have downloaded the necessary NuGets, and the code looks right to me. Any help would be appreciated.</p>
```<code>Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

excel.Visible = true;

Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open("C:\\Users\\Ty\\Documents\\Returns.xlsx");

Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();

NameSpace ns = outlook.GetNamespace("MAPI");

MAPIFolder folder = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

MailItem email = folder.Items[1] as MailItem;

//Use a regular expression to extract the name from the email body
string pattern = @"Full Name:\s*(.*)";

Match match = Regex.Match(email.Body, pattern);

string name = "";

if (match.Success)
{
    name = match.Groups[1].Value;
}

//Add the email subject, body, and name to the Excel sheet
int row = sheet.UsedRange.Rows.Count + 1; // Find the last used row

sheet.Cells[row, 1] = email.Subject;
sheet.Cells[row, 2] = email.Body;
sheet.Cells[row, 3] = name;
</code>```

Body:
As the title stated, I want to transfer data from an email to an excel sheet. But when I run the program it doesn't run with the Microsoft.Office.Interop.Excel namespace included. I have downloaded the necessary NuGets, and the code looks right to me. Any help would be appreciated.

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

excel.Visible = true;

Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open("C:\\Users\\Ty\\Documents\\Returns.xlsx");

Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();

NameSpace ns = outlook.GetNamespace("MAPI");

MAPIFolder folder = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

MailItem email = folder.Items[1] as MailItem;

//Use a regular expression to extract the name from the email body
string pattern = @"Full Name:\s*(.*)";

Match match = Regex.Match(email.Body, pattern);

string name = "";

if (match.Success)
{
    name = match.Groups[1].Value;
}

//Add the email subject, body, and name to the Excel sheet
int row = sheet.UsedRange.Rows.Count + 1; // Find the last used row

sheet.Cells[row, 1] = email.Subject;
sheet.Cells[row, 2] = email.Body;
sheet.Cells[row, 3] = name;


问:
Use password hash created in GO on Django admin auth doesn't work
I'he created a func in GO to simulate the hash password construction in Django. But when i create the user and try to login in Django Admin, i receive invalid password message and the hash of password was changed in database.

The function in go to recreate de pass hash builder is:

```<code>func PasswordEncode(password string, salt string, iterations int) (string, error) {

    if strings.TrimSpace(salt) == "" {
        salt = CreateRandomString(12)
    }

    if strings.Contains(salt, "$") {
        return "", errors.New("salt contains dollar sign ($)")
    }

    if iterations <= 0 {
        iterations = 20000
    }

    hash := pbkdf2.Key([]byte(password), []byte(salt), iterations, sha256.Size, sha256.New)

    b64Hash := base64.StdEncoding.EncodeToString(hash)

    return fmt.Sprintf("%s$%d$%s$%s", "pbkdf2_sha256", iterations, salt, b64Hash), nil
}

func CreateRandomString(len int) string {
    var container string
    var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    b := bytes.NewBufferString(str)
    length := b.Len()
    bigInt := big.NewInt(int64(length))
    for i := 0; i < len; i++ {
        randomInt, _ := rand.Int(rand.Reader, bigInt)
        container += string(str[randomInt.Int64()])
    }
    return container
}
</code>```

So i have this hash to 'example' password :

pbkdf2_sha256$20000$rkOZv4FYyskC$gIn13Rsr229e5AbhgYDTflBWOH9k+d6wEyKPmHryIjI=

But when i try to login in Django admin, i receive the invalid password message and the application change de hash to:

pbkdf2_sha256$390000$M3ntXZosTvxynIk193G107$40btNBSvVzDKXlS3pbrYfxpZV8lyjsTzG+fW/PL7wCY=

Obs.: I'he already tryied to put 22 characteres on salt build func , and set to 390000 iterations, but have the same problem with the difference that the hash is not changed.

Obs(2).: Obviusly, both of applications have the same database for users.

Body:
I'he created a func in GO to simulate the hash password construction in Django. But when i create the user and try to login in Django Admin, i receive invalid password message and the hash of password was changed in database.

The function in go to recreate de pass hash builder is:

func PasswordEncode(password string, salt string, iterations int) (string, error) {

    if strings.TrimSpace(salt) == "" {
        salt = CreateRandomString(12)
    }

    if strings.Contains(salt, "$") {
        return "", errors.New("salt contains dollar sign ($)")
    }

    if iterations <= 0 {
        iterations = 20000
    }

    hash := pbkdf2.Key([]byte(password), []byte(salt), iterations, sha256.Size, sha256.New)

    b64Hash := base64.StdEncoding.EncodeToString(hash)

    return fmt.Sprintf("%s$%d$%s$%s", "pbkdf2_sha256", iterations, salt, b64Hash), nil
}

func CreateRandomString(len int) string {
    var container string
    var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    b := bytes.NewBufferString(str)
    length := b.Len()
    bigInt := big.NewInt(int64(length))
    for i := 0; i < len; i++ {
        randomInt, _ := rand.Int(rand.Reader, bigInt)
        container += string(str[randomInt.Int64()])
    }
    return container
}

So i have this hash to 'example' password :

pbkdf2_sha256$20000$rkOZv4FYyskC$gIn13Rsr229e5AbhgYDTflBWOH9k+d6wEyKPmHryIjI=

But when i try to login in Django admin, i receive the invalid password message and the application change de hash to:

pbkdf2_sha256$390000$M3ntXZosTvxynIk193G107$40btNBSvVzDKXlS3pbrYfxpZV8lyjsTzG+fW/PL7wCY=

Obs.: I'he already tryied to put 22 characteres on salt build func , and set to 390000 iterations, but have the same problem with the difference that the hash is not changed.

Obs(2).: Obviusly, both of applications have the same database for users.


问:
Tools for debugging a java.lang.NoClassDefFoundError: Could not initialize class java.text.NumberFormat$Field?
After migrating from Log4J to Log4J2, we started randomly facing the following issue during a server's start up:

```<code>Caused by: java.lang.NoClassDefFoundError: Could not initialize class java.text.NumberFormat$Field
        at java.text.DecimalFormat.subformat(DecimalFormat.java:1639)
        at java.text.DecimalFormat.format(DecimalFormat.java:712)
        at java.text.DecimalFormat.format(DecimalFormat.java:646)
        at java.text.NumberFormat.format(NumberFormat.java:316)
</code>```

This happens when trying to format a number, i.e. NumberFormat.getIntegerInstance().format(...).

There is no other "Caused by" line that could point to a further issue in the stack trace. It's also baffling that it's not some external dependency, but rather it is complaining about a standard Java class.

The issue happens sometimes on jenkins test runs (not always), and on a single developer's machine (the rest of the team cannot reproduce the issue). Using -Dlog4j2.debug= to enable log4j2 debug messages makes the problem go away, as well as removing a logger for org.springframework, so I have the feeling it might be that the actual cause is happening in some background thread and the error message is being swallowed. We have an implementation of ApplicationContextInitializer for some custom stuff, and if we add the same lines for formatting there that fail at the end of the server's start up, then the problem also goes away, presumably because calling format at the early stages of the server's start up allows the JVM to load the class properly and then the issue is not seen (my assumption).

I've tried:

Putting a breakpoint in the constructor of NoClassDefFoundError,

Catching the error and printing the classpath before the server is killed,

with no luck.

Checking the changes done during the migration is kinda like searching a needle in a haystack as you can imagine.

I'm stuck as to what else to try, specially since I cannot freely reproduce it in a machine I have access to. What tools / techniques / tricks I could use that could point me in the right direction? Maybe some JVM flag to know when it fails to load a class? Any idea is appreciated really.

Body:
After migrating from Log4J to Log4J2, we started randomly facing the following issue during a server's start up:

Caused by: java.lang.NoClassDefFoundError: Could not initialize class java.text.NumberFormat$Field
        at java.text.DecimalFormat.subformat(DecimalFormat.java:1639)
        at java.text.DecimalFormat.format(DecimalFormat.java:712)
        at java.text.DecimalFormat.format(DecimalFormat.java:646)
        at java.text.NumberFormat.format(NumberFormat.java:316)

This happens when trying to format a number, i.e. NumberFormat.getIntegerInstance().format(...).

There is no other "Caused by" line that could point to a further issue in the stack trace. It's also baffling that it's not some external dependency, but rather it is complaining about a standard Java class.

The issue happens sometimes on jenkins test runs (not always), and on a single developer's machine (the rest of the team cannot reproduce the issue). Using -Dlog4j2.debug= to enable log4j2 debug messages makes the problem go away, as well as removing a logger for org.springframework, so I have the feeling it might be that the actual cause is happening in some background thread and the error message is being swallowed. We have an implementation of ApplicationContextInitializer for some custom stuff, and if we add the same lines for formatting there that fail at the end of the server's start up, then the problem also goes away, presumably because calling format at the early stages of the server's start up allows the JVM to load the class properly and then the issue is not seen (my assumption).

I've tried:

Putting a breakpoint in the constructor of NoClassDefFoundError,

Catching the error and printing the classpath before the server is killed,

with no luck.

Checking the changes done during the migration is kinda like searching a needle in a haystack as you can imagine.

I'm stuck as to what else to try, specially since I cannot freely reproduce it in a machine I have access to. What tools / techniques / tricks I could use that could point me in the right direction? Maybe some JVM flag to know when it fails to load a class? Any idea is appreciated really.


问:
Consuming a webservice running in Android app in a Instrumentationtest
I'm trying to figure out how to test a rest api and websocket running inside an android application with a AndroidInstrumentation test.

Service in android is running on 0.0.0.0:5053 and is working fine, but when I'm doing a test for it with AndroidJunitRunner I'm not able to reach the service, neither in 10.0.2.2 nor 10.0.2.15, 10.0.2.16..

None of them worked.

How can I test it? How can I get the IP for those tests?
Thanks


问:
Hide colorbar in plotly.graph.objects (choropleth)
I want to hide the color bar of my Choropleth map but i am not able to.Please help me.

I have used plotly.graph_objects for making my Choropleth Map.

my code for plotting the choropleth map is as follows:

```<code>fig = go.Figure(data=go.Choropleth(
    geojson=x,
    featureidkey='properties.NAME_2',
    locations=df['District'],
    z=df['Temp'],
    customdata= df[["District","Temperature","Min_Temperature","Max_Temperature","Pressure","Humidity","Visiblity","WindSpeed"]],
    marker_line_color='black',
    marker_opacity = 1,
    marker_line_width = 1,
    colorscale = 'Geyser',
    hovertemplate =
    "<b>%{customdata[0]}</b><br><br>"+
    "Temperature: %{customdata[1]}<br>"+
    "Min_Temperature: %{customdata[2]}<br>"+
    "Max_Temperature: %{customdata[3]}<br>"+
    "Pressure: %{customdata[4]}<br>"+
    "Humidity: %{customdata[5]}<br>"+
    "Visiblity: %{customdata[6]}<br>"+
    "Wind Speed: %{customdata[7]}<br>"+
    "<extra></extra>"
))

fig.update_geos(visible=False,fitbounds='locations')

fig.add_trace(go.Scattergeo(
    lon=y['lon_c'],
    lat=y['lat_c'],
    mode='text',
    textposition='top center',
    text=[str(x) for x in df["District"]],
    textfont={'color': 'Black'},
    hoverinfo='skip',
))
fig.update_layout(
    font = dict(
        size = 12
    ),
    margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
    height=680,
    width=800
)
</code>```

Body:
I want to hide the color bar of my Choropleth map but i am not able to.Please help me.

I have used plotly.graph_objects for making my Choropleth Map.

my code for plotting the choropleth map is as follows:

fig = go.Figure(data=go.Choropleth(
    geojson=x,
    featureidkey='properties.NAME_2',
    locations=df['District'],
    z=df['Temp'],
    customdata= df[["District","Temperature","Min_Temperature","Max_Temperature","Pressure","Humidity","Visiblity","WindSpeed"]],
    marker_line_color='black',
    marker_opacity = 1,
    marker_line_width = 1,
    colorscale = 'Geyser',
    hovertemplate =
    "%{customdata[0]}

"+
    "Temperature: %{customdata[1]}
"+
    "Min_Temperature: %{customdata[2]}
"+
    "Max_Temperature: %{customdata[3]}
"+
    "Pressure: %{customdata[4]}
"+
    "Humidity: %{customdata[5]}
"+
    "Visiblity: %{customdata[6]}
"+
    "Wind Speed: %{customdata[7]}
"+
    "<extra></extra>"
))

fig.update_geos(visible=False,fitbounds='locations')

fig.add_trace(go.Scattergeo(
    lon=y['lon_c'],
    lat=y['lat_c'],
    mode='text',
    textposition='top center',
    text=[str(x) for x in df["District"]],
    textfont={'color': 'Black'},
    hoverinfo='skip',
))
fig.update_layout(
    font = dict(
        size = 12
    ),
    margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
    height=680,
    width=800
)


问:
WebFluxSecurity - @PreAuthorize with or/and conditions fails with exception
I am getting an exception when I try to use the 'and' condition in the @PreAuthorize Spring Boot annotation in the WebFlux mode. When I work with the regular WebSecurity all works as expected.

The exception is:

```<code>Original Stack Trace:
        at org.springframework.security.authorization.method.ReactiveExpressionUtils.lambda$evaluateAsBoolean$0(ReactiveExpressionUtils.java:41) ~[spring-security-core-6.0.1.jar:6.0.1]
        at reactor.core.publisher.MonoErrorSupplied.subscribe(MonoErrorSupplied.java:55) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:165) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.FluxDefaultIfEmpty$DefaultIfEmptySubscriber.onNext(FluxDefaultIfEmpty.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:129) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:158) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.FluxFilter$FilterSubscriber.onNext(FluxFilter.java:113) ~[reactor-core-3.5.1.jar:3.5.1]
    ...
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1001E: Type conversion problem, cannot convert from reactor.core.publisher.MonoDefer<?> to java.lang.Boolean
    at org.springframework.expression.spel.support.StandardTypeConverter.convertValue(StandardTypeConverter.java:87) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.common.ExpressionUtils.convertTypedValue(ExpressionUtils.java:57) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:188) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpAnd.getBooleanValue(OpAnd.java:57) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpAnd.getValueInternal(OpAnd.java:52) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:188) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpAnd.getBooleanValue(OpAnd.java:57) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpAnd.getValueInternal(OpAnd.java:48) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:188) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpOr.getBooleanValue(OpOr.java:56) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpOr.getValueInternal(OpOr.java:51) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpOr.getValueInternal(OpOr.java:37) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:112) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:273) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.security.authorization.method.ReactiveExpressionUtils.lambda$evaluateAsBoolean$1(ReactiveExpressionUtils.java:37) ~[spring-security-core-6.0.1.jar:6.0.1]
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44) ~[reactor-core-3.5.1.jar:3.5.1]
    at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:165) ~[reactor-core-3.5.1.jar:3.5.1]
    at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
    at reactor.core.publisher.FluxDefaultIfEmpty$DefaultIfEmptySubscriber.onNext(FluxDefaultIfEmpty.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
...
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [reactor.core.publisher.MonoDefer<?>] to type [java.lang.Boolean]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:322) ~[spring-core-6.0.3.jar:6.0.3]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195) ~[spring-core-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.support.StandardTypeConverter.convertValue(StandardTypeConverter.java:82) ~[spring-expression-6.0.3.jar:6.0.3]
    ... 262 common frames omitted
</code>```

Environment: Spring Boot 3.0.1, Java 17

My server uses the standard Spring boot Security Configuration:

```<code>@EnableWebFluxSecurity
@Configuration
@EnableReactiveMethodSecurity(useAuthorizationManager=true)
public class SecurityConfig {

    @Bean
    SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http.authorizeExchange(exchanges -> exchanges
                        .pathMatchers("/actuator/health").permitAll()
                        .anyExchange().authenticated())
                .csrf().disable().build();
    }
}
</code>```

The PreAuthorize functions class look like this:

```<code>@Configuration
public class PreAuthorizeFunctionsReactive {

    @Bean
    public Function<String, Mono<Boolean>> hasParam() {
        return (param) -> Mono.defer(() -> getJwtToken().map(jwt -> Optional.ofNullable(jwt.getClaimAsString("param"))
            .orElse("")
            .equalsIgnoreCase(param)));
    }

    private Mono<Jwt> getJwtToken() {
        return ReactiveSecurityContextHolder.getContext()
                .map(ctx -> ctx.getAuthentication().getPrincipal())
                .cast(Jwt.class);
   }

}
</code>```

The controller class looks like this:

```<code>@RestController
@RequestMapping("/v1/test")
@Slf4j
public class TestControllerReactive {

    @PostMapping(path = "/auth/{param}/test", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
    @PreAuthorize("hasRole('admin') and @hasParam.apply(#param)")
    public Mono<String> testPreAuthorize(
        @RequestBody Flux<Part> parts,
        @PathVariable Mono<String> param) {
        return Mono.just("OK");
    }
}
</code>```

I tried several variants of the @PreAuthorize format:

@PreAuthorize(@hasParam.apply(#param)") - working as expected

@PreAuthorize(@hasParam.apply(#param) and @hasSome.apply(#param)") - fails with the exception above

@PreAuthorize("hasRole('admin') and @hasParam.apply(#param)") - fails with the exception above

I assume that the 'and'/'or' operators does not know how to work with Reactive/Mono objects that the @hasParam.apply(#param) returns.

So, the question is, is there a way to override the 'and'/'or' operators (what did I miss in the configuration)?

Body:
I am getting an exception when I try to use the 'and' condition in the @PreAuthorize Spring Boot annotation in the WebFlux mode. When I work with the regular WebSecurity all works as expected.

The exception is:

Original Stack Trace:
        at org.springframework.security.authorization.method.ReactiveExpressionUtils.lambda$evaluateAsBoolean$0(ReactiveExpressionUtils.java:41) ~[spring-security-core-6.0.1.jar:6.0.1]
        at reactor.core.publisher.MonoErrorSupplied.subscribe(MonoErrorSupplied.java:55) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:165) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.FluxDefaultIfEmpty$DefaultIfEmptySubscriber.onNext(FluxDefaultIfEmpty.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:129) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:158) ~[reactor-core-3.5.1.jar:3.5.1]
        at reactor.core.publisher.FluxFilter$FilterSubscriber.onNext(FluxFilter.java:113) ~[reactor-core-3.5.1.jar:3.5.1]
    ...
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1001E: Type conversion problem, cannot convert from reactor.core.publisher.MonoDefer<?> to java.lang.Boolean
    at org.springframework.expression.spel.support.StandardTypeConverter.convertValue(StandardTypeConverter.java:87) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.common.ExpressionUtils.convertTypedValue(ExpressionUtils.java:57) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:188) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpAnd.getBooleanValue(OpAnd.java:57) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpAnd.getValueInternal(OpAnd.java:52) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:188) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpAnd.getBooleanValue(OpAnd.java:57) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpAnd.getValueInternal(OpAnd.java:48) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:188) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpOr.getBooleanValue(OpOr.java:56) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpOr.getValueInternal(OpOr.java:51) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.OpOr.getValueInternal(OpOr.java:37) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:112) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:273) ~[spring-expression-6.0.3.jar:6.0.3]
    at org.springframework.security.authorization.method.ReactiveExpressionUtils.lambda$evaluateAsBoolean$1(ReactiveExpressionUtils.java:37) ~[spring-security-core-6.0.1.jar:6.0.1]
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44) ~[reactor-core-3.5.1.jar:3.5.1]
    at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:165) ~[reactor-core-3.5.1.jar:3.5.1]
    at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
    at reactor.core.publisher.FluxDefaultIfEmpty$DefaultIfEmptySubscriber.onNext(FluxDefaultIfEmpty.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
...
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [reactor.core.publisher.MonoDefer<?>] to type [java.lang.Boolean]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:322) ~[spring-core-6.0.3.jar:6.0.3]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195) ~[spring-core-6.0.3.jar:6.0.3]
    at org.springframework.expression.spel.support.StandardTypeConverter.convertValue(StandardTypeConverter.java:82) ~[spring-expression-6.0.3.jar:6.0.3]
    ... 262 common frames omitted

Environment: Spring Boot 3.0.1, Java 17

My server uses the standard Spring boot Security Configuration:

@EnableWebFluxSecurity
@Configuration
@EnableReactiveMethodSecurity(useAuthorizationManager=true)
public class SecurityConfig {

    @Bean
    SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http.authorizeExchange(exchanges -> exchanges
                        .pathMatchers("/actuator/health").permitAll()
                        .anyExchange().authenticated())
                .csrf().disable().build();
    }
}

The PreAuthorize functions class look like this:

@Configuration
public class PreAuthorizeFunctionsReactive {

    @Bean
    public Function<String, Mono<Boolean>> hasParam() {
        return (param) -> Mono.defer(() -> getJwtToken().map(jwt -> Optional.ofNullable(jwt.getClaimAsString("param"))
            .orElse("")
            .equalsIgnoreCase(param)));
    }

    private Mono<Jwt> getJwtToken() {
        return ReactiveSecurityContextHolder.getContext()
                .map(ctx -> ctx.getAuthentication().getPrincipal())
                .cast(Jwt.class);
   }

}

The controller class looks like this:

@RestController
@RequestMapping("/v1/test")
@Slf4j
public class TestControllerReactive {

    @PostMapping(path = "/auth/{param}/test", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
    @PreAuthorize("hasRole('admin') and @hasParam.apply(#param)")
    public Mono<String> testPreAuthorize(
        @RequestBody Flux<Part> parts,
        @PathVariable Mono<String> param) {
        return Mono.just("OK");
    }
}

I tried several variants of the @PreAuthorize format:

@PreAuthorize(@hasParam.apply(#param)") - working as expected

@PreAuthorize(@hasParam.apply(#param) and @hasSome.apply(#param)") - fails with the exception above

@PreAuthorize("hasRole('admin') and @hasParam.apply(#param)") - fails with the exception above

I assume that the 'and'/'or' operators does not know how to work with Reactive/Mono objects that the @hasParam.apply(#param) returns.

So, the question is, is there a way to override the 'and'/'or' operators (what did I miss in the configuration)?


问:
How can i plot a graph of String weekdays vs temperature using MPAndroidChart?
Im trying to plot a graph that shows measured data. In the xaxis will show the days ordered by date, in the yaxis will show temperature, i made a code using MPAndroidChart ( https://github.com/PhilJay/MPAndroidChart ), in this library you can change the value formatter of the axis.
this are the entrys that i used (taken from log):

```<code>Entry, x: 0.0 y: 27.02
Entry, x: 1.0 y: 26.52
Entry, x: 2.0 y: 28.5
Entry, x: 3.0 y: 29.26
Entry, x: 4.0 y: 33.34
</code>```

with the formatter i get this possible strings [Ju 22, Vi 23, Do 25, Lu 26, Ma 27], so the graph should be showing something like this:

```<code>Entry, x: Ju 22 y: 27.02
Entry, x: Vi 23 y: 26.52
Entry, x: Do 25 y: 28.5
Entry, x: Lu 26 y: 29.26
Entry, x: Ma 27 y: 33.34
</code>```

but it doesnt, turns out that the function override fun getFormattedValue(value: Float, axis: AxisBase?): String? {} has this Value:Float variable, the variable interpolate the values from the entries, i get this data from that:

```<code>E/Value: 0.0
E/Value: 0.7
E/Value: 1.4
E/Value: 2.1
E/Value: 2.8
E/Value: 3.5
</code>```

So you as you can imagine i get this Strings in the xaxis (You have this return from the formatter function: dateString[value.toInt()]):

```<code>Ju 23 , Ju 23, Vi 23, Do 25, Do 25, Lu 26
</code>```

Obviously this return its not optimal, the graph have no sense if you have 2 equal dates shown in the axes.

Someone can help improving this?

Body:
Im trying to plot a graph that shows measured data. In the xaxis will show the days ordered by date, in the yaxis will show temperature, i made a code using MPAndroidChart ( https://github.com/PhilJay/MPAndroidChart ), in this library you can change the value formatter of the axis.
this are the entrys that i used (taken from log):

Entry, x: 0.0 y: 27.02
Entry, x: 1.0 y: 26.52
Entry, x: 2.0 y: 28.5
Entry, x: 3.0 y: 29.26
Entry, x: 4.0 y: 33.34

with the formatter i get this possible strings [Ju 22, Vi 23, Do 25, Lu 26, Ma 27], so the graph should be showing something like this:

Entry, x: Ju 22 y: 27.02
Entry, x: Vi 23 y: 26.52
Entry, x: Do 25 y: 28.5
Entry, x: Lu 26 y: 29.26
Entry, x: Ma 27 y: 33.34

but it doesnt, turns out that the function override fun getFormattedValue(value: Float, axis: AxisBase?): String? {} has this Value:Float variable, the variable interpolate the values from the entries, i get this data from that:

E/Value: 0.0
E/Value: 0.7
E/Value: 1.4
E/Value: 2.1
E/Value: 2.8
E/Value: 3.5

So you as you can imagine i get this Strings in the xaxis (You have this return from the formatter function: dateString[value.toInt()]):

Ju 23 , Ju 23, Vi 23, Do 25, Do 25, Lu 26

Obviously this return its not optimal, the graph have no sense if you have 2 equal dates shown in the axes.

Someone can help improving this?


问:
Convert images to pdf without compressing in Python
I want to club some images to create a pdf, but these images are in ppm format to save color information as jpg averages the color information in some parts of the image to compress the image. When converted to pdf using in python it creates the pdf using jpg conversion and the color is lost in some parts of the images. What should I do to retain the color?

This is the code I am using to create the pdf. I am using pillow to save multiple images in a pdf.

```<code>from PIL import Image
import os
import sys

x = sys.argv[1]
dir = "folder_directory"
l = []
i = 0
image_1 = Image.open(dir + "\\" + os.listdir(dir)[0])
im_1 = image_1.convert('RGB')
for image in os.listdir(dir):
    if i < 1:
        i += 1
        continue
    print(image)
    image_2 = Image.open(dir + "\\" + image)
    im_2 = image_2.convert('RGB')
    l.append(im_2)

im_1.save('saving_dir' + x +'.pdf', save_all=True, append_images=l)
</code>```

Body:
I want to club some images to create a pdf, but these images are in ppm format to save color information as jpg averages the color information in some parts of the image to compress the image. When converted to pdf using in python it creates the pdf using jpg conversion and the color is lost in some parts of the images. What should I do to retain the color?

This is the code I am using to create the pdf. I am using pillow to save multiple images in a pdf.

from PIL import Image
import os
import sys

x = sys.argv[1]
dir = "folder_directory"
l = []
i = 0
image_1 = Image.open(dir + "\\" + os.listdir(dir)[0])
im_1 = image_1.convert('RGB')
for image in os.listdir(dir):
    if i < 1:
        i += 1
        continue
    print(image)
    image_2 = Image.open(dir + "\\" + image)
    im_2 = image_2.convert('RGB')
    l.append(im_2)

im_1.save('saving_dir' + x +'.pdf', save_all=True, append_images=l)


问:
How to implement Copy to Clipboard functionality in NodeJs with Handlebars template engine
I am trying to Implement copy to clipboard functionality in node.js using handlebars templating engine, my logic and code works fine, but when I read through the handlebars documentation, I noticed that handlebars is logicless therefore I can't Implement the JavaScript code.

My question is, what other way around can I go in implementing the copy to clipboard functionality using handlebars.

This is my code handlebars is rendering.

```<code><input type="text" required  id="ref_id"  name="ref_id" value="GH893JKPOdM839" class="form-control margin-bottom-20" placeholder="Referral ID">
<a type="button" class="v-button" onclick="copyLink()" onmouseout="outFunc()">
  <span class="tooltiptext2" id="myTooltip2">Copy to clipboard</span>
  <span style="display:block;padding:15px 60px;line-height:120%;">Copy Ref ID</span>
</a>

<script>
  function copyLink() {
    var copyText = document.getElementById("ref_id");
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    document.execCommand("copy");

    var tooltip = document.getElementById("myTooltip2");
    tooltip.innerHTML = "Copied: " + copyText.value;
  }

  function outFunc() {
    var tooltip = document.getElementById("myTooltip2");
    tooltip.innerHTML = "Copy to clipboard";
  }

  </script>
</code>```

Body:
I am trying to Implement copy to clipboard functionality in node.js using handlebars templating engine, my logic and code works fine, but when I read through the handlebars documentation, I noticed that handlebars is logicless therefore I can't Implement the JavaScript code.

My question is, what other way around can I go in implementing the copy to clipboard functionality using handlebars.

This is my code handlebars is rendering.

<input type="text" required  id="ref_id"  name="ref_id" value="GH893JKPOdM839" class="form-control margin-bottom-20" placeholder="Referral ID">

  Copy to clipboard
  Copy Ref ID


问:
"Define the key for this EntityType." I get that error. But I already defined the key -- Entity Framework code-first

System.Data.Entity.ModelConfiguration.ModelValidationException: 'One or more validation errors were detected during model generation:  // i get that error.

I already defined the key but it is not solved...no matter what I did it didn't work thanks for the help.I want one to one relation.

When I establish a many-to-many or many-to-one relationship, it does not give an error, but I also get this error in a one-to-one relationship.

```<code>using test.entity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Context context = new Context();
            context.Database.Create();
        }
    }
}
</code>```
```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test.entity
{
    public class ProductMainInfo
    {
        [Key]
        public int Id { get; set; }

        public virtual Category Category { get; set; }

        [ForeignKey("Category")]
        public int CategoryId { get;set;}
    }
}
</code>```
```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test.entity
{
    public class Category
    {
        [Key]
        public int id{get;set;}
        public string name{get;set;}
        public virtual ProductMainInfo ProductMainInfo { get; set; }
    }
}
</code>```
```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test.entity
{
    public class Context:DbContext
    {
        public DbSet<Category> Categories { get; set; }
        public DbSet<ProductMainInfo> ProductMainInfos { get; set; }
    }
}
</code>```

Body:
System.Data.Entity.ModelConfiguration.ModelValidationException: 'One or more validation errors were detected during model generation:  // i get that error.

I already defined the key but it is not solved...no matter what I did it didn't work thanks for the help.I want one to one relation.

When I establish a many-to-many or many-to-one relationship, it does not give an error, but I also get this error in a one-to-one relationship.

using test.entity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Context context = new Context();
            context.Database.Create();
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test.entity
{
    public class ProductMainInfo
    {
        [Key]
        public int Id { get; set; }

        public virtual Category Category { get; set; }

        [ForeignKey("Category")]
        public int CategoryId { get;set;}
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test.entity
{
    public class Category
    {
        [Key]
        public int id{get;set;}
        public string name{get;set;}
        public virtual ProductMainInfo ProductMainInfo { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test.entity
{
    public class Context:DbContext
    {
        public DbSet<Category> Categories { get; set; }
        public DbSet<ProductMainInfo> ProductMainInfos { get; set; }
    }
}


问:
Building a project in Intellij Community works but with Maven doesn't
It sounds strange, I know. But when I am executing a mvn clean install on a java reactive project, it failed. The logs indicated that execution on a reactive test method was completed and as in its Test you wrote AssertNotComplete then a error emerges.

I changed from AssertNotComplete to AssertComplete in that test and at the end triggered an error (an opposite), indicated that the reactive test method was not Completed.
But when I executed clean install on Intellij It's Successfully Build. Some clues?

Thanks in advance.

```<code>[ERROR] Tests run: 8, Failures: 1, Errors: 0, Skipped: 2, Time elapsed: 0.969 s <<< FAILURE! - in com.banknational.zeus.services.channel.providedservicepayment.util.CardUtilsTest
[ERROR] com.banknational.zeus.services.channel.providedservicepayment.util.CardUtilsTest.test_ListProducts_Different_FamilyCode_OK  Time elapsed: 0.055 s  <<< FAILURE!
java.lang.AssertionError: Completed! (latch = 0, values = 1, errors = 0, completions = 1)
        at com.banknational.zeus.services.channel.providedservicepayment.util.CardUtilsTest.test_ListProducts_Different_FamilyCode_OK(CardUtilsTest.java:137)
</code>```

I have changed the line in the file where the logs showed error but it didn't worked.
I restart my Intellij, free cache, I suspected that It probably did not work well. But at the end I did not find an error.

Body:
It sounds strange, I know. But when I am executing a mvn clean install on a java reactive project, it failed. The logs indicated that execution on a reactive test method was completed and as in its Test you wrote AssertNotComplete then a error emerges.

I changed from AssertNotComplete to AssertComplete in that test and at the end triggered an error (an opposite), indicated that the reactive test method was not Completed.
But when I executed clean install on Intellij It's Successfully Build. Some clues?

Thanks in advance.

[ERROR] Tests run: 8, Failures: 1, Errors: 0, Skipped: 2, Time elapsed: 0.969 s <<< FAILURE! - in com.banknational.zeus.services.channel.providedservicepayment.util.CardUtilsTest
[ERROR] com.banknational.zeus.services.channel.providedservicepayment.util.CardUtilsTest.test_ListProducts_Different_FamilyCode_OK  Time elapsed: 0.055 s  <<< FAILURE!
java.lang.AssertionError: Completed! (latch = 0, values = 1, errors = 0, completions = 1)
        at com.banknational.zeus.services.channel.providedservicepayment.util.CardUtilsTest.test_ListProducts_Different_FamilyCode_OK(CardUtilsTest.java:137)

I have changed the line in the file where the logs showed error but it didn't worked.
I restart my Intellij, free cache, I suspected that It probably did not work well. But at the end I did not find an error.


问:
Running Long Tasks via NodeJS + Prisma always loses connection? (ConnectorError)
I am a bit lost. I have a really time-intensive mysql insert to perform via prisma. Right now, I am using the t3 stack (nextjs + prisma + mysql on planetscale). Now this very long task always times out, everytime I try to execute it:

await prisma.megaItem.create( Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind:
QueryError(Server(ServerError { code: 1105, message: "vttablet: rpc
error: code = Aborted desc = transaction 1671642640521425196: in use:
in use: for tx killer rollback (CallerID: ny8ion72xu651v6m0unq)",
state: "HY000" })) })

I tried to move it out of my serverless functions and put it on its own nodejs server. But the same happens in there? I am not sure how I can keep this very long task running.

In my serverless function, I call my nodejs server:

await axios.post('http://localhost:3333', {
        items
      })
```
<p>In nodejs with express, I want to run the actual task:</p>
<pre class="lang-js prettyprint-override"><code>app.post('/', async (req, res) => {
    //first, i loop through the items and put them into the right format, to do a prisma insert
    let prismaItems = await Promise.all(items.map(async (item, i) => {

        let bla = await Promise.all(innerItem.bla.map(async innerItem => {
    //...

    //then, at some point, after I have this mega-query together, i want to put it all into prisma:
        await prisma.megaItem.create({
        data: {
            title: "My title",
            sentences: {
                create: [
                    ...prismaItems
                ]
            }

        },
    });
</code>```

All of this works when I put in not-so-much data, but if I put a lot, it will break.

Is there a way for my to NOT await the response of the server via async/await or to have the server do its thing for multiple minutes, without the frontend waiting for a response? The problem seems to be that after a seconds of running, the connection is lost or broken up and the task cannot complete.

Body:
I am a bit lost. I have a really time-intensive mysql insert to perform via prisma. Right now, I am using the t3 stack (nextjs + prisma + mysql on planetscale). Now this very long task always times out, everytime I try to execute it:

await prisma.megaItem.create( Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind:
QueryError(Server(ServerError { code: 1105, message: "vttablet: rpc
error: code = Aborted desc = transaction 1671642640521425196: in use:
in use: for tx killer rollback (CallerID: ny8ion72xu651v6m0unq)",
state: "HY000" })) })

I tried to move it out of my serverless functions and put it on its own nodejs server. But the same happens in there? I am not sure how I can keep this very long task running.

In my serverless function, I call my nodejs server:

await axios.post('http://localhost:3333', {
        items
      })

In nodejs with express, I want to run the actual task:

app.post('/', async (req, res) => {
    //first, i loop through the items and put them into the right format, to do a prisma insert
    let prismaItems = await Promise.all(items.map(async (item, i) => {

        let bla = await Promise.all(innerItem.bla.map(async innerItem => {
    //...

    //then, at some point, after I have this mega-query together, i want to put it all into prisma:
        await prisma.megaItem.create({
        data: {
            title: "My title",
            sentences: {
                create: [
                    ...prismaItems
                ]
            }

        },
    });

All of this works when I put in not-so-much data, but if I put a lot, it will break.

Is there a way for my to NOT await the response of the server via async/await or to have the server do its thing for multiple minutes, without the frontend waiting for a response? The problem seems to be that after a seconds of running, the connection is lost or broken up and the task cannot complete.


问:
How to upload pdf / Xls / docx to Firebase in android Studio?
I want to upload any type of document to the Firebase.
Also, we have to fetch the document from the local storage.
Can anyone tell how to achieve this?
I tried using StartActivityForResult() but it is deprecated and does not help at all.</p>


问:
Java SpringFramework HTTPRequest unicode character problem
I'm trying to get the content of an online page through SpringFramework using this procedure

```<code>public <T>HttpReply<T> httpRequest(final String uri, final HttpMethod method,
            final Class<T> expectedReturnType, final List<HttpMessageConverter<?>> messageConverters,
            final HashMap<String, Object> formValues, final HashMap<String, Object> headers)
                    throws HttpNullUriOrMethodException, HttpInvocationException {
        try {

            redirectInfo.set(new AbstractMap.SimpleEntry<String, String>(uri, ""));

            if (method==null) {
                throw new HttpNullUriOrMethodException("HttpMethod cannot be null.");
            }

            if (!StringUtils.hasText(uri)) {
                throw new HttpNullUriOrMethodException("URI cannot be null or empty.");
            }

            HttpRequestExecutingMessageHandler handler =
                    buildMessageHandler(uri, method, expectedReturnType, messageConverters);

            // Default queue for reply
            QueueChannel replyChannel = new QueueChannel();
            handler.setOutputChannel(replyChannel);

            // Exec Http Request
            Message<?> message = buildMessage(formValues, headers);
            try {
                handler.handleMessage(message);
            }
            catch (Exception e) {
                throw new HttpInvocationException("Error Handling HTTP Message.");
            }

            // Get Response
            Message<?> response = replyChannel.receive();
            if (response == null) {
                throw new HttpInvocationException("Error: communication is interrupted.");
            }

            // Read response Headers
            String[] usefulHeaders = readUsefulHeaders(response.getHeaders());

            // Return payload
            Object respObj = response.getPayload();

            if (expectedReturnType != null && !expectedReturnType.isInstance(respObj)) {
                throw new HttpInvocationException("Error: response payload is instance of "
                         + respObj.getClass().getName() + ". Expected: " + expectedReturnType.getClass().getName());
            }

            HttpReply<T> retVal = new HttpReply<>();
            retVal.setPayload((T)respObj);

            String valRedirect = uri;
            if (redirectInfo.get().getKey().equals(uri)) {
                if (StringUtils.hasText(redirectInfo.get().getValue())) {
                    valRedirect = redirectInfo.get().getValue();
                }
            }
            else {
                throw new HttpInvocationException("ERROR READING REDIRECT INFORMATION!!! Original URI: "
                        + uri + " - FOUND URI: " + redirectInfo.get().getKey());
            }
            retVal.setActualLocation(valRedirect);
            return retVal;
        }
        finally {
            redirectInfo.remove();
        }
    }
</code>```

which gets called like this

```<code>HttpReply<byte[]> feedContent = httpUtil.httpRequest(rssFeed.getUrl(), HttpMethod.GET, byte[].class, null,
                null, null);

rawXml = new String(feedContent.getPayload());
</code>```

Now, this procedure works fine, except that sometimes rawXml contains �, especially when reading from page with a charset different from UTF8.

I tried to put into the handler.setCharset(StandardCharsets.ISO_8859_1), or to change the message header so that it would contain "contentType=application/xml; charset=ISO-8859-1"

I also tried to convert the text once inside rawXml but sometimes the message is neither UTF-8 nor ISO-8859-1 and so the conversion just doesn't correct the missing characters.

Body:
I'm trying to get the content of an online page through SpringFramework using this procedure

public <T>HttpReply<T> httpRequest(final String uri, final HttpMethod method,
            final Class<T> expectedReturnType, final List<HttpMessageConverter<?>> messageConverters,
            final HashMap<String, Object> formValues, final HashMap<String, Object> headers)
                    throws HttpNullUriOrMethodException, HttpInvocationException {
        try {

            redirectInfo.set(new AbstractMap.SimpleEntry<String, String>(uri, ""));

            if (method==null) {
                throw new HttpNullUriOrMethodException("HttpMethod cannot be null.");
            }

            if (!StringUtils.hasText(uri)) {
                throw new HttpNullUriOrMethodException("URI cannot be null or empty.");
            }

            HttpRequestExecutingMessageHandler handler =
                    buildMessageHandler(uri, method, expectedReturnType, messageConverters);

            // Default queue for reply
            QueueChannel replyChannel = new QueueChannel();
            handler.setOutputChannel(replyChannel);

            // Exec Http Request
            Message<?> message = buildMessage(formValues, headers);
            try {
                handler.handleMessage(message);
            }
            catch (Exception e) {
                throw new HttpInvocationException("Error Handling HTTP Message.");
            }

            // Get Response
            Message<?> response = replyChannel.receive();
            if (response == null) {
                throw new HttpInvocationException("Error: communication is interrupted.");
            }

            // Read response Headers
            String[] usefulHeaders = readUsefulHeaders(response.getHeaders());

            // Return payload
            Object respObj = response.getPayload();

            if (expectedReturnType != null && !expectedReturnType.isInstance(respObj)) {
                throw new HttpInvocationException("Error: response payload is instance of "
                         + respObj.getClass().getName() + ". Expected: " + expectedReturnType.getClass().getName());
            }

            HttpReply<T> retVal = new HttpReply<>();
            retVal.setPayload((T)respObj);

            String valRedirect = uri;
            if (redirectInfo.get().getKey().equals(uri)) {
                if (StringUtils.hasText(redirectInfo.get().getValue())) {
                    valRedirect = redirectInfo.get().getValue();
                }
            }
            else {
                throw new HttpInvocationException("ERROR READING REDIRECT INFORMATION!!! Original URI: "
                        + uri + " - FOUND URI: " + redirectInfo.get().getKey());
            }
            retVal.setActualLocation(valRedirect);
            return retVal;
        }
        finally {
            redirectInfo.remove();
        }
    }

which gets called like this

HttpReply<byte[]> feedContent = httpUtil.httpRequest(rssFeed.getUrl(), HttpMethod.GET, byte[].class, null,
                null, null);

rawXml = new String(feedContent.getPayload());

Now, this procedure works fine, except that sometimes rawXml contains �, especially when reading from page with a charset different from UTF8.

I tried to put into the handler.setCharset(StandardCharsets.ISO_8859_1), or to change the message header so that it would contain "contentType=application/xml; charset=ISO-8859-1"

I also tried to convert the text once inside rawXml but sometimes the message is neither UTF-8 nor ISO-8859-1 and so the conversion just doesn't correct the missing characters.


问:
Flask MongoDB - prevent multiple concurrent calls to an endpoint by the same user
We have a Flask + MongoDB web application based on MongoEngine. We are trying to enforce a user-level limit in a thread safe manner, meaning we need to prevent multiple concurrent calls to an endpoint by the same user.

Looking at older threads and MongoEngine reference, we came up with this solutions. Relevant threads we found: It's not possible to lock a mongodb document. What if I need to?
https://www.mongodb.com/community/forums/t/locking-documents-in-mongo/6865/2

Our solution is based on a boolean field in the user document which is used as a mutex. The lock field is set to True with an atomic modify, operations are performed by the endpoint and then the lock is released (False).

To enforce this we have a lock attribute in the User model:

```<code>User
  - ...
  - plans
      - execution_plan
          - ...
          - lock (bool)
</code>```

The following code decorates the endpoint.

def execution_plans_decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user: User = User.objects.get(_id=get_jwt_identity())
        execution_plan = user.plans.execution_plan

        timeout = time.time() + current_app.config['PLAN_LOCK_TIMEOUT']
        modified = False
        while time.time() < timeout:
            # acquire lock with an atomic query
            modified = user.modify(
                query={f'plans__execution_plan__lock': False},
                **{f'set__plans__execution_plan__lock': True}
            )
            if modified:
                logger.info(f'lock acquired for execution_plan')
                break
            time.sleep(0.5)
        if not modified:
            logger.info(f'could not acquire lock for execution_plan')
            return jsonify({'msg': 'Too many concurrent requests'}), 429

        # if a condition is not met, block the endpoint
        if not condition:
            execution_plan.lock = False
            user.save()
            return jsonify({
                'msg': f'Max number of executions reached. Upgrade execution plan'
            }), 402

        # execute the decorated function
        try:
            rv = f(*args, **kwargs)
        except Exception:
            # re-raise exception
            raise
        finally:
            # always release lock
            execution_plan.lock = False
            user.save()
        return rv

    return decorated_function
```

We believe the code is formally correct and proved to work without any issue.
However, on rare occasions in production (once every ~10.000 requests), the lock is not released and is marked as true.
This locks all subsequent requests to the endpoint for a particular user, requiring manual intervention.

Body:
We have a Flask + MongoDB web application based on MongoEngine. We are trying to enforce a user-level limit in a thread safe manner, meaning we need to prevent multiple concurrent calls to an endpoint by the same user.

Looking at older threads and MongoEngine reference, we came up with this solutions. Relevant threads we found: It's not possible to lock a mongodb document. What if I need to?
https://www.mongodb.com/community/forums/t/locking-documents-in-mongo/6865/2

Our solution is based on a boolean field in the user document which is used as a mutex. The lock field is set to True with an atomic modify, operations are performed by the endpoint and then the lock is released (False).

To enforce this we have a lock attribute in the User model:

User
  - ...
  - plans
      - execution_plan
          - ...
          - lock (bool)

The following code decorates the endpoint.

def execution_plans_decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user: User = User.objects.get(_id=get_jwt_identity())
        execution_plan = user.plans.execution_plan

        timeout = time.time() + current_app.config['PLAN_LOCK_TIMEOUT']
        modified = False
        while time.time() < timeout:
            # acquire lock with an atomic query
            modified = user.modify(
                query={f'plans__execution_plan__lock': False},
                **{f'set__plans__execution_plan__lock': True}
            )
            if modified:
                logger.info(f'lock acquired for execution_plan')
                break
            time.sleep(0.5)
        if not modified:
            logger.info(f'could not acquire lock for execution_plan')
            return jsonify({'msg': 'Too many concurrent requests'}), 429

        # if a condition is not met, block the endpoint
        if not condition:
            execution_plan.lock = False
            user.save()
            return jsonify({
                'msg': f'Max number of executions reached. Upgrade execution plan'
            }), 402

        # execute the decorated function
        try:
            rv = f(*args, **kwargs)
        except Exception:
            # re-raise exception
            raise
        finally:
            # always release lock
            execution_plan.lock = False
            user.save()
        return rv

    return decorated_function

We believe the code is formally correct and proved to work without any issue.
However, on rare occasions in production (once every ~10.000 requests), the lock is not released and is marked as true.
This locks all subsequent requests to the endpoint for a particular user, requiring manual intervention.


问:
Why does the number of bytes in this buffer change from the original size when dealing with images?
So i'm looking at some image resizing code in our code base, and i've noticed that after passing an image through PIL the number of bytes of the image increases by just under 2x.

I've gutted most of the code out for the purpose of this demonstration just so I could isolate the case:

```<code>import io
from PIL import Image
from django.core.files.base import ContentFile

def size_test(content_file: ContentFile):
    with content_file.open("rb") as file:
        file_bytes = file.read()
        print("original size of bytes: %s" % len(file_bytes))

        image = Image.open(io.BytesIO(file_bytes), formats=["JPEG"])

        with io.BytesIO() as buffer:
            image.save(buffer, format="JPEG")
            buffer_bytes = buffer.getvalue()

        print("new size of bytes: %s" % len(buffer_bytes))
</code>```

Calling the above with the following code, loading in a JPEG file of known size:

```<code>with open('10mb.jpg', 'rb') as file:
    cf = ContentFile(file.read())

utils.size_test(cf)
</code>```

Here is the output:

```<code>original size of bytes: 10174706
new size of bytes: 19538695
</code>```

Maybe i'm missing something glaringly obvious, but i'm not sure what makes this image's bytes increase by 9MB in memory, unless it's to do with JPEG compression? Maybe by loading the JPEG into memory we are uncompressing it?

Just tried this with a 1.7MB PNG file (changing the relevant formats in the original function):

```<code>def size_test(content_file: ContentFile):
    with content_file.open("rb") as file:
        # load into Image object
        file_bytes = file.read()
        print("original size of bytes: %s" % len(file_bytes))
        image = Image.open(io.BytesIO(file_bytes), formats=["PNG"])
        with io.BytesIO() as buffer:
            image.save(buffer, format="PNG")
            data = buffer.getvalue()
        print("new size of bytes: %s" % len(data))
</code>```

The opposite occurs:

```<code>original size of bytes: 1701968
new size of bytes: 1331325
</code>```

What is going on here?

Body:
So i'm looking at some image resizing code in our code base, and i've noticed that after passing an image through PIL the number of bytes of the image increases by just under 2x.

I've gutted most of the code out for the purpose of this demonstration just so I could isolate the case:

import io
from PIL import Image
from django.core.files.base import ContentFile

def size_test(content_file: ContentFile):
    with content_file.open("rb") as file:
        file_bytes = file.read()
        print("original size of bytes: %s" % len(file_bytes))

        image = Image.open(io.BytesIO(file_bytes), formats=["JPEG"])

        with io.BytesIO() as buffer:
            image.save(buffer, format="JPEG")
            buffer_bytes = buffer.getvalue()

        print("new size of bytes: %s" % len(buffer_bytes))

Calling the above with the following code, loading in a JPEG file of known size:

with open('10mb.jpg', 'rb') as file:
    cf = ContentFile(file.read())

utils.size_test(cf)

Here is the output:

original size of bytes: 10174706
new size of bytes: 19538695

Maybe i'm missing something glaringly obvious, but i'm not sure what makes this image's bytes increase by 9MB in memory, unless it's to do with JPEG compression? Maybe by loading the JPEG into memory we are uncompressing it?

Just tried this with a 1.7MB PNG file (changing the relevant formats in the original function):

def size_test(content_file: ContentFile):
    with content_file.open("rb") as file:
        # load into Image object
        file_bytes = file.read()
        print("original size of bytes: %s" % len(file_bytes))
        image = Image.open(io.BytesIO(file_bytes), formats=["PNG"])
        with io.BytesIO() as buffer:
            image.save(buffer, format="PNG")
            data = buffer.getvalue()
        print("new size of bytes: %s" % len(data))

The opposite occurs:

original size of bytes: 1701968
new size of bytes: 1331325

What is going on here?