问:
Swift double to string
Before I updated xCode 6, I had no problems casting a double to a string but now it gives me an error

```<code>var a: Double = 1.5
var b: String = String(a)
</code>```

It gives me the error message "double is not convertible to string". Is there any other way to do it?

答: You shouldn't really ever cast a double to a string, the most common reason for casting a float to a string is to present it to a user, but floats are not real number and can only approximate lots of values, similar to how ⅓ can not be represented as a decimal number with a finite number of decimal places. Instead keep you values as float for all their use, then when you want to present them to the user, use something like NumberFormater to convert them for your. This stage of converting for user presentation is what something like your viewModel should do.</p>

Title: Swift double to string

Body:
Before I updated xCode 6, I had no problems casting a double to a string but now it gives me an error

var a: Double = 1.5
var b: String = String(a)

It gives me the error message "double is not convertible to string". Is there any other way to do it?


来源: stackexchange

问:
Navbar overshadows/overlaps the content of a page
So I am learning HTMl/css and I came across this issue:

Wide screen; nav bar covers the content

Smaller screen; nav bar covers the content even more

Here is some sampple code to reproduce this problem:

```<code><!DOCTYPE html>
<html>
<head>
<style>
body {margin:0;}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}
</style>
</head>
<body>

<ul>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

<div style="padding:20px;margin-top:30px;background-color:#1abc9c;height:1500px;">
  <h1>Fixed Top Navigation Bar</h1>
  <h2>Scroll this page to see the effect</h2>
  <h2>The navigation bar will stay at the top of the page while scrolling</h2>

  <p>Some text some text some text some text..</p>
</div>

</body>
</html>
</code>```

My question is, does anyone know how to make everything underneath the nav bar, go UNDER the nav bar? So that the nav bar wont cover the contents?

Thanks in advance!

答: Simply create Fixed size of navbar and add same size of padding-top property to parent div.

ContentLicense: CC BY-SA 4.0

Body:
So I am learning HTMl/css and I came across this issue:

Wide screen; nav bar covers the content

Smaller screen; nav bar covers the content even more

Here is some sampple code to reproduce this problem:

<!DOCTYPE html>

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Fixed Top Navigation Bar

Scroll this page to see the effect

The navigation bar will stay at the top of the page while scrolling

Some text some text some text some text..

My question is, does anyone know how to make everything underneath the nav bar, go UNDER the nav bar? So that the nav bar wont cover the contents?

Thanks in advance!


问:
How do I get all permutations in KDB?
Say I want to get:

```<code>0 0
0 1
0 2
1 0
1 1
1 2
etc
</code>```

I'm to do (til 3) (,\:) til 3 but this doesn't seem to do it, giving me a type error.

What am I doing wrong?

答:
cross keyword is what you are looking for

```<code>q)(til 3) cross til 3
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
</code>```

The solution to your original problem without using a keyword is:

```<code>q)raze ((til 3),/:\:) til 3
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
</code>```

Title: How do I get all permutations in KDB?

Body:
Say I want to get:

0 0
0 1
0 2
1 0
1 1
1 2
etc

I'm to do (til 3) (,\:) til 3 but this doesn't seem to do it, giving me a type error.

What am I doing wrong?

Body:
cross keyword is what you are looking for

q)(til 3) cross til 3
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

The solution to your original problem without using a keyword is:

q)raze ((til 3),/:\:) til 3
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2


答:
Simply, just use position: sticky instead of position: fixed:

ul {
  position: sticky;
}
```

sticky allows you to "stick" a container on the window rather than the document (like what fixed does). Therefore, it doesn't float over the document and cover other content.

Title: Navbar overshadows/overlaps the content of a page

Body:
Simply, just use position: sticky instead of position: fixed:

ul {
  position: sticky;
}

sticky allows you to "stick" a container on the window rather than the document (like what fixed does). Therefore, it doesn't float over the document and cover other content.


问:
How to get and set Textfield value in flutter
Sample Data

data

```<code>data1
data2
data3
    data_detail
    data_detail1
        score - > textfield
</code>```

tabel data, how do i do set or get data on scrore, i use textfield.
is it possible to use controller?

Structure Example

Listview.builder(
    itemCount : anything.length
    itemBuilder:(context, index){

    Listview.Builder(
    itemCount : anything[data][index][data_detail].length
    itemBuilder:(context, index2){

        Textfield (
        controller : ??
        )

        }
    )
}
)```

with a structure like that I'm quite confused about the use of controllers in textfields, is it possible to use a list controller with such a structure?

答:
Yes, you can use TextEditingController for this.

First, define a TextEditingController:

```<code>final TextEditingController txtController = TextEditingController();
</code>```

To get the value from a TextField use txtController.text and to set the value use txtController.text = 'new value'

Body:
Sample Data

data

data1
data2
data3
    data_detail
    data_detail1
        score - > textfield

tabel data, how do i do set or get data on scrore, i use textfield.
is it possible to use controller?

Structure Example

Listview.builder(
    itemCount : anything.length
    itemBuilder:(context, index){

    Listview.Builder(
    itemCount : anything[data][index][data_detail].length
    itemBuilder:(context, index2){

        Textfield (
        controller : ??
        )

        }
    )
}
)

with a structure like that I'm quite confused about the use of controllers in textfields, is it possible to use a list controller with such a structure?

Body:
Yes, you can use TextEditingController for this.

First, define a TextEditingController:

final TextEditingController txtController = TextEditingController();

To get the value from a TextField use txtController.text and to set the value use txtController.text = 'new value'


问:
How to override CSS styles of Bootstrap for ".navlink"?
I'm not able to change the color of the ".navlink" to white in my html file.
Please help me to change the color of the ".navlink" to white.

       tent workshop
       <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

       </button>

                   Home

                   Contact

                   Products

```

答:
You should always use the selectors that Bootstrap uses to be able to override the color defined by bootstrap. Also, your CSS must be included after Bootstrap.

.navbar-nav .nav-link {
  color: #ffffff;
}

.navbar-nav .nav-link:focus,
.navbar-nav .nav-link:hover {
  color: #ffffff;
}```
</div>
</div>
</p>
<p>OR you override the CSS from Bootstrap by using "!important"</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-link {
  color: #ffffff!important;
}

.nav-link:focus,
.nav-link:hover {
  color: #ffffff!important;
}</code>```

Body:
You should always use the selectors that Bootstrap uses to be able to override the color defined by bootstrap. Also, your CSS must be included after Bootstrap.

.navbar-nav .nav-link {
  color: #ffffff;
}

.navbar-nav .nav-link:focus,
.navbar-nav .nav-link:hover {
  color: #ffffff;
}

OR you override the CSS from Bootstrap by using "!important"

.nav-link {
  color: #ffffff!important;
}

.nav-link:focus,
.nav-link:hover {
  color: #ffffff!important;
}


问:
How to hide ios app IP address from third party servers?
My ios app retrieves some data from third party servers during runetime.
For privacy reasons, I want to hide the IP addresses of my users, in order to prevent those servers to know them. How can I do that ?

My idea is to set up a kind of "proxy server" or "VPN server" inbetween the app and the third party servers. Is that a good idea ?

Thanks for your help!

答:
Yes, proxying is the right way to do this. You could do it with a VPN, but that's overkill, and requires considerable setup on the client side which you don't control.

You can get a web server such as Nginx or Apache to act as a proxy directly through config options, or you can do it via scripting with PHP or whatever. I do the latter to provide a proxied service to gravatar.com. The principle is quite straightforward:

Accept a request from your client.

On your server side, make a request (using an HTTP library, such as Guzzle) to the 3rd party service to get whatever is needed.

Parse the response from there and create a response suitable for your client.

This way the 3rd party service will only ever see the IP of your server, not your client, and you can choose exactly what data from the client you pass through. In my gravatar example, it sends an MD5 hash of the user's email address, which has its own privacy implications, but that's a separate problem!


问:
how to get value which is above of function for each
I'm stuck to getting data from this xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<document>
    <AAA>Header</AAA>
    <BBB>
        <CCC>
            <DDD>
                <EEE>123123</EEE>
                <FFF>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>1</III>
                    </GGG>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>3</III>
                    </GGG>
                </FFF>
            </DDD>
        </CCC>
        <CCC>
            <DDD>
                <EEE>234234</EEE>
                <FFF>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>2</III>
                    </GGG>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>4</III>
                    </GGG>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>6</III>
                    </GGG>
                </FFF>
            </DDD>
        </CCC>
        <CCC>
            <DDD>
                <EEE>345345</EEE>
                <FFF>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>7</III>
                    </GGG>
                </FFF>
            </DDD>
        </CCC>
    </BBB>
</document>
</code>```

Needed result should be:

```<code>Header;
Body;1;123123
Body;3;123123
Body;2;234234
Body;4;234234
Body;6;234234
Body;7;345345
</code>```

My xslt looks:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="text" encoding="Windows-1257" indent="yes"/>

<xsl:template match="/">
        <!--Start Header--><xsl:value-of select="document/AAA"/><xsl:text>;</xsl:text>
        <!--End Header--><xsl:text>
</xsl:text>
        <xsl:for-each select="document/BBB/CCC/DDD/FFF/GGG">
            <!--Start Body--><xsl:value-of select="HHH"/><xsl:text>;</xsl:text>
            <xsl:value-of select="III"/><xsl:text>;</xsl:text>
            <xsl:value-of select="../EEE"/><--This doesn't work-->
            <!--End Body--><xsl:text>
</xsl:text>
        </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

now I have problem to get value from EEE tag. Please help to solve it because I have no idea how to do it.

答:
From your for-each statement the current context that you are working at is document/BBB/CCC/DDD/FFF/GGG.

The full path of the EEE statement is document/BBB/CCC/DDD/EEE.

Therefore you need to come back two levels to reach the EEE node from the GGG node:

```<code><xsl:value-of select="../../EEE"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm stuck to getting data from this xml:

<?xml version="1.0" encoding="UTF-8"?>
<document>
    <AAA>Header</AAA>
    <BBB>
        <CCC>
            <DDD>
                <EEE>123123</EEE>
                <FFF>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>1</III>
                    </GGG>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>3</III>
                    </GGG>
                </FFF>
            </DDD>
        </CCC>
        <CCC>
            <DDD>
                <EEE>234234</EEE>
                <FFF>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>2</III>
                    </GGG>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>4</III>
                    </GGG>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>6</III>
                    </GGG>
                </FFF>
            </DDD>
        </CCC>
        <CCC>
            <DDD>
                <EEE>345345</EEE>
                <FFF>
                    <GGG>
                        <HHH>Body</HHH>
                        <III>7</III>
                    </GGG>
                </FFF>
            </DDD>
        </CCC>
    </BBB>
</document>

Needed result should be:

Header;
Body;1;123123
Body;3;123123
Body;2;234234
Body;4;234234
Body;6;234234
Body;7;345345

My xslt looks:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="text" encoding="Windows-1257" indent="yes"/>

<xsl:template match="/">
        <xsl:value-of select="document/AAA"/><xsl:text>;</xsl:text>
        <xsl:text>
</xsl:text>
        <xsl:for-each select="document/BBB/CCC/DDD/FFF/GGG">
            <xsl:value-of select="HHH"/><xsl:text>;</xsl:text>
            <xsl:value-of select="III"/><xsl:text>;</xsl:text>
            <xsl:value-of select="../EEE"/><--This doesn't work-->
            <xsl:text>
</xsl:text>
        </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

now I have problem to get value from EEE tag. Please help to solve it because I have no idea how to do it.

Body:
From your for-each statement the current context that you are working at is document/BBB/CCC/DDD/FFF/GGG.

The full path of the EEE statement is document/BBB/CCC/DDD/EEE.

Therefore you need to come back two levels to reach the EEE node from the GGG node:

<xsl:value-of select="../../EEE"/>


问:
Regex to exclude sub directory
I'm going an automatic global registration. I'm struggling to figure how to exclude a specific sub directory. How would a regex for that look? I'm sorry to not have an example of a try but I have no idea honestly. Searching I found a few examples but it never matches to exclude just a directory.

This is how I get the components now.

```<code>const registerComponents = () => {
  const pascalCase = (name: string) => {
    return _.chain(name).camelCase().upperFirst().value()
  }

  const context = require.context('@/components', true, /\w+\.(vue)$/)
  _.forEach(context.keys(), fileName => {
    const componentConfig = context(fileName)

    const name = (fileName.split('/').pop() || '').replace(/\.\w+$/, '')
    const componentName = pascalCase(name)

    Vue.component(componentName, componentConfig.default || componentConfig)
  })
}
</code>```

This is the structure. I would like to exclude the folder /_exclude/

```<code>components/_exclude/file.vue
components/_exclude/file2.vue
components/_exclude/svg/globe.vue
components/some-file.vue
components/svg/cart.vue
</code>```

答:
This pattern would match all .vue files except those in _exclude/:

```<code>/^\.\/(?!_exclude\/).*\.vue$/
</code>```

Breakdown of the pattern:

^\.\/

Match the leading ./ in the file paths returned from require.context().

(?!_exclude\/)

Using negative look-ahead, assert _exclude/ does not match.

.*

Match any character(s). Note the \w+ from your original pattern would have failed on file separators in the file paths.

\.vue$

Match the .vue file extension. Note the parentheses in (vue) from your original pattern would have created an unecessary capture group.

Title: Regex to exclude sub directory

Body:
I'm going an automatic global registration. I'm struggling to figure how to exclude a specific sub directory. How would a regex for that look? I'm sorry to not have an example of a try but I have no idea honestly. Searching I found a few examples but it never matches to exclude just a directory.

This is how I get the components now.

const registerComponents = () => {
  const pascalCase = (name: string) => {
    return _.chain(name).camelCase().upperFirst().value()
  }

  const context = require.context('@/components', true, /\w+\.(vue)$/)
  _.forEach(context.keys(), fileName => {
    const componentConfig = context(fileName)

    const name = (fileName.split('/').pop() || '').replace(/\.\w+$/, '')
    const componentName = pascalCase(name)

    Vue.component(componentName, componentConfig.default || componentConfig)
  })
}

This is the structure. I would like to exclude the folder /_exclude/

components/_exclude/file.vue
components/_exclude/file2.vue
components/_exclude/svg/globe.vue
components/some-file.vue
components/svg/cart.vue

Body:
This pattern would match all .vue files except those in _exclude/:

/^\.\/(?!_exclude\/).*\.vue$/

Breakdown of the pattern:

^\.\/

Match the leading ./ in the file paths returned from require.context().

(?!_exclude\/)

Using negative look-ahead, assert _exclude/ does not match.

.*

Match any character(s). Note the \w+ from your original pattern would have failed on file separators in the file paths.

\.vue$

Match the .vue file extension. Note the parentheses in (vue) from your original pattern would have created an unecessary capture group.


问:
How can I add or remove class using react functional component
I am using react typescript. I am trying to add or remove an active class if I click any list item but the code is sometimes not working. So I want to update my code in a better way. can anyone help me to improve update my below function code?

Here is my function which I want to update

```<code>   const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(e: any) {
        list.forEach((item) => item.classList.remove('active'))
        e.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', (e) => activeLink(item)))
</code>```

Full code with HTML

```<code>

export default function MobileNavigation() {
    const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(this: any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        this.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', activeLink))

    return <div className='mobile-navigation'>
        <ul>
            <li className='m-list active'>
                <a href="#">
                    <span className='m-icon'><i className="fa-solid fa-house"></i></span>
                    <span className='m-text'>Home</span>
                </a>
            </li>
            <li className='m-list'>
                <a href="#">
                    <span className='m-icon'><i className="fa-solid fa-shop"></i></span>
                    <span className='m-text'>Shop</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-store"></i></span>
                    <span className='m-text'>Vendors</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-address-card"></i></span>
                    <span className='m-text'>About us</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-headset"></i></span>
                    <span className='m-text'>Contact Us</span></a>
            </li>
            <div className="indicator"></div>
        </ul>
    </div>;
}

</code>```

答: Your code is pure VanillaJS, not Typescript or React. Try to read something about Typescript AND React, make example project and try - https://medium.com/codex/typescript-and-create-react-app-11bdebcbf763</p>

Body:
I am using react typescript. I am trying to add or remove an active class if I click any list item but the code is sometimes not working. So I want to update my code in a better way. can anyone help me to improve update my below function code?

Here is my function which I want to update

   const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(e: any) {
        list.forEach((item) => item.classList.remove('active'))
        e.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', (e) => activeLink(item)))

Full code with HTML

export default function MobileNavigation() {
    const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(this: any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        this.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', activeLink))

    return

                    Home

                    Shop

                    Vendors

                    About us

                    Contact Us

;
}


问:
Why does my code return "Unexpected token ="?
I am working on Discord.TS bot but when I launch it with ts-node src/index.ts, I see the error

```<code>/home/negative/Dev/JS/Bot/src/structures/Client.ts:10
    commands = new discord_js_1.Collection();
             ^

SyntaxError: Unexpected token =
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Module.m._compile (/home/negative/Dev/JS
...
</code>```

Here is my code (Client.ts)

import {
    ApplicationCommandDataResolvable,
    Client,
    ClientEvents,
    Collection
} from "discord.js";
import { CommandType } from "../typings/Command";
import glob from "glob";
import { promisify } from "util";
import { RegisterCommandsOptions } from "../typings/client";
import { Event } from "./Event";

const globPromise = promisify(glob);
export class ExtendedClient extends Client {
    commands: Collection<string, CommandType> = new Collection();

    constructor() {
        super({ intents: 32767 });
    }

    start() {
        this.registerModules();
        this.login(process.env.botToken);
    }
    async importFile(filePath: string) {
        return (await import(filePath))?.default;
    }

    async registerCommands({ commands, guildId }: RegisterCommandsOptions) {
        if (guildId) {
            this.guilds.cache.get(guildId)?.commands.set(commands);
            console.log(`Registering commands to ${guildId}`);
        } else {
            this.application?.commands.set(commands);
            console.log("Registering global commands");
        }
    }

    async registerModules() {
        // Commands
        const slashCommands: ApplicationCommandDataResolvable[] = [];
        const commandFiles = await globPromise(
            `${__dirname}/../commands/*/*{.ts,.js}`
        );
        commandFiles.forEach(async (filePath) => {
            const command: CommandType = await this.importFile(filePath);
            if (!command.name) return;
            console.log(command);

            this.commands.set(command.name, command);
            slashCommands.push(command);
        });

        this.on("ready", () => {
            this.registerCommands({
                commands: slashCommands,
                guildId: process.env.guildId
            });
        });

        // Event
        const eventFiles = await globPromise(
            `${__dirname}/../events/*{.ts,.js}`
        );
        eventFiles.forEach(async (filePath) => {
            const event: Event<keyof ClientEvents> = await this.importFile(
                filePath
            );
            this.on(event.event, event.run);
        });
    }
}
```

The Visual Studio Code says that my code has no errors, but I can not fix this one. Can someone please tell me how to fix it? I have been working on this problem...
If you know  how to fix this, please tell, I will be really please to you.

答:
This error is because you are targeting a JavaScript version that isn't supported by your installed Node.js version. You can either change the JavaScript version you are targeting, or update your Node.js version.

Option 1: Updating Node.js Version

Make sure you have installed at least Node.js version 16.11.0 (according to node.green this is the first version to fully support instance class fields).

You can check your node version by typing node -v in your terminal.

```<code>$ node -v
v17.1.0
</code>```

You can then install the latest Node.js version from their website: https://nodejs.org/

Option 2: Changing Target JavaScript Version

Open your tsconfig.json file and change the target field to a version that is supported by your current Node.js version.

You can check your node version by typing node -v in your terminal.

```<code>$ node -v
v17.1.0
</code>```

Consult node.green to determine what JavaScript version you can target based on your current Node.js version.

Body:
I am working on Discord.TS bot but when I launch it with ts-node src/index.ts, I see the error

/home/negative/Dev/JS/Bot/src/structures/Client.ts:10
    commands = new discord_js_1.Collection();
             ^

SyntaxError: Unexpected token =
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Module.m._compile (/home/negative/Dev/JS
...

Here is my code (Client.ts)

import {
    ApplicationCommandDataResolvable,
    Client,
    ClientEvents,
    Collection
} from "discord.js";
import { CommandType } from "../typings/Command";
import glob from "glob";
import { promisify } from "util";
import { RegisterCommandsOptions } from "../typings/client";
import { Event } from "./Event";

const globPromise = promisify(glob);
export class ExtendedClient extends Client {
    commands: Collection<string, CommandType> = new Collection();

    constructor() {
        super({ intents: 32767 });
    }

    start() {
        this.registerModules();
        this.login(process.env.botToken);
    }
    async importFile(filePath: string) {
        return (await import(filePath))?.default;
    }

    async registerCommands({ commands, guildId }: RegisterCommandsOptions) {
        if (guildId) {
            this.guilds.cache.get(guildId)?.commands.set(commands);
            console.log(`Registering commands to ${guildId}`);
        } else {
            this.application?.commands.set(commands);
            console.log("Registering global commands");
        }
    }

    async registerModules() {
        // Commands
        const slashCommands: ApplicationCommandDataResolvable[] = [];
        const commandFiles = await globPromise(
            `${__dirname}/../commands/*/*{.ts,.js}`
        );
        commandFiles.forEach(async (filePath) => {
            const command: CommandType = await this.importFile(filePath);
            if (!command.name) return;
            console.log(command);

            this.commands.set(command.name, command);
            slashCommands.push(command);
        });

        this.on("ready", () => {
            this.registerCommands({
                commands: slashCommands,
                guildId: process.env.guildId
            });
        });

        // Event
        const eventFiles = await globPromise(
            `${__dirname}/../events/*{.ts,.js}`
        );
        eventFiles.forEach(async (filePath) => {
            const event: Event<keyof ClientEvents> = await this.importFile(
                filePath
            );
            this.on(event.event, event.run);
        });
    }
}

The Visual Studio Code says that my code has no errors, but I can not fix this one. Can someone please tell me how to fix it? I have been working on this problem...
If you know  how to fix this, please tell, I will be really please to you.

Body:
This error is because you are targeting a JavaScript version that isn't supported by your installed Node.js version. You can either change the JavaScript version you are targeting, or update your Node.js version.

Option 1: Updating Node.js Version

Make sure you have installed at least Node.js version 16.11.0 (according to node.green this is the first version to fully support instance class fields).

You can check your node version by typing node -v in your terminal.

$ node -v
v17.1.0

You can then install the latest Node.js version from their website: https://nodejs.org/

Option 2: Changing Target JavaScript Version

Open your tsconfig.json file and change the target field to a version that is supported by your current Node.js version.

You can check your node version by typing node -v in your terminal.

$ node -v
v17.1.0

Consult node.green to determine what JavaScript version you can target based on your current Node.js version.


问:
OpenCL crash when Max work group size is used
So I have a problem.

I am writing an application which uses OpenCL and whenever I use the max work group size or anything above half of the max work group size, I get a crash (a black screen).

Does anyone know what the reason might be?

I would love to use to entire work group size, instead of just half.

Thanks in advance

答:
The most likely reason is that you have a global array of a size that, at some point, is not evenly divisible by the workgroup size.

For example a global array of size 1920. Workgroup size 32/64/128 works, then you get 60/30/15 workgroups. But if you choose workgroup size 256 (or larger), you get 7.5 workgroups. What then happens is that 8 workgropus are executed, and the last workgroup covers threads 1792-2047. Yet, the global array ends at tread 1919, so access to array elements 1920-2047 reads from / writes to Nirwana and this can crash the entire program.

There are 2 possible solutions:

Only choose a workgroup size small enough that all global array sizes are divisible by it. Note that workgroup size must be 32 or a multiple of 32.

Alternatively, at the very begin of the Kernel code, use a so-called "guard clause": if(get_global_id(0)>=array_size) return;. This makes the thread end if the there is no corresponding memory address to the thread ID, preventing crashing. With this, you can also use any array size that is not divisible by the workgroup size.


问:
Concept of "auto" keyword in c
Could you please give me the exact concept of the keyword auto in a C program.

When I went through the book Deep C secrets, I saw this quote:

The auto keyword is apparently
useless. It is only meaningful to a
compiler-writer  making an entry in a
symbol table. It says this storage is
automatically allocated on entering
the block (as opposed to global static
allocation, or dynamic allocation on
the heap). Auto is irrelevant to
other programmers, since you get it by
default.

答:
Quote from c-programming-simple-steps.com on c-auto

Practical usage None. Really, there is no reason to use the auto
keyword in C. The only place where we can use it is when we create a
variable within a function but… all variables created there are
already auto.

Why the C auto exists? For backward compatibility. The predecessors of
C used the auto to declare variables. Back in the days there was a lot
of code that had to be ported to the new C language. Adding the
keyword to the language was of help in that case.

Title: Concept of "auto" keyword in c


问:
How to swap 2 button positions in Kotlin programatically by preference?
So, I have 2 buttons and I wanna swap them by using a preference but Yeah, I can't make them switch properly

Here is my code for preference

```<code>    // In MainActivity.kt

    override fun onResume() {
        super.onResume()
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val shouldFlipButtonPosition = sharedPreferences.getBoolean("buttonpositions", false)
        if (isButtonPositionFlipped != shouldFlipButtonPosition) {
            isButtonPositionFlipped = shouldFlipButtonPosition
            val cleanBtn = findViewById<Button>(R.id.cleanBtn)
            val analyzeBtn = findViewById<Button>(R.id.analyzeBtn)
            if (isButtonPositionFlipped) {

                // Buttons swaped.

            } else {

               // Buttons back to normal.

            }
        }
</code>```

I tried again to make them swap but I got some ugly results like this:

```<code>    override fun onResume() {
        super.onResume()
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val shouldFlipButtonPosition = sharedPreferences.getBoolean("buttonpositions", false)
        if (isButtonPositionFlipped != shouldFlipButtonPosition) {
            isButtonPositionFlipped = shouldFlipButtonPosition
            val cleanBtn = findViewById<Button>(R.id.cleanBtn)
            val analyzeBtn = findViewById<Button>(R.id.analyzeBtn)
            if (isButtonPositionFlipped) {
                val posX = cleanBtn.x
                val posY = cleanBtn.y
                analyzeBtn.x = posX
                analyzeBtn.y = posY
            } else {
                cleanBtn.setPadding(0, 0, 0, 0)
                analyzeBtn.setPadding(0, 0, 0, 0)
            }
        }
    }
</code>```
```<code>    override fun onResume() {
        super.onResume()
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val shouldFlipButtonPosition = sharedPreferences.getBoolean("buttonpositions", false)
        if (isButtonPositionFlipped != shouldFlipButtonPosition) {
            isButtonPositionFlipped = shouldFlipButtonPosition
            val cleanBtn = findViewById<Button>(R.id.cleanBtn)
            val analyzeBtn = findViewById<Button>(R.id.analyzeBtn)
            if (isButtonPositionFlipped) {
                cleanBtn.setPadding(640, 0, 0, 0)
                analyzeBtn.setPadding(0, 0, 640, 0)
            } else {
                cleanBtn.setPadding(0, 0, 0, 0)
                analyzeBtn.setPadding(0, 0, 0, 0)
            }
        }
    }
</code>```

I have to mention I tried to use set.Margins but isn't working

How can I swap them by using this method?

答:
Try use RelativeLayout(or ConstraintLayout):</p>
```<code>   override fun onResume() {
        super.onResume()
        val cleanBtn = findViewById<Button>(R.id.cleanBtn);
        val analyzeBtn = findViewById<Button>(R.id.analyzeBtn);
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val shouldFlipButtonPosition = sharedPreferences.getBoolean("buttonpositions", false)
        var isButtonPositionFlipped = true;
        if (isButtonPositionFlipped != shouldFlipButtonPosition) {
            isButtonPositionFlipped = shouldFlipButtonPosition;
            (cleanBtn.layoutParams as RelativeLayout.LayoutParams).leftMargin =
                dipToPixels(this, 100f);//100dp?
            (analyzeBtn.layoutParams as RelativeLayout.LayoutParams).leftMargin = 0;
        } else {
            (cleanBtn.layoutParams as RelativeLayout.LayoutParams).leftMargin = 0;
            (analyzeBtn.layoutParams as RelativeLayout.LayoutParams).leftMargin =
                dipToPixels(this, 100f);//100dp?
        }
    }

    private fun dipToPixels(context: Context, dipValue: Float): Int {
        val metrics: DisplayMetrics = context.resources.displayMetrics
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics).toInt()
    }
</code>```
```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".TestActivity">

    <Button
        android:id="@+id/cleanBtn"
        android:layout_width="wrap_content"
        android:text="111"
        android:layout_height="wrap_content"></Button>

    <Button
        android:id="@+id/analyzeBtn"
        android:layout_marginLeft="100dp"
        android:layout_width="wrap_content"
        android:text="222"
        android:layout_height="wrap_content"></Button>

</RelativeLayout>
</code>```

Body:
So, I have 2 buttons and I wanna swap them by using a preference but Yeah, I can't make them switch properly

Here is my code for preference

    // In MainActivity.kt

    override fun onResume() {
        super.onResume()
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val shouldFlipButtonPosition = sharedPreferences.getBoolean("buttonpositions", false)
        if (isButtonPositionFlipped != shouldFlipButtonPosition) {
            isButtonPositionFlipped = shouldFlipButtonPosition
            val cleanBtn = findViewById<Button>(R.id.cleanBtn)
            val analyzeBtn = findViewById<Button>(R.id.analyzeBtn)
            if (isButtonPositionFlipped) {

                // Buttons swaped.

            } else {

               // Buttons back to normal.

            }
        }

I tried again to make them swap but I got some ugly results like this:

    override fun onResume() {
        super.onResume()
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val shouldFlipButtonPosition = sharedPreferences.getBoolean("buttonpositions", false)
        if (isButtonPositionFlipped != shouldFlipButtonPosition) {
            isButtonPositionFlipped = shouldFlipButtonPosition
            val cleanBtn = findViewById<Button>(R.id.cleanBtn)
            val analyzeBtn = findViewById<Button>(R.id.analyzeBtn)
            if (isButtonPositionFlipped) {
                val posX = cleanBtn.x
                val posY = cleanBtn.y
                analyzeBtn.x = posX
                analyzeBtn.y = posY
            } else {
                cleanBtn.setPadding(0, 0, 0, 0)
                analyzeBtn.setPadding(0, 0, 0, 0)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val shouldFlipButtonPosition = sharedPreferences.getBoolean("buttonpositions", false)
        if (isButtonPositionFlipped != shouldFlipButtonPosition) {
            isButtonPositionFlipped = shouldFlipButtonPosition
            val cleanBtn = findViewById<Button>(R.id.cleanBtn)
            val analyzeBtn = findViewById<Button>(R.id.analyzeBtn)
            if (isButtonPositionFlipped) {
                cleanBtn.setPadding(640, 0, 0, 0)
                analyzeBtn.setPadding(0, 0, 640, 0)
            } else {
                cleanBtn.setPadding(0, 0, 0, 0)
                analyzeBtn.setPadding(0, 0, 0, 0)
            }
        }
    }

I have to mention I tried to use set.Margins but isn't working

How can I swap them by using this method?

Body:
Try use RelativeLayout(or ConstraintLayout):

   override fun onResume() {
        super.onResume()
        val cleanBtn = findViewById<Button>(R.id.cleanBtn);
        val analyzeBtn = findViewById<Button>(R.id.analyzeBtn);
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val shouldFlipButtonPosition = sharedPreferences.getBoolean("buttonpositions", false)
        var isButtonPositionFlipped = true;
        if (isButtonPositionFlipped != shouldFlipButtonPosition) {
            isButtonPositionFlipped = shouldFlipButtonPosition;
            (cleanBtn.layoutParams as RelativeLayout.LayoutParams).leftMargin =
                dipToPixels(this, 100f);//100dp?
            (analyzeBtn.layoutParams as RelativeLayout.LayoutParams).leftMargin = 0;
        } else {
            (cleanBtn.layoutParams as RelativeLayout.LayoutParams).leftMargin = 0;
            (analyzeBtn.layoutParams as RelativeLayout.LayoutParams).leftMargin =
                dipToPixels(this, 100f);//100dp?
        }
    }

    private fun dipToPixels(context: Context, dipValue: Float): Int {
        val metrics: DisplayMetrics = context.resources.displayMetrics
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics).toInt()
    }

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".TestActivity">

    <Button
        android:id="@+id/cleanBtn"
        android:layout_width="wrap_content"
        android:text="111"
        android:layout_height="wrap_content"></Button>

    <Button
        android:id="@+id/analyzeBtn"
        android:layout_marginLeft="100dp"
        android:layout_width="wrap_content"
        android:text="222"
        android:layout_height="wrap_content"></Button>

</RelativeLayout>


问:
Passing function through Switch Route component
I want to build an app, which collects input information from sub-components and lift this information up to my main App component. I am using Switch with multiple Route to navigate through my questionnaire. I am able to pass variables and functions through my app until the <Switch> statement.

My problem: how do I pass a function or variable into my <Route> component.

```<code>class App extends Component {
    state = {
      date: new Date(),
      machineid: null,
    };

  handleChangeMachine(event) {
    const machineid_temp = event.target.value;
    this.setState({machineid: machineid_temp})
    console.log(machineid_temp)
  }

  render(){
    return (
    <div className="page">
      <Router>
        <Header testvalue="this is working"/>
        <Switch testvalues="this is working">
          <Route testvalues="this is not working" path="/" exact component={Landingpage}/>
          <Route path="/survey" component={Survey}/>
          <Route path="/kontakt" component={Kontakt}/>
          <Route path="/question_one" handleChangeMachine={this.handleChangeMachine}  component={question_one}/> {/* This is not working */}
          <Route path="/question_two" component={question_two}/>
        </Switch>
      </Router>
    </div>
  );
}
}

export default App;
</code>```

In this case the function handleChangeMachine isn't properly passed to the component question_one. Has anyone an idea about how I can solve it? I've tried every thing I understood as a React-beginner.

答:
Try this solution

class App extends Component {
    state = {
      date: new Date(),
      machineid: null,
    };

  handleChangeMachine(event) {
    const machineid_temp = event.target.value;
    this.setState({machineid: machineid_temp})
    console.log(machineid_temp)
  }

  render(){
    return (

      <Router>

        <Switch testvalues="this is working">
          <Route testvalues="this is not working" path="/" exact component={Landingpage}/>
          <Route path="/survey" component={Survey}/>
          <Route path="/kontakt" component={Kontakt}/>
          <Route path="/question_one">
          <question_one handleChangeMachine={this.handleChangeMachine.bind(this)} /> // rename component with UpperCase and without "_"
          </Route>
          <Route path="/question_two" component={question_two}/>
        </Switch>
      </Router>

  );
}
}

export default App;```

Body:
I want to build an app, which collects input information from sub-components and lift this information up to my main App component. I am using Switch with multiple Route to navigate through my questionnaire. I am able to pass variables and functions through my app until the <Switch> statement.

My problem: how do I pass a function or variable into my <Route> component.

class App extends Component {
    state = {
      date: new Date(),
      machineid: null,
    };

  handleChangeMachine(event) {
    const machineid_temp = event.target.value;
    this.setState({machineid: machineid_temp})
    console.log(machineid_temp)
  }

  render(){
    return (

      <Router>

        <Switch testvalues="this is working">
          <Route testvalues="this is not working" path="/" exact component={Landingpage}/>
          <Route path="/survey" component={Survey}/>
          <Route path="/kontakt" component={Kontakt}/>
          <Route path="/question_one" handleChangeMachine={this.handleChangeMachine}  component={question_one}/> {/* This is not working */}
          <Route path="/question_two" component={question_two}/>
        </Switch>
      </Router>

  );
}
}

export default App;

In this case the function handleChangeMachine isn't properly passed to the component question_one. Has anyone an idea about how I can solve it? I've tried every thing I understood as a React-beginner.

Body:
Try this solution

class App extends Component {
    state = {
      date: new Date(),
      machineid: null,
    };

  handleChangeMachine(event) {
    const machineid_temp = event.target.value;
    this.setState({machineid: machineid_temp})
    console.log(machineid_temp)
  }

  render(){
    return (
    <div className="page">
      <Router>
        <Header testvalue="this is working"/>
        <Switch testvalues="this is working">
          <Route testvalues="this is not working" path="/" exact component={Landingpage}/>
          <Route path="/survey" component={Survey}/>
          <Route path="/kontakt" component={Kontakt}/>
          <Route path="/question_one">
          <question_one handleChangeMachine={this.handleChangeMachine.bind(this)} /> // rename component with UpperCase and without "_"
          </Route>
          <Route path="/question_two" component={question_two}/>
        </Switch>
      </Router>
    </div>
  );
}
}

export default App;


Title: Extracting daypart Items for the Python List

Body:
how do I extract the items from the 'daypart' item in the list below.

forecast_data = requests.get(fiveDayForecastUrl)
forecast_dictionary = forecast_data.json()
json_list = list(forecast_dictionary.items())
print(any('cloudCover' in inner_list for inner_list in forecast_dictionary['daypart']))
print(json_list)

Result of json_list is below.

[('calendarDayTemperatureMax', [28, 29, 27, 28, 29, 30]), ('calendarDayTemperatureMin', [15, 16, 18, 17, 16, 15]), ('dayOfWeek', ['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']), ('expirationTimeUtc', [1644346025, 1644346025, 1644346025, 1644346025, 1644346025, 1644346025]), ('moonPhase', ['First Quarter', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous']), ('moonPhaseCode', ['FQ', 'WXG', 'WXG', 'WXG', 'WXG', 'WXG']), ('moonPhaseDay', [7, 8, 9, 10, 11, 11]), ('moonriseTimeLocal', ['2022-02-08T12:30:04+0200', '2022-02-09T13:24:48+0200', '2022-02-10T14:18:50+0200', '2022-02-11T15:13:16+0200', '2022-02-12T16:05:40+0200', '2022-02-13T16:55:40+0200']), ('moonriseTimeUtc', [1644316204, 1644405888, 1644495530, 1644585196, 1644674740, 1644764140]), ('moonsetTimeLocal', ['2022-02-08T23:39:38+0200', '', '2022-02-10T00:16:37+0200', '2022-02-11T00:58:13+0200', '2022-02-12T01:44:21+0200', '2022-02-13T02:34:17+0200']), ('moonsetTimeUtc', [1644356378, None, 1644444997, 1644533893, 1644623061, 1644712457]), ('narrative', ['Partly cloudy. Low 16C.', 'Plenty of sun. Highs 28 to 30C and lows 17 to 19C.', 'Thunderstorms developing in the afternoon. Highs 26 to 28C and lows 16 to 18C.', 'Partly cloudy. Highs 27 to 29C and lows 15 to 17C.', 'Mostly sunny. Highs 28 to 30C and lows 14 to 16C.', 'Sunny. Highs 29 to 31C and lows 15 to 17C.']), ('qpf', [0.0, 0.0, 2.46, 0.0, 0.0, 0.0]), ('qpfSnow', [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), ('sunriseTimeLocal', ['2022-02-08T05:48:01+0200', '2022-02-09T05:48:44+0200', '2022-02-10T05:49:25+0200', '2022-02-11T05:50:07+0200', '2022-02-12T05:50:48+0200', '2022-02-13T05:51:28+0200']), ('sunriseTimeUtc', [1644292081, 1644378524, 1644464965, 1644551407, 1644637848, 1644724288]), ('sunsetTimeLocal', ['2022-02-08T18:54:58+0200', '2022-02-09T18:54:18+0200', '2022-02-10T18:53:38+0200', '2022-02-11T18:52:56+0200', '2022-02-12T18:52:13+0200', '2022-02-13T18:51:30+0200']), ('sunsetTimeUtc', [1644339298, 1644425658, 1644512018, 1644598376, 1644684733, 1644771090]), ('temperatureMax', [None, 29, 27, 28, 29, 30]), ('temperatureMin', [16, 18, 17, 16, 15, 16]), ('validTimeLocal', ['2022-02-08T07:00:00+0200', '2022-02-09T07:00:00+0200', '2022-02-10T07:00:00+0200', '2022-02-11T07:00:00+0200', '2022-02-12T07:00:00+0200', '2022-02-13T07:00:00+0200']), ('validTimeUtc', [1644296400, 1644382800, 1644469200, 1644555600, 1644642000, 1644728400]), ('daypart', [{'cloudCover': [None, 29, 33, 29, 40, 40, 37, 40, 25, 20, 12, 18], 'dayOrNight': [None, 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N'], 'daypartName': [None, 'Tonight', 'Tomorrow', 'Tomorrow night', 'Thursday', 'Thursday night', 'Friday', 'Friday night', 'Saturday', 'Saturday night', 'Sunday', 'Sunday night'], 'iconCode': [None, 29, 34, 29, 38, 29, 30, 29, 34, 33, 32, 33], 'iconCodeExtend': [None, 2900, 3400, 2900, 7203, 2900, 3000, 2900, 3400, 3300, 3200, 3300], 'narrative': [None, 'Partly cloudy. Low 16C. Winds light and variable.', 'Except for a few afternoon clouds, mainly sunny. High 29C. Winds WNW at 10 to 15 km/h.', 'Partly cloudy. Low 18C. Winds light and variable.', 'Partly cloudy early. Scattered thunderstorms developing in the afternoon. High 27C. Winds NNE at 10 to 15 km/h. Chance of rain 50%.', 'A few clouds. Low 17C. Winds light and variable.', 'Partly cloudy skies. High 28C. Winds NE at 10 to 15 km/h.', 'Partly cloudy. Low 16C. Winds E at 10 to 15 km/h.', 'A few clouds from time to time. High 29C. Winds NE at 10 to 15 km/h.', 'A few clouds from time to time. Low around 15C. Winds E at 10 to 15 km/h.', 'Sunny. High near 30C. Winds NE at 10 to 15 km/h.', 'Mostly clear. Low 16C. Winds E at 10 to 15 km/h.'], 'precipChance': [None, 8, 22, 8, 50, 18, 24, 18, 4, 2, 2, 3], 'precipType': [None, 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain'], 'qpf': [None, 0.0, 0.0, 0.0, 2.46, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 'qpfSnow': [None, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 'qualifierCode': [None, None, None, None, None, None, None, None, None, None, None, None], 'qualifierPhrase': [None, None, None, None, None, None, None, None, None, None, None, None], 'relativeHumidity': [None, 79, 50, 65, 55, 76, 51, 58, 37, 54, 38, 54], 'snowRange': [None, '', '', '', '', '', '', '', '', '', '', ''], 'temperature': [None, 16, 29, 18, 27, 17, 28, 16, 29, 15, 30, 16], 'temperatureHeatIndex': [None, 19, 28, 24, 27, 22, 27, 23, 28, 23, 29, 24], 'temperatureWindChill': [None, 17, 19, 18, 20, 17, 19, 16, 17, 15, 17, 17], 'thunderCategory': [None, 'No thunder', 'No thunder', 'No thunder', 'Thunder expected', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder'], 'thunderIndex': [None, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0], 'uvDescription': [None, 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low'], 'uvIndex': [None, 0, 11, 0, 11, 0, 11, 0, 11, 0, 11, 0], 'windDirection': [None, 140, 288, 126, 30, 95, 38, 86, 53, 81, 41, 83], 'windDirectionCardinal': [None, 'SE', 'WNW', 'SE', 'NNE', 'E', 'NE', 'E', 'NE', 'E', 'NE', 'E'], 'windPhrase': [None, 'Winds light and variable.', 'Winds WNW at 10 to 15 km/h.', 'Winds light and variable.', 'Winds NNE at 10 to 15 km/h.', 'Winds light and variable.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.'], 'windSpeed': [None, 9, 11, 10, 16, 9, 12, 12, 13, 13, 10, 10], 'wxPhraseLong': [None, 'Partly Cloudy', 'Mostly Sunny', 'Partly Cloudy', 'PM Thunderstorms', 'Partly Cloudy', 'Partly Cloudy', 'Partly Cloudy', 'Mostly Sunny', 'Mostly Clear', 'Sunny', 'Mostly Clear'], 'wxPhraseShort': [None, 'P Cloudy', 'M Sunny', 'P Cloudy', 'PM T-Storms', 'P Cloudy', 'P Cloudy', 'P Cloudy', 'M Sunny', 'M Clear', 'Sunny', 'M Clear']}])]

Body:
Looking at the json_list you provided, with a little of manual formatting :

json_list = [
    ('calendarDayTemperatureMax', [28, 29, 27, 28, 29, 30]),
    ('calendarDayTemperatureMin', [15, 16, 18, 17, 16, 15]),
    ('dayOfWeek', ['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']),
    ('expirationTimeUtc', [1644346025, 1644346025, 1644346025, 1644346025, 1644346025, 1644346025]),
    ('moonPhase', ['First Quarter', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous']),
    ('moonPhaseCode', ['FQ', 'WXG', 'WXG', 'WXG', 'WXG', 'WXG']),
    ('moonPhaseDay', [7, 8, 9, 10, 11, 11]),
    ('moonriseTimeLocal', ['2022-02-08T12:30:04+0200', '2022-02-09T13:24:48+0200', '2022-02-10T14:18:50+0200', '2022-02-11T15:13:16+0200', '2022-02-12T16:05:40+0200', '2022-02-13T16:55:40+0200']),
    ('moonriseTimeUtc', [1644316204, 1644405888, 1644495530, 1644585196, 1644674740, 1644764140]),
    ('moonsetTimeLocal', ['2022-02-08T23:39:38+0200', '', '2022-02-10T00:16:37+0200', '2022-02-11T00:58:13+0200', '2022-02-12T01:44:21+0200', '2022-02-13T02:34:17+0200']),
    ('moonsetTimeUtc', [1644356378, None, 1644444997, 1644533893, 1644623061, 1644712457]),
    ('narrative', ['Partly cloudy. Low 16C.', 'Plenty of sun. Highs 28 to 30C and lows 17 to 19C.', 'Thunderstorms developing in the afternoon. Highs 26 to 28C and lows 16 to 18C.', 'Partly cloudy. Highs 27 to 29C and lows 15 to 17C.', 'Mostly sunny. Highs 28 to 30C and lows 14 to 16C.', 'Sunny. Highs 29 to 31C and lows 15 to 17C.']),
    ('qpf', [0.0, 0.0, 2.46, 0.0, 0.0, 0.0]),
    ('qpfSnow', [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
    ('sunriseTimeLocal', ['2022-02-08T05:48:01+0200', '2022-02-09T05:48:44+0200', '2022-02-10T05:49:25+0200', '2022-02-11T05:50:07+0200', '2022-02-12T05:50:48+0200', '2022-02-13T05:51:28+0200']),
    ('sunriseTimeUtc', [1644292081, 1644378524, 1644464965, 1644551407, 1644637848, 1644724288]),
    ('sunsetTimeLocal', ['2022-02-08T18:54:58+0200', '2022-02-09T18:54:18+0200', '2022-02-10T18:53:38+0200', '2022-02-11T18:52:56+0200', '2022-02-12T18:52:13+0200', '2022-02-13T18:51:30+0200']),
    ('sunsetTimeUtc', [1644339298, 1644425658, 1644512018, 1644598376, 1644684733, 1644771090]),
    ('temperatureMax', [None, 29, 27, 28, 29, 30]),
    ('temperatureMin', [16, 18, 17, 16, 15, 16]),
    ('validTimeLocal', ['2022-02-08T07:00:00+0200', '2022-02-09T07:00:00+0200', '2022-02-10T07:00:00+0200', '2022-02-11T07:00:00+0200', '2022-02-12T07:00:00+0200', '2022-02-13T07:00:00+0200']),
    ('validTimeUtc', [1644296400, 1644382800, 1644469200, 1644555600, 1644642000, 1644728400]),
    ('daypart', [{'cloudCover': [None, 29, 33, 29, 40, 40, 37, 40, 25, 20, 12, 18],
                  'dayOrNight': [None, 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N'],
                  'daypartName': [None, 'Tonight', 'Tomorrow', 'Tomorrow night', 'Thursday', 'Thursday night', 'Friday', 'Friday night', 'Saturday', 'Saturday night', 'Sunday', 'Sunday night'],
                  'iconCode': [None, 29, 34, 29, 38, 29, 30, 29, 34, 33, 32, 33],
                  'iconCodeExtend': [None, 2900, 3400, 2900, 7203, 2900, 3000, 2900, 3400, 3300, 3200, 3300],
                  'narrative': [None, 'Partly cloudy. Low 16C. Winds light and variable.', 'Except for a few afternoon clouds, mainly sunny. High 29C. Winds WNW at 10 to 15 km/h.', 'Partly cloudy. Low 18C. Winds light and variable.', 'Partly cloudy early. Scattered thunderstorms developing in the afternoon. High 27C. Winds NNE at 10 to 15 km/h. Chance of rain 50%.', 'A few clouds. Low 17C. Winds light and variable.', 'Partly cloudy skies. High 28C. Winds NE at 10 to 15 km/h.', 'Partly cloudy. Low 16C. Winds E at 10 to 15 km/h.', 'A few clouds from time to time. High 29C. Winds NE at 10 to 15 km/h.', 'A few clouds from time to time. Low around 15C. Winds E at 10 to 15 km/h.', 'Sunny. High near 30C. Winds NE at 10 to 15 km/h.', 'Mostly clear. Low 16C. Winds E at 10 to 15 km/h.'],
                  'precipChance': [None, 8, 22, 8, 50, 18, 24, 18, 4, 2, 2, 3],
                  'precipType': [None, 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain'],
                  'qpf': [None, 0.0, 0.0, 0.0, 2.46, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                  'qpfSnow': [None, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                  'qualifierCode': [None, None, None, None, None, None, None, None, None, None, None, None],
                  'qualifierPhrase': [None, None, None, None, None, None, None, None, None, None, None, None],
                  'relativeHumidity': [None, 79, 50, 65, 55, 76, 51, 58, 37, 54, 38, 54],
                  'snowRange': [None, '', '', '', '', '', '', '', '', '', '', ''],
                  'temperature': [None, 16, 29, 18, 27, 17, 28, 16, 29, 15, 30, 16],
                  'temperatureHeatIndex': [None, 19, 28, 24, 27, 22, 27, 23, 28, 23, 29, 24],
                  'temperatureWindChill': [None, 17, 19, 18, 20, 17, 19, 16, 17, 15, 17, 17],
                  'thunderCategory': [None, 'No thunder', 'No thunder', 'No thunder', 'Thunder expected', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder'],
                  'thunderIndex': [None, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0],
                  'uvDescription': [None, 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low'],
                  'uvIndex': [None, 0, 11, 0, 11, 0, 11, 0, 11, 0, 11, 0],
                  'windDirection': [None, 140, 288, 126, 30, 95, 38, 86, 53, 81, 41, 83],
                  'windDirectionCardinal': [None, 'SE', 'WNW', 'SE', 'NNE', 'E', 'NE', 'E', 'NE', 'E', 'NE', 'E'],
                  'windPhrase': [None, 'Winds light and variable.', 'Winds WNW at 10 to 15 km/h.', 'Winds light and variable.', 'Winds NNE at 10 to 15 km/h.', 'Winds light and variable.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.'],
                  'windSpeed': [None, 9, 11, 10, 16, 9, 12, 12, 13, 13, 10, 10],
                  'wxPhraseLong': [None, 'Partly Cloudy', 'Mostly Sunny', 'Partly Cloudy', 'PM Thunderstorms', 'Partly Cloudy', 'Partly Cloudy', 'Partly Cloudy', 'Mostly Sunny', 'Mostly Clear', 'Sunny', 'Mostly Clear'],
                  'wxPhraseShort': [None, 'P Cloudy', 'M Sunny', 'P Cloudy', 'PM T-Storms', 'P Cloudy', 'P Cloudy', 'P Cloudy', 'M Sunny', 'M Clear', 'Sunny', 'M Clear']
                  }]
     )
]

Because you converted to a list the result of forecast_dictionary.items(), it means that here is the dictionary you started with :

forecast_dictionary = dict(json_list)
# or, more explicitly :
forecast_dictionary = {
    'calendarDayTemperatureMax': [28, 29, 27, 28, 29, 30],
    'calendarDayTemperatureMin': [15, 16, 18, 17, 16, 15],
    'dayOfWeek': ['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
    'expirationTimeUtc': [1644346025, 1644346025, 1644346025, 1644346025, 1644346025, 1644346025],
    'moonPhase': ['First Quarter', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous', 'Waxing Gibbous'],
    'moonPhaseCode': ['FQ', 'WXG', 'WXG', 'WXG', 'WXG', 'WXG'],
    'moonPhaseDay': [7, 8, 9, 10, 11, 11],
    'moonriseTimeLocal': ['2022-02-08T12:30:04+0200', '2022-02-09T13:24:48+0200', '2022-02-10T14:18:50+0200', '2022-02-11T15:13:16+0200', '2022-02-12T16:05:40+0200', '2022-02-13T16:55:40+0200'],
    'moonriseTimeUtc': [1644316204, 1644405888, 1644495530, 1644585196, 1644674740, 1644764140],
    'moonsetTimeLocal': ['2022-02-08T23:39:38+0200', '', '2022-02-10T00:16:37+0200', '2022-02-11T00:58:13+0200', '2022-02-12T01:44:21+0200', '2022-02-13T02:34:17+0200'],
    'moonsetTimeUtc': [1644356378, None, 1644444997, 1644533893, 1644623061, 1644712457],
    'narrative': ['Partly cloudy. Low 16C.', 'Plenty of sun. Highs 28 to 30C and lows 17 to 19C.', 'Thunderstorms developing in the afternoon. Highs 26 to 28C and lows 16 to 18C.', 'Partly cloudy. Highs 27 to 29C and lows 15 to 17C.', 'Mostly sunny. Highs 28 to 30C and lows 14 to 16C.', 'Sunny. Highs 29 to 31C and lows 15 to 17C.'],
    'qpf': [0.0, 0.0, 2.46, 0.0, 0.0, 0.0],
    'qpfSnow': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
    'sunriseTimeLocal': ['2022-02-08T05:48:01+0200', '2022-02-09T05:48:44+0200', '2022-02-10T05:49:25+0200', '2022-02-11T05:50:07+0200', '2022-02-12T05:50:48+0200', '2022-02-13T05:51:28+0200'],
    'sunriseTimeUtc': [1644292081, 1644378524, 1644464965, 1644551407, 1644637848, 1644724288],
    'sunsetTimeLocal': ['2022-02-08T18:54:58+0200', '2022-02-09T18:54:18+0200', '2022-02-10T18:53:38+0200', '2022-02-11T18:52:56+0200', '2022-02-12T18:52:13+0200', '2022-02-13T18:51:30+0200'],
    'sunsetTimeUtc': [1644339298, 1644425658, 1644512018, 1644598376, 1644684733, 1644771090],
    'temperatureMax': [None, 29, 27, 28, 29, 30],
    'temperatureMin': [16, 18, 17, 16, 15, 16],
    'validTimeLocal': ['2022-02-08T07:00:00+0200', '2022-02-09T07:00:00+0200', '2022-02-10T07:00:00+0200', '2022-02-11T07:00:00+0200', '2022-02-12T07:00:00+0200', '2022-02-13T07:00:00+0200'],
    'validTimeUtc': [1644296400, 1644382800, 1644469200, 1644555600, 1644642000, 1644728400],
    'daypart': [{'cloudCover': [None, 29, 33, 29, 40, 40, 37, 40, 25, 20, 12, 18],
                 'dayOrNight': [None, 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N'],
                 'daypartName': [None, 'Tonight', 'Tomorrow', 'Tomorrow night', 'Thursday', 'Thursday night', 'Friday', 'Friday night', 'Saturday', 'Saturday night', 'Sunday', 'Sunday night'],
                 'iconCode': [None, 29, 34, 29, 38, 29, 30, 29, 34, 33, 32, 33],
                 'iconCodeExtend': [None, 2900, 3400, 2900, 7203, 2900, 3000, 2900, 3400, 3300, 3200, 3300],
                 'narrative': [None, 'Partly cloudy. Low 16C. Winds light and variable.', 'Except for a few afternoon clouds, mainly sunny. High 29C. Winds WNW at 10 to 15 km/h.', 'Partly cloudy. Low 18C. Winds light and variable.', 'Partly cloudy early. Scattered thunderstorms developing in the afternoon. High 27C. Winds NNE at 10 to 15 km/h. Chance of rain 50%.', 'A few clouds. Low 17C. Winds light and variable.', 'Partly cloudy skies. High 28C. Winds NE at 10 to 15 km/h.', 'Partly cloudy. Low 16C. Winds E at 10 to 15 km/h.', 'A few clouds from time to time. High 29C. Winds NE at 10 to 15 km/h.', 'A few clouds from time to time. Low around 15C. Winds E at 10 to 15 km/h.', 'Sunny. High near 30C. Winds NE at 10 to 15 km/h.', 'Mostly clear. Low 16C. Winds E at 10 to 15 km/h.'],
                 'precipChance': [None, 8, 22, 8, 50, 18, 24, 18, 4, 2, 2, 3],
                 'precipType': [None, 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain', 'rain'],
                 'qpf': [None, 0.0, 0.0, 0.0, 2.46, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                 'qpfSnow': [None, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                 'qualifierCode': [None, None, None, None, None, None, None, None, None, None, None, None],
                 'qualifierPhrase': [None, None, None, None, None, None, None, None, None, None, None, None],
                 'relativeHumidity': [None, 79, 50, 65, 55, 76, 51, 58, 37, 54, 38, 54],
                 'snowRange': [None, '', '', '', '', '', '', '', '', '', '', ''],
                 'temperature': [None, 16, 29, 18, 27, 17, 28, 16, 29, 15, 30, 16],
                 'temperatureHeatIndex': [None, 19, 28, 24, 27, 22, 27, 23, 28, 23, 29, 24],
                 'temperatureWindChill': [None, 17, 19, 18, 20, 17, 19, 16, 17, 15, 17, 17],
                 'thunderCategory': [None, 'No thunder', 'No thunder', 'No thunder', 'Thunder expected', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder', 'No thunder'],
                 'thunderIndex': [None, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0],
                 'uvDescription': [None, 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low', 'Extreme', 'Low'],
                 'uvIndex': [None, 0, 11, 0, 11, 0, 11, 0, 11, 0, 11, 0],
                 'windDirection': [None, 140, 288, 126, 30, 95, 38, 86, 53, 81, 41, 83],
                 'windDirectionCardinal': [None, 'SE', 'WNW', 'SE', 'NNE', 'E', 'NE', 'E', 'NE', 'E', 'NE', 'E'],
                 'windPhrase': [None, 'Winds light and variable.', 'Winds WNW at 10 to 15 km/h.', 'Winds light and variable.', 'Winds NNE at 10 to 15 km/h.', 'Winds light and variable.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.', 'Winds NE at 10 to 15 km/h.', 'Winds E at 10 to 15 km/h.'],
                 'windSpeed': [None, 9, 11, 10, 16, 9, 12, 12, 13, 13, 10, 10],
                 'wxPhraseLong': [None, 'Partly Cloudy', 'Mostly Sunny', 'Partly Cloudy', 'PM Thunderstorms', 'Partly Cloudy', 'Partly Cloudy', 'Partly Cloudy', 'Mostly Sunny', 'Mostly Clear', 'Sunny', 'Mostly Clear'],
                 'wxPhraseShort': [None, 'P Cloudy', 'M Sunny', 'P Cloudy', 'PM T-Storms', 'P Cloudy', 'P Cloudy', 'P Cloudy', 'M Sunny', 'M Clear', 'Sunny', 'M Clear']
                 }]
}

If you want to get the daypart item from the dictionary, then it is simply :

daypart_item = forecast_dictionary["daypart"]
print(json.dumps(daypart_item))

[{"cloudCover": [null, 29, 33, 29, 40, 40, 37, 40, 25, 20, 12, 18], "dayOrNight": ... }]


问:
Can I build SearchPredicates in HibernateSearch without SearchSession and Class?
I am trying to migrate a project using ElasticSearch to HibernateSearch. Currently, we build complex ElasticSearch queries via combining multiple QueryBuilder objects created by separate methods like this:

```<code>protected QueryBuilder createSetQuery(String key, Set<?> values, boolean contains) {
    if (contains && !values.isEmpty()) {
        return QueryBuilders.termsQuery(key, values);
    } else if (!contains && Objects.nonNull(values)) {
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        return boolQuery.mustNot(QueryBuilders.termsQuery(key, values));
    } else {
        return QueryBuilders.matchQuery(key, 0);
    }
}
</code>```

The returned QueryBuilder objects are then combined in calling methods via BooleanQueryBuilder objects like this:

```<code>...
BoolQueryBuilder boolQuery = new BoolQueryBuilder();
boolQuery.must(createSetQuery(...);
...
</code>```

Now I tried to migrate these methods to equivalent HibernateSearch methods like this, returning SearchPredicates instead of QueryBuilders (reading the HibernateSearch documentation https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single I got the impression that is the closest match):

```<code>protected SearchPredicate createSetSearchPredicate(Class<?> clazz, SearchSession searchSession, String fieldName,
                                                   Set<?> fieldValues, boolean contains) {
    if (contains) {
        SearchScope<?> scope = searchSession.scope(clazz);
        SearchPredicateFactory factory = scope.predicate();
        return factory.terms().field( fieldName ).matchingAny( fieldValues ).toPredicate();
    } else {
        SearchScope<?> scope = searchSession.scope(clazz);
        SearchPredicateFactory factory = scope.predicate();
        return factory.bool().mustNot(factory.terms().field( fieldName ).matchingAny( fieldValues )).toPredicate();
    }
}
</code>```

The problem I have is creating a SearchPredicate always seems to require a given Class and a HibernateSearch SearchSession. Is there any way to create such SearchPredicate instances without those two objects? In a similar "class agnostic" way as when building the ElasticSearch QueryBuilders?

Currently, I have to either

create the SearchSession in the outermost calling method and pass it together with a Class object through all intermediate methods until I reach those SearchPredicate creating methods or

create the SearchSession object within each SearchPredicate creating method

My questions:

is the later - creating SearchSession objects within each method - a problem? Do I have to make sure to reuse existing sessions or is SearchSession already a singleton and I do not have to worry about that?

is there a way to create SearchPredicates without Class and SearchSession objects, similar to how we created ElasticSearch QueryBuilder objects?

is there a more approriate way to do what I am trying? Some other HibernateSearch class that would better fit as an replacement for the ombinable ElasticSearch QueryBuilder objects than SearchPredicates?

Thanks a lot in advance for any help!

答:
I would recommend having a look at this section of the reference documentation to get an idea of how the Hibernate Search API is intended to be used.

You could just do this:

protected List<MyEntity> myOuterMostMethod() {
    List<MyEntity> hits = searchSession.search( MyEntity.class )
        .where( f -> f.bool( b -> {
            b.must( createSetSearchPredicate( f, "myField1",
                    Set.of( "val1", "val2" ), true ) );
            b.must( createSetSearchPredicate( f, "myField2",
                    Set.of( "val3", "val4" ), false ) );
        } ) )
        .fetchHits( 20 );
}

protected SearchPredicate createSetSearchPredicate(SearchPredicateFactory factory,
    String fieldName, Set<?> fieldValues, boolean contains) {
    if (contains) {
        return factory.terms()
                .field( fieldName ).matchingAny( fieldValues )
                .toPredicate();
    } else {
        return factory.bool().mustNot(factory.terms()
                .field( fieldName ).matchingAny( fieldValues ))
                .toPredicate();
    }
}
```
<p>You can also do this, which is clearer in my opinion:</p>
<pre class="lang-java prettyprint-override"><code>
protected List<MyEntity> myOuterMostMethod() {
    List<MyEntity> hits = searchSession.search( MyEntity.class )
        .where( f -> f.bool( b -> {
            b.must( containAny( f, "myField1", Set.of( "val1", "val2" ) ) );
            b.mustNot( containAny( f, "myField2", Set.of( "val3", "val4" ) ) );
        } ) )
        .fetchHits( 20 );
}

protected SearchPredicate containAny(SearchPredicateFactory factory,
    String fieldName, Set<?> fieldValues) {
    return factory.terms().field( fieldName ).matchingAny( fieldValues ).toPredicate();
}
</code>```

As to your questions:

is the later - creating SearchSession objects within each method - a problem? Do I have to make sure to reuse existing sessions or is SearchSession already a singleton and I do not have to worry about that?

There is some level of caching behind the scenes, so performance-wise it shouldn't be too bad. But really, there's no need to re-create a SearchSession every time. Just grab the SearchPredicateFactory as shown in my example and pass that to your method.

is there a way to create SearchPredicates without Class and SearchSession objects, similar to how we created ElasticSearch QueryBuilder objects?

Not really. Hibernate Search checks that the fields you reference actually exist, and it uses metadata to convert the values that you pass into JSON. It needs context in order to access that metadata, so it can't just create predicates from a static method call.

You can, however, create search predicates without a session. That gets rid of the requirement to have an open EntityManager/Session from Hibernate ORM, but you still need access to an EntityManagerFactory/SessionFactory (which contains the metadata Hibernate Search needs) and you still need to tell Hibernate Search which class you will target. Something like this:

```<code>EntityManagerFactory entityManagerFactory = ...;
SearchScope<?> scope = Search.mapping(entityManagerFactory).scope(clazz);
SearchPredicateFactory factory = scope.predicate()
</code>```

Also, if you really want to bypass Hibernate Search metadata, you can pass a JSON query to Hibernate Search directly.

is there a more approriate way to do what I am trying? Some other HibernateSearch class that would better fit as an replacement for the ombinable ElasticSearch QueryBuilder objects than SearchPredicates?

The classes you're using are the right ones. I think you just need to make peace with the fact that Hibernate Search needs some context (a SearchPredicateFactory instance) to create a predicate, and does not offer static methods to create a predicate.

Body:
I am trying to migrate a project using ElasticSearch to HibernateSearch. Currently, we build complex ElasticSearch queries via combining multiple QueryBuilder objects created by separate methods like this:

protected QueryBuilder createSetQuery(String key, Set<?> values, boolean contains) {
    if (contains && !values.isEmpty()) {
        return QueryBuilders.termsQuery(key, values);
    } else if (!contains && Objects.nonNull(values)) {
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        return boolQuery.mustNot(QueryBuilders.termsQuery(key, values));
    } else {
        return QueryBuilders.matchQuery(key, 0);
    }
}

The returned QueryBuilder objects are then combined in calling methods via BooleanQueryBuilder objects like this:

...
BoolQueryBuilder boolQuery = new BoolQueryBuilder();
boolQuery.must(createSetQuery(...);
...

Now I tried to migrate these methods to equivalent HibernateSearch methods like this, returning SearchPredicates instead of QueryBuilders (reading the HibernateSearch documentation https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single I got the impression that is the closest match):

protected SearchPredicate createSetSearchPredicate(Class<?> clazz, SearchSession searchSession, String fieldName,
                                                   Set<?> fieldValues, boolean contains) {
    if (contains) {
        SearchScope<?> scope = searchSession.scope(clazz);
        SearchPredicateFactory factory = scope.predicate();
        return factory.terms().field( fieldName ).matchingAny( fieldValues ).toPredicate();
    } else {
        SearchScope<?> scope = searchSession.scope(clazz);
        SearchPredicateFactory factory = scope.predicate();
        return factory.bool().mustNot(factory.terms().field( fieldName ).matchingAny( fieldValues )).toPredicate();
    }
}

The problem I have is creating a SearchPredicate always seems to require a given Class and a HibernateSearch SearchSession. Is there any way to create such SearchPredicate instances without those two objects? In a similar "class agnostic" way as when building the ElasticSearch QueryBuilders?

Currently, I have to either

create the SearchSession in the outermost calling method and pass it together with a Class object through all intermediate methods until I reach those SearchPredicate creating methods or

create the SearchSession object within each SearchPredicate creating method

My questions:

is the later - creating SearchSession objects within each method - a problem? Do I have to make sure to reuse existing sessions or is SearchSession already a singleton and I do not have to worry about that?

is there a way to create SearchPredicates without Class and SearchSession objects, similar to how we created ElasticSearch QueryBuilder objects?

is there a more approriate way to do what I am trying? Some other HibernateSearch class that would better fit as an replacement for the ombinable ElasticSearch QueryBuilder objects than SearchPredicates?

Thanks a lot in advance for any help!

Body:
I would recommend having a look at this section of the reference documentation to get an idea of how the Hibernate Search API is intended to be used.

You could just do this:

protected List<MyEntity> myOuterMostMethod() {
    List<MyEntity> hits = searchSession.search( MyEntity.class )
        .where( f -> f.bool( b -> {
            b.must( createSetSearchPredicate( f, "myField1",
                    Set.of( "val1", "val2" ), true ) );
            b.must( createSetSearchPredicate( f, "myField2",
                    Set.of( "val3", "val4" ), false ) );
        } ) )
        .fetchHits( 20 );
}

protected SearchPredicate createSetSearchPredicate(SearchPredicateFactory factory,
    String fieldName, Set<?> fieldValues, boolean contains) {
    if (contains) {
        return factory.terms()
                .field( fieldName ).matchingAny( fieldValues )
                .toPredicate();
    } else {
        return factory.bool().mustNot(factory.terms()
                .field( fieldName ).matchingAny( fieldValues ))
                .toPredicate();
    }
}

You can also do this, which is clearer in my opinion:

protected List<MyEntity> myOuterMostMethod() {
    List<MyEntity> hits = searchSession.search( MyEntity.class )
        .where( f -> f.bool( b -> {
            b.must( containAny( f, "myField1", Set.of( "val1", "val2" ) ) );
            b.mustNot( containAny( f, "myField2", Set.of( "val3", "val4" ) ) );
        } ) )
        .fetchHits( 20 );
}

protected SearchPredicate containAny(SearchPredicateFactory factory,
    String fieldName, Set<?> fieldValues) {
    return factory.terms().field( fieldName ).matchingAny( fieldValues ).toPredicate();
}

As to your questions:

is the later - creating SearchSession objects within each method - a problem? Do I have to make sure to reuse existing sessions or is SearchSession already a singleton and I do not have to worry about that?

There is some level of caching behind the scenes, so performance-wise it shouldn't be too bad. But really, there's no need to re-create a SearchSession every time. Just grab the SearchPredicateFactory as shown in my example and pass that to your method.

is there a way to create SearchPredicates without Class and SearchSession objects, similar to how we created ElasticSearch QueryBuilder objects?

Not really. Hibernate Search checks that the fields you reference actually exist, and it uses metadata to convert the values that you pass into JSON. It needs context in order to access that metadata, so it can't just create predicates from a static method call.

You can, however, create search predicates without a session. That gets rid of the requirement to have an open EntityManager/Session from Hibernate ORM, but you still need access to an EntityManagerFactory/SessionFactory (which contains the metadata Hibernate Search needs) and you still need to tell Hibernate Search which class you will target. Something like this:

EntityManagerFactory entityManagerFactory = ...;
SearchScope<?> scope = Search.mapping(entityManagerFactory).scope(clazz);
SearchPredicateFactory factory = scope.predicate()

Also, if you really want to bypass Hibernate Search metadata, you can pass a JSON query to Hibernate Search directly.

is there a more approriate way to do what I am trying? Some other HibernateSearch class that would better fit as an replacement for the ombinable ElasticSearch QueryBuilder objects than SearchPredicates?

The classes you're using are the right ones. I think you just need to make peace with the fact that Hibernate Search needs some context (a SearchPredicateFactory instance) to create a predicate, and does not offer static methods to create a predicate.


问:
Improving accuracy on multilabe segmentation problem with DeepLabV3+ and ResNet101
I took the code from this page and made several modifications: https://keras.io/examples/vision/deeplabv3_plus/

One thing I did was add flipping left right augmentation to the dataset:

```<code>def image_augmentation(img):
    img = tf.image.random_flip_left_right(img)
    return img

def image_process(path, mask=False):
    img = tf.io.read_file(path)

    if mask == True:
        img = tf.image.decode_png(img, channels=1)
        img.set_shape([None, None, 1])
        img = tf.image.resize(images=img, size=[image_size, image_size])
        img = image_augmentation(img) # <- This is where the augmentation is happening

    else:
        img = tf.image.decode_png(img, channels=3)
        img.set_shape([None, None, 3])
        img = tf.image.resize(images=img, size=[image_size, image_size])
        img = img / 127.5 - 1

    return img
</code>```

Then I've changed the backend from ResNet50 to ResNet101 but did not alter the convolution block. I've decreased the learning rate from 0.01 to 0.001.

This is the CIHP dataset and I'm basically using the entire dataset for training and not a subset. After 25 epochs, my accuracy is at best 0.76. I've tried other augmentation techniques, such as random cropping, flipping up and down, brightness, etc. but all of them yielded far worse performance.

What are other things I can do to improve the accuracy?

Edit

This is my training code:

```<code>loss = keras.losses.SparseCategoricalCrossentropy(from_logits = True)

lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor = 0.1,patience = 5, min_lr=0.0001)

model.compile(optimizer = keras.optimizers.Adam(learning_rate = lr), loss = loss, metrics=["accuracy"],)

history = model.fit(train_dataset, validation_data = val_dataset, epochs = 100)
</code>```

答:
I would opt for a learning rate scheduler, so that I do not hold the
learning rate fixed during the entire training phase. You can opt for either a built-in ReduceLROnPlateau() or define your own scheduler.

Error analysis. In which situations does the network predict bad? Which are the classes that have poor performance? It makes sense to augment only the situations in which the network poorly performs, those augmented samples would be the ones that would help you most when trying to improve the performance of the network.

An increase in image size may help the network learn small objects better, if the GPU memory allows you this I would resort to this approach. Replace the BatchNormalization() with GroupNormalization() (see tensorflow-addons) as you may have to decrease the batch size for the training to work.

Loss functions. Plain categorical-crossentropy (if multi-class) or binary-crossentropy (if multi-label) may not work that well in case of imbalanced problems. You could potentially use Dice loss or IoU loss; even a combination of those losses with binary/categorical crossentropy.

Last but not least, switching to another backbone (a more powerful feature extractor) could yield an increase in your metrics.

For (1) and example could be:

```<code>    reduce_lr_callback = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1, mode='min')
    ...
    model.fit(....., callbacks = [reduce_lr_callback])
</code>```

Body:
I took the code from this page and made several modifications: https://keras.io/examples/vision/deeplabv3_plus/

One thing I did was add flipping left right augmentation to the dataset:

def image_augmentation(img):
    img = tf.image.random_flip_left_right(img)
    return img

def image_process(path, mask=False):
    img = tf.io.read_file(path)

    if mask == True:
        img = tf.image.decode_png(img, channels=1)
        img.set_shape([None, None, 1])
        img = tf.image.resize(images=img, size=[image_size, image_size])
        img = image_augmentation(img) # <- This is where the augmentation is happening

    else:
        img = tf.image.decode_png(img, channels=3)
        img.set_shape([None, None, 3])
        img = tf.image.resize(images=img, size=[image_size, image_size])
        img = img / 127.5 - 1

    return img

Then I've changed the backend from ResNet50 to ResNet101 but did not alter the convolution block. I've decreased the learning rate from 0.01 to 0.001.

This is the CIHP dataset and I'm basically using the entire dataset for training and not a subset. After 25 epochs, my accuracy is at best 0.76. I've tried other augmentation techniques, such as random cropping, flipping up and down, brightness, etc. but all of them yielded far worse performance.

What are other things I can do to improve the accuracy?

Edit

This is my training code:

loss = keras.losses.SparseCategoricalCrossentropy(from_logits = True)

lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor = 0.1,patience = 5, min_lr=0.0001)

model.compile(optimizer = keras.optimizers.Adam(learning_rate = lr), loss = loss, metrics=["accuracy"],)

history = model.fit(train_dataset, validation_data = val_dataset, epochs = 100)

Body:
I would opt for a learning rate scheduler, so that I do not hold the
learning rate fixed during the entire training phase. You can opt for either a built-in ReduceLROnPlateau() or define your own scheduler.

Error analysis. In which situations does the network predict bad? Which are the classes that have poor performance? It makes sense to augment only the situations in which the network poorly performs, those augmented samples would be the ones that would help you most when trying to improve the performance of the network.

An increase in image size may help the network learn small objects better, if the GPU memory allows you this I would resort to this approach. Replace the BatchNormalization() with GroupNormalization() (see tensorflow-addons) as you may have to decrease the batch size for the training to work.

Loss functions. Plain categorical-crossentropy (if multi-class) or binary-crossentropy (if multi-label) may not work that well in case of imbalanced problems. You could potentially use Dice loss or IoU loss; even a combination of those losses with binary/categorical crossentropy.

Last but not least, switching to another backbone (a more powerful feature extractor) could yield an increase in your metrics.

For (1) and example could be:

    reduce_lr_callback = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1, mode='min')
    ...
    model.fit(....., callbacks = [reduce_lr_callback])


问:
Flutter Show a toast message when navigating to a screen with a condition
I have a login screen and screens after the login, there other screens fetch data. But if something wrong happends with the api i did so it returns the user back to the login after he enters the app if there is a problem with the api for example reponse.statuscode == 401 etc.</p>
```<code>
late Response response2;
String? basicAuth;
TextEditingController phoneNumberController = TextEditingController();
TextEditingController passwordController = TextEditingController();

Future<Response> fetchWorkingLocationData(BuildContext context) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var authorization = prefs.getString('authorization');
  var url = 'https://dev.api.wurk.skyver.co/api/v1/projects';
  basicAuth = 'Basic ' +
      base64Encode(
        utf8.encode('${phoneNumberController.text}:${passwordController.text}'),
      );
  response2 = await http.get(
    Uri.parse(url),
    headers: <String, String>{
      'authorization': authorization ?? basicAuth.toString()
    },
  );
  if (response2.statusCode == 401 || response2.statusCode == 403) {
    Navigator.pushReplacement(
        context, MaterialPageRoute(builder: (context) => const LoginScreen()));
    prefs.remove('authorization');
// here i want to show the toast message after it sends the user to login, and the message is: User data was changed.
  }
  print(response2.statusCode);

  return response2;
}
</code>```

答:
You should be able to show a SnackBar with your message

...
prefs.remove('authorization');
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
  content: Text('User data was changed'),
),);
```

You might have to wrap your Scaffold in a ScaffoldMessenger, but other than that this should work just fine.

More info on how to work with the SnackBar can be found in the docs: https://docs.flutter.dev/cookbook/design/snackbars

Body:
I have a login screen and screens after the login, there other screens fetch data. But if something wrong happends with the api i did so it returns the user back to the login after he enters the app if there is a problem with the api for example reponse.statuscode == 401 etc.

late Response response2;
String? basicAuth;
TextEditingController phoneNumberController = TextEditingController();
TextEditingController passwordController = TextEditingController();

Future<Response> fetchWorkingLocationData(BuildContext context) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var authorization = prefs.getString('authorization');
  var url = 'https://dev.api.wurk.skyver.co/api/v1/projects';
  basicAuth = 'Basic ' +
      base64Encode(
        utf8.encode('${phoneNumberController.text}:${passwordController.text}'),
      );
  response2 = await http.get(
    Uri.parse(url),
    headers: <String, String>{
      'authorization': authorization ?? basicAuth.toString()
    },
  );
  if (response2.statusCode == 401 || response2.statusCode == 403) {
    Navigator.pushReplacement(
        context, MaterialPageRoute(builder: (context) => const LoginScreen()));
    prefs.remove('authorization');
// here i want to show the toast message after it sends the user to login, and the message is: User data was changed.
  }
  print(response2.statusCode);

  return response2;
}

Body:
You should be able to show a SnackBar with your message

...
prefs.remove('authorization');
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
  content: Text('User data was changed'),
),);

You might have to wrap your Scaffold in a ScaffoldMessenger, but other than that this should work just fine.

More info on how to work with the SnackBar can be found in the docs: https://docs.flutter.dev/cookbook/design/snackbars


问:
How to format a long adding thousands separator on Arduino
I'm developing a project on Arduino that parses some JSON data from a remote web API displaying it on a 16x2 LCD.

I would like to format a long parsed with TextFinder adding the thousands separator (a comma separator would be fine).

In a nutshell, how do I code the formatLong function?

```<code>long longToBeFormatted = 32432423;

formattedLong = formatLong(longToBeFormatted); //How to implement this?

lcd.print(formattedLong) // formattedLong is a string
</code>```

答:
Maybe not best algorithm, but here's an implementation example (standard C):</p>

```<code>char* formatLong(long toBeFormatted)
{
    // Get the string representation as is
    char* buffer = (char*) malloc(sizeof(long));
    ltoa(toBeFormatted, buffer, 10);

    // Calculate how much commas there will be
    unsigned int buff_length = strlen(buffer);
    unsigned int num_commas = buff_length / 3;
    unsigned int digits_left = buff_length % 3;
    if (digits_left == 0)
    {
        num_commas--;
    }

    // Allocate space for final string representation
    unsigned int final_length = buff_length + num_commas + 1;
    char* final = (char*) malloc(final_length);
    memset(final, 0, final_length);

    // Parse strings from last to first to count positions
    int final_pos = final_length - 2;
    int buff_pos = buff_length - 1;
    int i = 0;
    while(final_pos >= 0)
    {
        final[final_pos--] = buffer[buff_pos--];
        i++;
        if (i % 3 == 0)
        {
            final[final_pos--] = ',';
        }
    }

    // Free obsolete memory and return buffer
    free(buffer);
    return final;
}
</code>```

Body:
I'm developing a project on Arduino that parses some JSON data from a remote web API displaying it on a 16x2 LCD.

I would like to format a long parsed with TextFinder adding the thousands separator (a comma separator would be fine).

In a nutshell, how do I code the formatLong function?

long longToBeFormatted = 32432423;

formattedLong = formatLong(longToBeFormatted); //How to implement this?

lcd.print(formattedLong) // formattedLong is a string

Body:
Maybe not best algorithm, but here's an implementation example (standard C):

char* formatLong(long toBeFormatted)
{
    // Get the string representation as is
    char* buffer = (char*) malloc(sizeof(long));
    ltoa(toBeFormatted, buffer, 10);

    // Calculate how much commas there will be
    unsigned int buff_length = strlen(buffer);
    unsigned int num_commas = buff_length / 3;
    unsigned int digits_left = buff_length % 3;
    if (digits_left == 0)
    {
        num_commas--;
    }

    // Allocate space for final string representation
    unsigned int final_length = buff_length + num_commas + 1;
    char* final = (char*) malloc(final_length);
    memset(final, 0, final_length);

    // Parse strings from last to first to count positions
    int final_pos = final_length - 2;
    int buff_pos = buff_length - 1;
    int i = 0;
    while(final_pos >= 0)
    {
        final[final_pos--] = buffer[buff_pos--];
        i++;
        if (i % 3 == 0)
        {
            final[final_pos--] = ',';
        }
    }

    // Free obsolete memory and return buffer
    free(buffer);
    return final;
}


问:
Waiting for second key of chord
I have assigned the keyboard shortcut Ctrl+E to a command.  But when I click Ctrl+E, the status bar says Ctrl+E was pressed.  Waiting for the second key of the chord...".

If I hit the Esc key, I get "The key combination (Ctrl+E, Esc) is not a command."

How do I activate the command that has been assigned to Ctrl+E?

I know that this is the same as the question How do you stop Visual Studio from waiting for the second part of a shortcut-combination? . But the answer given there (hit Esc) does not work for me.

答:
Go to Tools -> Options.
A window will open up, In that Environment -> Keyboard -> Keyboard
And Just Press the Reset button on the right.

Screenshot

Title: Waiting for second key of chord