问:
JQuery and Elementor Sticky Header Not Working Properly
Site URL: https://petnotify.sporksquad.com/

I'm building a website for a client, and I built two stacked containers within it. I want only the bottom half with the navbar to be sticky and have the disappear / reappear feature. It works perfectly until I scroll up too quickly and the bottom part overtakes the top container with the logo and social icons. I would love to prevent this from happening and
properly stopping below the top container when you reach the top of the page.

I followed this tutorial and this is my Elementor set-up. The code I used is

```<code><script>

document.addEventListener('DOMContentLoaded', function() {
jQuery(function($) {
    var mywindow = $(window);
    var mypos = mywindow.scrollTop();
    let scrolling = false; /* For throlling scroll event */
    window.addEventListener('scroll', function() {
        scrolling = true;
    });
    setInterval(() => {
        if (scrolling) {
            scrolling = false;
            if (mypos > 20) {
                if (mywindow.scrollTop() > mypos) {
                    $('#stickyheaders').addClass('headerup');
                } else {
                    $('#stickyheaders').removeClass('headerup');
                }
            }
            mypos = mywindow.scrollTop();
        }
    }, 300);
});
});

</script>
<style>
#stickyheaders{
    transition : transform 0.4s ease;
}
.headerup{
    transform: translateY(-20vh); /*adjust this value to the height of your header*/
}
</style>
</code>```

I've tried messing around with the vh for the height of header (each container is 10vh so the header is 20vh). Not sure what else to do as I'm not super familiar with jQuery but I'm sure it's an easy fix.

Body:
Site URL: https://petnotify.sporksquad.com/

I'm building a website for a client, and I built two stacked containers within it. I want only the bottom half with the navbar to be sticky and have the disappear / reappear feature. It works perfectly until I scroll up too quickly and the bottom part overtakes the top container with the logo and social icons. I would love to prevent this from happening and
properly stopping below the top container when you reach the top of the page.

I followed this tutorial and this is my Elementor set-up. The code I used is

I've tried messing around with the vh for the height of header (each container is 10vh so the header is 20vh). Not sure what else to do as I'm not super familiar with jQuery but I'm sure it's an easy fix.


来源: stackexchange

问:
Is there an efficient/analytical solution to find probabilities of each case in a power set?
In my capacity as a design engineer, I needed to size equipment to feed compressed air to a set of dust collectors. These dust collectors require 10 minutes (approximately) of "pulsing" air every few hours to clean the filter medium. The pulses last 0.1 s and they happen every 10 s while the pulsing lasts. The volume of air used during each pulse varies by dust collector. The equipment I am designing will feed many different types of dust collectors in different areas. For example, in one area, equipment might feed 2 dust collectors that each require 3 scf* per pulse, and also feed 1 dust collector that requires 5 scf per pulse. In another area, those numbers will be totally different. I would like to be sure that I design the equipment in every area to handle 99% or 99.9% of cases.

For each area, a power set describes each flow case that I might see. In the simple example above where I only have three dust collectors, the power set is (), (3,), (3,), (5,), (3, 3), (3, 5), (3, 5), (3, 3, 5). I wrote the following code in python. It calculates the probability of each case of the power set, and then selects the case with a total flow under which 99% and 99.9% of flow cases will probably occur. Since I could not figure out an analytical way to solve for the probability of each case, I ended up using a double for-loop over the power set to deal with the probability of each case overlapping with another. This gets really slow for cases with more than about 5 dust collectors.

```<code>import numpy as np
import pandas as pd
from numpy.random import rand
from itertools import chain, combinations

# placeholder array to simulate dust collector flows in an area
flows = np.round(rand(int(np.round(rand() *10, 0))),2)
flows = np.round(rand(7),2)

# aproximate probability that one dust collector will be pulsing at any time
p = 0.0017 # based on 6 pulse/min while pulsing, 10 min pulsing/hr, 0.1 s/pulse

# function to produce a numpy array containing the powerset of actual values
def numPowerset(iterable):
    "numPowerset([1,2,3]) --> [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]"
    s = list(iterable)
    c = list(chain.from_iterable(combinations(s, r) for r in range(len(s) +1)))
    return np.array(c, dtype='object')

# function to produce numpy array containing unique values to represent actuals
def idPowerset(iterable):
    "idPowerset([1,2,3]) --> [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]"
    s = np.linspace(0, len(list(iterable)) -1, len(list(iterable)))
    c = list(chain.from_iterable(combinations(s, r) for r in range(len(s) +1)))
    return np.array(c, dtype='object')

# creating the dataframe where I want to see my results
df = pd.DataFrame(numPowerset(flows), columns=['Num. Combination'])
df['ID Combination'] = idPowerset(flows)

# calculating the probability of each event, inclusive of the probability that
# the event occurs as part of another event (overlapping events)
df['Probability'] = p**df['ID Combination'].str.len()

# removing the probability of overlapping events
for i in reversed(df.index):
    for j in df.index:
        if (np.size(df.loc[j,'ID Combination'])
            <= np.size(df.loc[i,'ID Combination'])):
               pass
        elif (df.loc[i,'ID Combination'] in
              list(idPowerset(df.loc[j,'ID Combination']))):
                df.loc[i,'Probability'] -= df.loc[j,'Probability']

# totalling flows
df['Total Flow'] = list(map(sum, df['Num. Combination']))

# summing probabilities for each possible flow rate
df = df.groupby('Total Flow').sum(numeric_only=True)

# normalizing probability (because I don't really care about the zero flow case)
df.drop(index = 0, inplace=True)
df['Normalized Probability'] = df['Probability']/df['Probability'].sum()

# getting cumulative normalized probability and flows that account for more than most cases
df = df.sort_values('Total Flow').reset_index() # just making sure I get the right value on top
df['Cumulative N. Prob.'] = df['Normalized Probability'].cumsum()
design99 = df[df['Cumulative N. Prob.']>0.99].reset_index().at[0,'Total Flow']
design999 = df[df['Cumulative N. Prob.']>0.999].reset_index().at[0,'Total Flow']

# viewing results
print()
print(df)
print('Sum of probabilities is: %f'%sum(df['Probability']))
print('Sum of normalized probs. is: %f'%sum(df['Normalized Probability']))
print('Design 99% flow is:', design99)
print('Design 99.9% flow is:', design999)
</code>```

I am sure that an analytical solution to this statistical problem would fix the speed issues here. Solutions that improve performance without an analytical solution would also be welcome.

*60°F and 1 atm reference conditions

ContentLicense: CC BY-SA 4.0

Body:
In my capacity as a design engineer, I needed to size equipment to feed compressed air to a set of dust collectors. These dust collectors require 10 minutes (approximately) of "pulsing" air every few hours to clean the filter medium. The pulses last 0.1 s and they happen every 10 s while the pulsing lasts. The volume of air used during each pulse varies by dust collector. The equipment I am designing will feed many different types of dust collectors in different areas. For example, in one area, equipment might feed 2 dust collectors that each require 3 scf* per pulse, and also feed 1 dust collector that requires 5 scf per pulse. In another area, those numbers will be totally different. I would like to be sure that I design the equipment in every area to handle 99% or 99.9% of cases.

For each area, a power set describes each flow case that I might see. In the simple example above where I only have three dust collectors, the power set is (), (3,), (3,), (5,), (3, 3), (3, 5), (3, 5), (3, 3, 5). I wrote the following code in python. It calculates the probability of each case of the power set, and then selects the case with a total flow under which 99% and 99.9% of flow cases will probably occur. Since I could not figure out an analytical way to solve for the probability of each case, I ended up using a double for-loop over the power set to deal with the probability of each case overlapping with another. This gets really slow for cases with more than about 5 dust collectors.

import numpy as np
import pandas as pd
from numpy.random import rand
from itertools import chain, combinations

# placeholder array to simulate dust collector flows in an area
flows = np.round(rand(int(np.round(rand() *10, 0))),2)
flows = np.round(rand(7),2)

# aproximate probability that one dust collector will be pulsing at any time
p = 0.0017 # based on 6 pulse/min while pulsing, 10 min pulsing/hr, 0.1 s/pulse

# function to produce a numpy array containing the powerset of actual values
def numPowerset(iterable):
    "numPowerset([1,2,3]) --> [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]"
    s = list(iterable)
    c = list(chain.from_iterable(combinations(s, r) for r in range(len(s) +1)))
    return np.array(c, dtype='object')

# function to produce numpy array containing unique values to represent actuals
def idPowerset(iterable):
    "idPowerset([1,2,3]) --> [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]"
    s = np.linspace(0, len(list(iterable)) -1, len(list(iterable)))
    c = list(chain.from_iterable(combinations(s, r) for r in range(len(s) +1)))
    return np.array(c, dtype='object')

# creating the dataframe where I want to see my results
df = pd.DataFrame(numPowerset(flows), columns=['Num. Combination'])
df['ID Combination'] = idPowerset(flows)

# calculating the probability of each event, inclusive of the probability that
# the event occurs as part of another event (overlapping events)
df['Probability'] = p**df['ID Combination'].str.len()

# removing the probability of overlapping events
for i in reversed(df.index):
    for j in df.index:
        if (np.size(df.loc[j,'ID Combination'])
            <= np.size(df.loc[i,'ID Combination'])):
               pass
        elif (df.loc[i,'ID Combination'] in
              list(idPowerset(df.loc[j,'ID Combination']))):
                df.loc[i,'Probability'] -= df.loc[j,'Probability']

# totalling flows
df['Total Flow'] = list(map(sum, df['Num. Combination']))

# summing probabilities for each possible flow rate
df = df.groupby('Total Flow').sum(numeric_only=True)

# normalizing probability (because I don't really care about the zero flow case)
df.drop(index = 0, inplace=True)
df['Normalized Probability'] = df['Probability']/df['Probability'].sum()

# getting cumulative normalized probability and flows that account for more than most cases
df = df.sort_values('Total Flow').reset_index() # just making sure I get the right value on top
df['Cumulative N. Prob.'] = df['Normalized Probability'].cumsum()
design99 = df[df['Cumulative N. Prob.']>0.99].reset_index().at[0,'Total Flow']
design999 = df[df['Cumulative N. Prob.']>0.999].reset_index().at[0,'Total Flow']

# viewing results
print()
print(df)
print('Sum of probabilities is: %f'%sum(df['Probability']))
print('Sum of normalized probs. is: %f'%sum(df['Normalized Probability']))
print('Design 99% flow is:', design99)
print('Design 99.9% flow is:', design999)

I am sure that an analytical solution to this statistical problem would fix the speed issues here. Solutions that improve performance without an analytical solution would also be welcome.

*60°F and 1 atm reference conditions


问:
Nodejs Webpack Breaking Change
Error page

I have Uniswap Clone project and when i start the project i get this module error. can someone who knows please help?

Methods I've tried:

*npm audit --fix

*npm install cipher-base

*add webpack.config.js

Error Code:

```<code>Compiled with problems:X

ERROR in ../../node_modules/cipher-base/index.js 2:16-43

Module not found: Error: Can't resolve 'stream' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\cipher-base'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
  - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "stream": false }

ERROR in ../../node_modules/eth-lib/lib/bytes.js 7:193-227

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\eth-lib\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
  - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "crypto": false }

ERROR in ../../node_modules/web3-eth-accounts/lib/index.js 27:74-91

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\web3-eth-accounts\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
  - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "crypto": false }

ERROR in ../../node_modules/web3-eth-accounts/node_modules/eth-lib/lib/bytes.js 5:193-227

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\web3-eth-accounts\node_modules\eth-lib\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
  - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "crypto": false }

ERROR in ../../node_modules/web3-providers-http/lib/index.js 26:11-26

Module not found: Error: Can't resolve 'http' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\web3-providers-http\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
  - install 'stream-http'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "http": false }

ERROR in ../../node_modules/web3-providers-http/lib/index.js 27:12-28

Module not found: Error: Can't resolve 'https' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\web3-providers-http\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "https": require.resolve("https-browserify") }'
  - install 'https-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "https": false }
</code>```

Package.json:

```<code>{
  "name": "@my-app/monorepo",
  "version": "1.0.0",
  "keywords": [
    "ethereum",
    "react",
    "workspaces",
    "yarn"
  ],
  "private": true,
  "scripts": {
    "react-app:build": "yarn workspace @my-app/react-app build",
    "react-app:eject": "yarn workspace @my-app/react-app eject",
    "react-app:ipfs": "yarn workspace @my-app/react-app ipfs",
    "react-app:start": "yarn workspace @my-app/react-app start",
    "react-app:test": "yarn workspace @my-app/react-app test"
  },
  "workspaces": {
    "packages": [
      "packages/*"
    ]
  },
  "resolutions": {
    "react-error-overlay": "6.0.9"
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "assert": "^2.0.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^9.1.0",
    "babel-preset-react": "^6.24.1",
    "buffer": "^6.0.3",
    "crypto-browserify": "^3.12.0",
    "https-browserify": "^1.0.0",
    "os-browserify": "^0.3.0",
    "process": "^0.11.10",
    "react-app-rewired": "^2.2.1",
    "react-scripts": "^5.0.0",
    "stream-browserify": "^3.0.0",
    "stream-http": "^3.2.0",
    "url": "^0.11.0",
    "webpack": "^5.75.0",
    "webpack-config": "^7.0.0",
    "webpack-fix-style-only-entries": "^0.6.1"
  },
  "dependencies": {
    "cipher-base": "^1.0.4",
    "ipfs-deploy": "12.0.1",
    "node-polyfill-webpack-plugin": "^2.0.1",
    "swr": "^2.0.0",
    "util": "^0.12.5"
  }
}
</code>```

I tried the solutions on sites such as overflow, but I could not find the solution.

Title: Nodejs Webpack Breaking Change

Body:
Error page

I have Uniswap Clone project and when i start the project i get this module error. can someone who knows please help?

Methods I've tried:

*npm audit --fix

*npm install cipher-base

*add webpack.config.js

Error Code:

Compiled with problems:X

ERROR in ../../node_modules/cipher-base/index.js 2:16-43

Module not found: Error: Can't resolve 'stream' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\cipher-base'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
  - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "stream": false }

ERROR in ../../node_modules/eth-lib/lib/bytes.js 7:193-227

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\eth-lib\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
  - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "crypto": false }

ERROR in ../../node_modules/web3-eth-accounts/lib/index.js 27:74-91

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\web3-eth-accounts\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
  - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "crypto": false }

ERROR in ../../node_modules/web3-eth-accounts/node_modules/eth-lib/lib/bytes.js 5:193-227

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\web3-eth-accounts\node_modules\eth-lib\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
  - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "crypto": false }

ERROR in ../../node_modules/web3-providers-http/lib/index.js 26:11-26

Module not found: Error: Can't resolve 'http' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\web3-providers-http\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
  - install 'stream-http'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "http": false }

ERROR in ../../node_modules/web3-providers-http/lib/index.js 27:12-28

Module not found: Error: Can't resolve 'https' in 'C:\Users\Asus\Desktop\nzl swap 1.0\my-eth-app\node_modules\web3-providers-http\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
  - add a fallback 'resolve.fallback: { "https": require.resolve("https-browserify") }'
  - install 'https-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
  resolve.fallback: { "https": false }

Package.json:

{
  "name": "@my-app/monorepo",
  "version": "1.0.0",
  "keywords": [
    "ethereum",
    "react",
    "workspaces",
    "yarn"
  ],
  "private": true,
  "scripts": {
    "react-app:build": "yarn workspace @my-app/react-app build",
    "react-app:eject": "yarn workspace @my-app/react-app eject",
    "react-app:ipfs": "yarn workspace @my-app/react-app ipfs",
    "react-app:start": "yarn workspace @my-app/react-app start",
    "react-app:test": "yarn workspace @my-app/react-app test"
  },
  "workspaces": {
    "packages": [
      "packages/*"
    ]
  },
  "resolutions": {
    "react-error-overlay": "6.0.9"
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "assert": "^2.0.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^9.1.0",
    "babel-preset-react": "^6.24.1",
    "buffer": "^6.0.3",
    "crypto-browserify": "^3.12.0",
    "https-browserify": "^1.0.0",
    "os-browserify": "^0.3.0",
    "process": "^0.11.10",
    "react-app-rewired": "^2.2.1",
    "react-scripts": "^5.0.0",
    "stream-browserify": "^3.0.0",
    "stream-http": "^3.2.0",
    "url": "^0.11.0",
    "webpack": "^5.75.0",
    "webpack-config": "^7.0.0",
    "webpack-fix-style-only-entries": "^0.6.1"
  },
  "dependencies": {
    "cipher-base": "^1.0.4",
    "ipfs-deploy": "12.0.1",
    "node-polyfill-webpack-plugin": "^2.0.1",
    "swr": "^2.0.0",
    "util": "^0.12.5"
  }
}

I tried the solutions on sites such as overflow, but I could not find the solution.


问:
MySQL connecting to PythonAnywhere error 2003
I'm using pycharm. I already have the SSH tunnel, I just need to connect it but i always get the same error:

import mysql.connector

cnx = mysql.connector.connect(
    host="i know it.mysql.eu.pythonanywhere-services.com",
    user="i know it",
    port=3306,
    password="i know it",
    database="i know it"
)

```
<p>Error:</p>
```mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '%-.100s:%u' (%s) (Warning: %u format: a real number is required, not str)

```

Body:
I'm using pycharm. I already have the SSH tunnel, I just need to connect it but i always get the same error:

import mysql.connector

cnx = mysql.connector.connect(
    host="i know it.mysql.eu.pythonanywhere-services.com",
    user="i know it",
    port=3306,
    password="i know it",
    database="i know it"
)

Error:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '%-.100s:%u' (%s) (Warning: %u format: a real number is required, not str)


问:
Integrate Visual studio code with selenium Web driver into Azure DevOps
I learned testing scripts selenium web driver with java in Visual studio code
But now i want to connect or integrate Visual studio code into Azure DevOpS to perform Automation testing.

Can anyone please help me out


问:
How to use IAM roles attached to AWS Cognito user pool groups with Identity pools
I have a cognito user pool with many groups. Each group is associated with an IAM role. A user in the pool can be a member of more than one group. I also have an identity pool for which the cognito user pool is the identity provider. The problem I'm running into has two parts.

I am unable to use the precedence ordering for the group roles. This is because the IAM roles have different permissions and there is no point in ordering them. A user will select the group/role that they want to use which rules out any system for ranking them. This rules out using the cognito:preferred_role field in the identity token.

2)I then looked at using the rule based mappings in conjunction with a custom attribute. This way a role could be specified in the custom attribute and then the token could be regenerated. However, the rule based mapping only allows 25 rules per identity pool and this is not nearly enough for our the number of groups/roles.

Lastly, I looked at using the CustomRoleArn parameter in the GetCredentialsForIdentity API method. When using it I got an error saying "An error occurred (InvalidParameterException) when calling the GetCredentialsForIdentity operation: Only SAML providers and providers with RoleMappings support custom role ARN". This brings us back to the 25 rule limit.

So is there a way to specify an IAM role for and authenticated user to assume that isn't some obtuse ordering system or limited by the number of rules I can use?


问:
mlflow: INVALID_PARAMETER_VALUE Parameters can not be modified after a value is set
I get the following exception raised, help me please

```<code>mlflow.exceptions.RestException: INVALID_PARAMETER_VALUE: Response:
{
  'Error': {
    'Code': 'ValidationError',
    'Severity': None,
    'Message': 'Parameters can not be modified after a value is set.',
    'MessageFormat': None,
    'MessageParameters': None,
    'ReferenceCode': None,
    'DetailsUri': None,
    'Target': None,
    'Details': [],
    'InnerError': None,
    'DebugInfo': None,
    'AdditionalInfo': None
  },
  'Correlation': {
    'operation': '13b09a7297c0e920a41eeaa728c4cb4e',
    'request': 'ae8a75a01a168e65'
  },
  'Environment': 'westeurope',
  'Location': 'westeurope',
  'Time': '2022-12-22T23:37:07.4626959+00:00',
  'ComponentName': 'mlflow',
  'error_code': 'INVALID_PARAMETER_VALUE'
}
</code>```

my code pretty much looks like this

```<code>mlflow.start_run()
mlflow.log_params({'key1':1, 'key2':2})
mlflow.log_param('key3', 3) //Exception raised
</code>```

PS: the mlflow version  i am using is 2.1.0

Body:
I get the following exception raised, help me please

mlflow.exceptions.RestException: INVALID_PARAMETER_VALUE: Response:
{
  'Error': {
    'Code': 'ValidationError',
    'Severity': None,
    'Message': 'Parameters can not be modified after a value is set.',
    'MessageFormat': None,
    'MessageParameters': None,
    'ReferenceCode': None,
    'DetailsUri': None,
    'Target': None,
    'Details': [],
    'InnerError': None,
    'DebugInfo': None,
    'AdditionalInfo': None
  },
  'Correlation': {
    'operation': '13b09a7297c0e920a41eeaa728c4cb4e',
    'request': 'ae8a75a01a168e65'
  },
  'Environment': 'westeurope',
  'Location': 'westeurope',
  'Time': '2022-12-22T23:37:07.4626959+00:00',
  'ComponentName': 'mlflow',
  'error_code': 'INVALID_PARAMETER_VALUE'
}

my code pretty much looks like this

mlflow.start_run()
mlflow.log_params({'key1':1, 'key2':2})
mlflow.log_param('key3', 3) //Exception raised

PS: the mlflow version  i am using is 2.1.0


问:
Im getting nosuchmethoderror tried calling []("id")
```<code>ListTile(
  leading: Icon(Icons.person),
  title: const Text('Profilim'),
  onTap: () async {
    print("aaaaaaa");
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => profile(gelenid : widget.gelenid)),
    );
  },
),
</code>```

When I press this button im gettin nosuchmethoderror and I have this code in profile.dart

```<code>import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:personal_planner/update.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class profile extends StatefulWidget {
  const profile({this.gelenid});
  final gelenid;

  @override
  State<profile> createState() => _profileState();
}
class _profileState extends State<profile> {

  var satir;
  dbGoster() async {
    Directory klasor = await getApplicationDocumentsDirectory();
    String veritabyolu = join(klasor.path, "personal.sqlite");
    Database db = await openDatabase(veritabyolu);
    if (await databaseExists(veritabyolu)){
      print("Var");

      List<Map<String,dynamic>> maps=await db.rawQuery("SELECT * FROM personals WHERE id = ?" ,[widget.gelenid.toString()]);
      List.generate(maps.length, (index) {
        satir=maps[index];
      });}  else {
      print("Veri tabanı yok");
    };
  }
  @override
  Widget build(BuildContext context) {
    dbGoster();

    return Scaffold(
        appBar: AppBar(
          title: Text("Profilim"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("ID=>"+satir["id"].toString()),
              Text("TC Kimlik=>"+satir["tc"].toString()),
              Text("İsim=>"+satir["isim"]),
              Text("Soyisim=>"+satir["soyisim"]),
              Text("Sifre=>"+satir["sifre"]),
              Text("Medeni=>"+satir["medeni"].toString() ),
              Text("İlgi Alanları=>"+satir["ilgialan"].toString()),
              Text("Ehliyet=>"+satir["ehliyet"].toString()),
              ElevatedButton(onPressed: (){
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => update(gelenid : widget.gelenid)),
                );
              }, child: Text("Güncellemek için bas!")),

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

I tried every possible what I know and found but I couldn't fix.

I think the sql query must be do first but I tried initstate etc.

I tried if else statement in children  for text widget but it couldn't help

Except this-> When I press button I got nosuchmethoderror but if I do hotreload page comes on my phone

Body:
ListTile(
  leading: Icon(Icons.person),
  title: const Text('Profilim'),
  onTap: () async {
    print("aaaaaaa");
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => profile(gelenid : widget.gelenid)),
    );
  },
),

When I press this button im gettin nosuchmethoderror and I have this code in profile.dart

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:personal_planner/update.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class profile extends StatefulWidget {
  const profile({this.gelenid});
  final gelenid;

  @override
  State<profile> createState() => _profileState();
}
class _profileState extends State<profile> {

  var satir;
  dbGoster() async {
    Directory klasor = await getApplicationDocumentsDirectory();
    String veritabyolu = join(klasor.path, "personal.sqlite");
    Database db = await openDatabase(veritabyolu);
    if (await databaseExists(veritabyolu)){
      print("Var");

      List<Map<String,dynamic>> maps=await db.rawQuery("SELECT * FROM personals WHERE id = ?" ,[widget.gelenid.toString()]);
      List.generate(maps.length, (index) {
        satir=maps[index];
      });}  else {
      print("Veri tabanı yok");
    };
  }
  @override
  Widget build(BuildContext context) {
    dbGoster();

    return Scaffold(
        appBar: AppBar(
          title: Text("Profilim"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("ID=>"+satir["id"].toString()),
              Text("TC Kimlik=>"+satir["tc"].toString()),
              Text("İsim=>"+satir["isim"]),
              Text("Soyisim=>"+satir["soyisim"]),
              Text("Sifre=>"+satir["sifre"]),
              Text("Medeni=>"+satir["medeni"].toString() ),
              Text("İlgi Alanları=>"+satir["ilgialan"].toString()),
              Text("Ehliyet=>"+satir["ehliyet"].toString()),
              ElevatedButton(onPressed: (){
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => update(gelenid : widget.gelenid)),
                );
              }, child: Text("Güncellemek için bas!")),

            ],
          ),
        ),
    );
  }
}

I tried every possible what I know and found but I couldn't fix.

I think the sql query must be do first but I tried initstate etc.

I tried if else statement in children  for text widget but it couldn't help

Except this-> When I press button I got nosuchmethoderror but if I do hotreload page comes on my phone


问:
B-tree algorithm of child splitting
I am trying to implement a B-tree, however I have trouble grasping the proper insertion algorithm.
I am trying to make one with pre-emptive splitting of nodes.
Here is what I have figured so far in steps:

Splitting:

Begin splitting node N with parent P

Allocate a new node K

Copy all the keys from N from middle index (MaxKeys / 2 + 1) to the end, to K

Copy all the children from N from middle index (MaxKeys / 2 + 1) to the end, to K

Remove the right half of the keys and children in N

Inserting into P after split:

Get the middle key (at index MaxKeys / 2) of N

Find the index I of the first key in P that is larger than the found key in step 1

Shift all keys of P from index I, to the right

Shift all keys of P from index I + 1, to the right

Set the key of P at the middle index to the key of N from step 1

Set child of P at the index I + 1 to null

Finishing:

Set the child of P at index one step right of the ndex of N from step 1, to the new node K

My questions are:

Should I somehow check which side I should be moving keys and children, since it's not going to be always on the right side?

If I have to split the root, I must have a special case since then there is no parent node P, or is there a way to handle it in a generalized manner?

Title: B-tree algorithm of child splitting


问:
I'm creating a quiz application .on result screen i wanted to use two Lottie animation which switch according to score user
I'm creating a quiz application .on result screen i wanted to use two Lottie animation which switch according to score user.
im wanted to use if statement for switching 2 lottie animations if user get less score then fail animation shows and if passes congrats animation shows.
the result score in coming from questionsActivity through Intent to ScoreActivity.and i also dont know how to use that data which is coming from previous screen through intent for making decision for showing Lottie animations.
can anyone help me out how can i do this kind of stuff
this is what i do</p>
```<code></code>```
```<code>public class ScoreActivity extends AppCompatActivity {
    LottieAnimationView lottieAnimationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
        loadAds();

        TextView scored = findViewById(R.id.scored);
        TextView total = findViewById(R.id.total);
        Button doneBtn = findViewById(R.id.done_btn);
        lottieAnimationView = findViewById(R.id.animationView);

        scored.setText(String.valueOf(getIntent().getIntExtra("score", 0)));
        total.setText(" / " + getIntent().getIntExtra("total", 0));
        doneBtn.setOnClickListener(view -> finish());
        lottieAnimationView.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                if (
                lottieAnimationView.setTextDelegate(String.valueOf(getIntent().getIntExtra("score")));)
            }

            @Override
            public void onAnimationEnd(Animator animator) {

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        lottieAnimationView.setAnimation("trophy.json");

    }

    private void loadAds() {
        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(LoadAdError adError) {
                // Code to be executed when an ad request fails.
                AdRequest adRequest = new AdRequest.Builder().build();
                mAdView.loadAd(adRequest);
            }
        });

    }

}
</code>```
```<code>
</code>```

Body:
I'm creating a quiz application .on result screen i wanted to use two Lottie animation which switch according to score user.
im wanted to use if statement for switching 2 lottie animations if user get less score then fail animation shows and if passes congrats animation shows.
the result score in coming from questionsActivity through Intent to ScoreActivity.and i also dont know how to use that data which is coming from previous screen through intent for making decision for showing Lottie animations.
can anyone help me out how can i do this kind of stuff
this is what i do

public class ScoreActivity extends AppCompatActivity {
    LottieAnimationView lottieAnimationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
        loadAds();

        TextView scored = findViewById(R.id.scored);
        TextView total = findViewById(R.id.total);
        Button doneBtn = findViewById(R.id.done_btn);
        lottieAnimationView = findViewById(R.id.animationView);

        scored.setText(String.valueOf(getIntent().getIntExtra("score", 0)));
        total.setText(" / " + getIntent().getIntExtra("total", 0));
        doneBtn.setOnClickListener(view -> finish());
        lottieAnimationView.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                if (
                lottieAnimationView.setTextDelegate(String.valueOf(getIntent().getIntExtra("score")));)
            }

            @Override
            public void onAnimationEnd(Animator animator) {

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        lottieAnimationView.setAnimation("trophy.json");

    }

    private void loadAds() {
        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(LoadAdError adError) {
                // Code to be executed when an ad request fails.
                AdRequest adRequest = new AdRequest.Builder().build();
                mAdView.loadAd(adRequest);
            }
        });

    }

}


问:
How to reset a cloud Postgres DB as if it was just created before each demo deployment?
I was using Heroku for projects in development.

Heroku has a great option to reset Postgres DB: https://devcenter.heroku.com/articles/managing-heroku-postgres-using-cli#pg-reset.

Now I'm using other cloud services for Postgres hosting which don't have such feature.

Since during the development phases the DB can change considerably I would like to automatically reset the DB during each deployment before being filled again by my new code.

How do I reset the DB (as if it was just created) if the hosting doesn't provide me a CLI/API to do it but only a web interface and of course the connection string?


问:
Blogger Dynamic Thumbnail Image Caption
I want to make a dynamic caption for the thumbnail image which will be from the first image alt or title. what is the code for that for Blogger?</p>

Title: Blogger Dynamic Thumbnail Image Caption


问:
How to elasticsearch-js selecting specific fields, grouping them, and flattening the results?
In Oracle, if I get duplicate rows I can use grouping to collapse the duplicates into one row.  How would I go about doing this in elasticsearch - particularly, using elasticsearch-js.

I have been tinkering with queries in Kibana, but the output is pretty ugly.

See the following query:

Here is the raw output:

Here is the grouped data:

Notice how id is nested in buckets[x].key.  For example - 27480140.

But custPoNumber is nested inside that with a buckets array of size 1 - which I then have to look inside its buckets[y].key to get.

It would be nice if I could flatten this back out so the output looks like the raw output again.  Especially since parsing this is going to be a pain when I add more aggregations (I need to select, group, and flatten least 20 more fields - where there are about 60 fields total).

Is there a better way to select only specific fields from the index, group the results, and flatten them out?

A solution in JSON for Kibana would be nice, but especially a way to do it in elasticsearch-js for Node.

Thanks!!!


问:
Obtain the current logged e-mail address and send an e-mail
MY GOAL: Get the current logged email to use as "to" in mail() function to send an email.

THE MAIN PROBLEM:

The email value I get I get it correctly, but it doesn't seem to be in string format, so the code fails and I get this in my apache logs:

Got error 'PHP message: PHP Warning:  strpos() expects parameter 1 to be string, object given in /mypath/wp-content/plugins/manage-notification-emails/modules/custom-recipients.php on line 81 and PHP message: PHP Warning:  explode() expects parameter 2 to be string, object given in /mypath/wp-includes/pluggable.php on line 226

So I decided to convert that value to string using (string) or strval() function, but I get this in my apache logs:

Got error 'PHP message: PHP Recoverable fatal error:  Object of class WP_User could not be converted to string in /mypath

HOW I'M GETTING THE EMAIL: I'm using $current_user = wp_get_current_user();. And this contains an object:

```<code>{
    "ID": "155",
    "user_login": "AlexTec",
    "user_pass": "XXXXXXXXXXXXXXXXXXXXXX",
    "user_nicename": "alextec",
    "user_email": "alex@glab360.com",
    "user_url": "http://glab360.com",
    "user_registered": "2022-02-01 08:16:43",
    "user_activation_key": "1663934936:$P$BOwE7xoTKh.hXDHesANXZRenp15c2c0",
    "user_status": "0",
    "display_name": "Alex"
}
</code>```

So if I want to get the email, I just need to use: $current_user = wp_get_current_user()->user_email;, but this doesn't work and I get my first log output I showed you in "THE MAIN PROBLEM".

I checked it with JavaScript using typeof() and appears that the email is an string.

A curious fact is that for example, if I get the name using $current_user = wp_get_current_user()->display_name;, I have 0 problems and I get no errors.

The code crashes exactly when I try to assign the email to $to variable, just like this:

```<code>$to = $current_user;
$headers = array('Content-Type: text/html; charset=utf-8');
$subject = 'This is just a test';
$message = 'Hello';
wp_mail( $to, $subject, $message, $headers );
</code>```

If I replace $to = $current_user; for $to = "stringemail@gmail.com"; it works everything perfect and I get no errors in my logs and the email is delivered.

Someone can help me? I'm getting crazy

Body:
MY GOAL: Get the current logged email to use as "to" in mail() function to send an email.

THE MAIN PROBLEM:

The email value I get I get it correctly, but it doesn't seem to be in string format, so the code fails and I get this in my apache logs:

Got error 'PHP message: PHP Warning:  strpos() expects parameter 1 to be string, object given in /mypath/wp-content/plugins/manage-notification-emails/modules/custom-recipients.php on line 81 and PHP message: PHP Warning:  explode() expects parameter 2 to be string, object given in /mypath/wp-includes/pluggable.php on line 226

So I decided to convert that value to string using (string) or strval() function, but I get this in my apache logs:

Got error 'PHP message: PHP Recoverable fatal error:  Object of class WP_User could not be converted to string in /mypath

HOW I'M GETTING THE EMAIL: I'm using $current_user = wp_get_current_user();. And this contains an object:

{
    "ID": "155",
    "user_login": "AlexTec",
    "user_pass": "XXXXXXXXXXXXXXXXXXXXXX",
    "user_nicename": "alextec",
    "user_email": "alex@glab360.com",
    "user_url": "http://glab360.com",
    "user_registered": "2022-02-01 08:16:43",
    "user_activation_key": "1663934936:$P$BOwE7xoTKh.hXDHesANXZRenp15c2c0",
    "user_status": "0",
    "display_name": "Alex"
}

So if I want to get the email, I just need to use: $current_user = wp_get_current_user()->user_email;, but this doesn't work and I get my first log output I showed you in "THE MAIN PROBLEM".

I checked it with JavaScript using typeof() and appears that the email is an string.

A curious fact is that for example, if I get the name using $current_user = wp_get_current_user()->display_name;, I have 0 problems and I get no errors.

The code crashes exactly when I try to assign the email to $to variable, just like this:

$to = $current_user;
$headers = array('Content-Type: text/html; charset=utf-8');
$subject = 'This is just a test';
$message = 'Hello';
wp_mail( $to, $subject, $message, $headers );

If I replace $to = $current_user; for $to = "stringemail@gmail.com"; it works everything perfect and I get no errors in my logs and the email is delivered.

Someone can help me? I'm getting crazy


问:
How to return VBA macro output when IEEE xplore search columns are inconsistent?
My macro works for a good chunk of the team wants, but the problem arises when certain columns don't generate in the same order.

You can test this on any IEEE Xplore advanced search URL (no institutional signup or even personal login is needed for this) such as this (this link automatically selects Per page = 100 to generate at least 100 results)

(You can optionally substitute another source for initial output if you prefer: In the Chrome Dev Tools > Network tab, sort the left-hand column Name parameters, click the one called "source" then select cURL as Bash and export to http://konklone.io/json/ or similar to generate a CSV containing all 100 rows allowed so you're starting with what I provide here for what Excel VBA needs. You can press Ctrl+R to Reload if the Name columns aren't showing what I have here.)

Some of the authors' values (names and partial IEEE path URLs) are generated and the macro generates a new first spreadsheet tab Destination which populates those (replacing the authors/0 id, authors/1 id, values in the column and inserts a hyperlink for those values so the author names hyperlink to the actual IEEE profile). But it seems to break down after the first few author columns (I see the author names but nothing hyperlinks after that point). Clearly, the columns must change sometimes after a given Network > Konklone output and now the macro can't match the right hyperlinks and names. This problem also happens occasionally with some Network/Konklone output columns further to the right. I just need the author (id/0, /1, /2 to the end) links and articles links (documentLink is one URL/value for each row of authors). The good news is the header row of the Network/Konklone output is consistent regardless of how many rows of results shown, so is there a way to exclude generating hyperlinks where no corresponding URL exists in the corresponding offset column/row? (I've read a little about Step -1 as a way to iterate through the first row so one can identify the row headings across the columns, but that is far above my VBA skillset.) Don't assume I'm very good so fine to spell out a solution for a noob! Many thanks in advance!

```<code>Sub DOoNOToUSEoIEEEAdvancedSearchReformat()
'starting from a page like https://ieeexplore.ieee.org/search/searchresult.jsp?action=search&matchBoolean=true&queryText=(%22All%20Metadata%22:cuda)%20AND%20(%22All%20Metadata%22:gpu)%20NOT%20(%22Author%20Affiliations%22:nvidia)&highlight=true&returnType=SEARCH&matchPubs=true&rowsPerPage=100&searchWithin=speed&returnFacets=ALL&pageNumber=1
'export it using JSON per How to do IEEExplore Advanced (Network console JSON to Excel).docx

Dim a As Long, i As Long, j As Long, LC As Long, LR As Long, z As Long
Dim cell As Range, M As Range, OneRange As Range, SortCell As Range
Dim celltourl As String, unlinked As String
Dim ws As Worksheet, wd As Worksheet, wa As Worksheet

If ActiveWorkbook.Name = ThisWorkbook.Name Then 'you are in the wrong file because the macro is not stored in the exported IEEExplore file
    MsgBox ("You do not have the IEEExplore Excel file generated by Konklone selected in the foreground. Also make sure:" & vbNewLine & _
    "1) column headings row is the 1st row" & vbNewLine & _
    "2) you didn't delete any other rows copied from Konklone" & vbNewLine & _
    "Then re-run macro by selecting View --> Macros --> View Macros --> select IEEEAdvSearchReformat macro --> Run.")
    Exit Sub
ElseIf ActiveSheet.Cells(1, 1).Value2 <> "authors/0/preferredName" Then
    MsgBox "It appears you have some extra rows above the column headings row, or maybe extra columns preceding Candidate Name. Please delete those then re-run macro."
    Exit Sub

Else
'Copy first sheet to a new sheet per https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.copy
    Set ws = ActiveSheet
'we will rename its tab later:   ws.Name = "IEEExploreSearchResultCleaned"
    Sheets.Add 'if no argument provided, Excel uses the default values and adds 1 worksheet before the active sheet, and now it is the active sheet
    Set wd = ActiveSheet 'provides a short variable reference to this sheet going forward
    wd.Name = "Destination" 'name its tab as well

'turn off screen updating and unfreeze all worksheets
Application.ScreenUpdating = False
For Each wa In Application.ActiveWorkbook.Worksheets
    wa.Activate
    With Application.ActiveWindow
        .FreezePanes = False
    End With
Next

ws.Activate 'make orig sheet active again before the next code section

'delete all columns containing these strings in the header row
'below adapted from https://www.extendoffice.com/documents/excel/3086-excel-delete-columns-based-on-header.html
Dim xFNum, xFFNum, xCount As Integer
Dim xStr As String
Dim xArrName As Variant
Dim MR, xRg As Range
On Error Resume Next
Set MR = Range("A1:CP1")
xArrName = Array("preferredName", "*/normalizedName", "patentCitation*", "accessType*", "publicationNumber", "articleNumber", "doi", "isNumber", "showHtml", "showAlgorithm", _
"showDataset", "showVideo", "ephemera", "vj", "rightsLink", "rightslinkFlag", "pdfSize", "startPage", "endPage", "publicationDate", "htmlLink", "publisher", "showCheckbox", "redline", "handleProduct", "highlightedTitle", "publicationTitle", _
"pdfLink", "articleContentType", "isStandard", "isConference", "isJournalAndMagazine", "isEarlyAccess", "isMagazine", "isJournal", "isBook", "course", "displayContentType", "docIdentifier", "isBookWithoutChapters", "volume", "issue", "majorTopic")
'enclose each column name (or partial name with wildcard to use with Like below) with quotes and separate by comma
'alternatively, have the array contain only substrings and surround with wildcards, e.g., .Range.Replace "*" & Array(i) & "*",
xCount = MR.Count
xStr = xArrName(xFNum)
For xFFNum = xCount To 1 Step -1
Set xRg = MR(1, xFFNum)
For xFNum = 0 To UBound(xArrName)
xStr = xArrName(xFNum)
If xRg.Value Like xStr Then xRg.EntireColumn.Delete
Next xFNum
Next

'only one not working is the articleTitle isn't hyperlinking in the test sheet (which means URL won't carry over to Destination Col A either

On Error Resume Next
Set M = Range("A1:AR1") 'AR is authors/7/id column
For i = 1 To M.Count
    If Cells(1, i).Value Like "*/id" Then 'i is an author column number
    For j = 2 To Cells(Rows.Count, i).End(xlUp).Row 'last non-blank cell in column i
        celltourl = Cells(j, i).Value
        'another way: If Not IsEmpty(Cells(j, i).Value)
        If celltourl <> "" Then
        Cells(j, i).Value = "https://ieeexplore.ieee.org/author/" + celltourl 'prepend to row j value
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(j, i).Offset(0, -1), Address:=Cells(j, i).Value
        End If 'for inner If celltourl
    Next j 'done with authors
    ElseIf Cells(1, i).Value Like "documentLink" Then 'i is an article link column number, ie documentLink
    For j = 2 To Cells(Rows.Count, i).End(xlUp).Row 'last non-blank cell in column i
        celltourl = Cells(j, i).Value
        If celltourl <> "" Then
        Cells(j, i).Value = "https://ieeexplore.ieee.org" + celltourl 'prepend to row j value
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(j, i).Offset(0, 3), Address:=Cells(j, i).Value 'add URL to articleTitle 3 cols to the right
        End If 'for inner If celltourl
    Range("U1:U101").Copy wd.Range("A1:A101") 'was col AL, now col U; copy/paste article links to Dest tab col A
    Next j 'done with article title/link
    ElseIf Cells(1, i).Value Like "publicationLink" Then 'i is pub link column number, ie PublicationLink
    For j = 2 To Cells(Rows.Count, i).End(xlUp).Row 'last non-blank cell in column i
        celltourl = Cells(j, i).Value
        If celltourl <> "" Then
        Cells(j, i).Value = "https://ieeexplore.ieee.org" + celltourl 'prepend to row j value
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(j, i).Offset(0, 5), Address:=Cells(j, i).Value 'add URL to displayPublicationTitle 5 cols to the right
        End If 'for inner If celltourl
    Next j 'done with publication title/link
    ElseIf Cells(1, i).Value Like "citationsLink" Then 'i is citations link column number, ie citationsLink
    For j = 2 To Cells(Rows.Count, i).End(xlUp).Row 'last non-blank cell in column i
        celltourl = Cells(j, i).Value
        If celltourl <> "" Then
        Cells(j, i).Value = "https://ieeexplore.ieee.org" + celltourl 'prepend to row j value
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(j, i).Offset(0, -4), Address:=Cells(j, i).Value 'add URL to citationCount 4 cols to the left
        End If 'for inner If celltourl
    Next j 'done with citation count/link
    End If 'done with link columns, now copy special columns to new locations on Destination tab
Next i
'    Range("U1:U101").Copy wd.Range("A1:A101") 'as col AL, now col U; copy/paste article links to Dest tab col A
    Range("AB1:AB101").Copy wd.Range("B1:B101") 'copy/paste abstract text to Dest tab col B
    Range("T1:T101").Copy wd.Range("C1:C101") 'copy/paste citation links to Dest tab col C
    Range("S1:S101").Copy wd.Range("D1:D101") 'copy/paste pub year to Dest tab col D
    Range("AA1:AA101").Copy wd.Range("E1:E101") 'copy/paste publication links to Dest tab col E
    Range("D1:D101").Copy wd.Range("F1:F101") 'copy/paste author 0 to Dest tab
    Range("H1:H101").Copy wd.Range("G1:G101") 'copy/paste author 1 to Dest tab
    Range("L1:L101").Copy wd.Range("H1:H101") 'copy/paste author 2 to Dest tab
    Range("P1:P101").Copy wd.Range("I1:I101") 'copy/paste author 3 to Dest tab
    Range("AE1:AE101").Copy wd.Range("J1:J101") 'copy/paste author 4 to Dest tab
    Range("AI1:AI101").Copy wd.Range("K1:K101") 'copy/paste author 5 to Dest tab
    Range("AM1:AM101").Copy wd.Range("L1:L101") 'copy/paste author 6 to Dest tab
    Range("AQ1:AQ101").Copy wd.Range("M1:M101") 'copy/paste author 7 to Dest tab

wd.Activate 'bring focus to Destination worksheet
'below works, but don't need it because above just copying over certain columns
'ws.Range("A1:AQ101").Copy wd.Range("E1:AS101") 'don't need to copy over all other columns, just leave them on ws tab for referennce
'On Error Resume Next
'Dim xFNumy, xFFNumy, xCounty As Integer
'Dim xStry As String
'Dim xArrNamey As Variant
'Dim MRy, xRgy As Range
'Set MRy = Range("A1:AS1")
'xArrNamey = Array("authors/0/preferredName", "*/firstName", "*/lastName", "*/id") 'delete some columns on wd, but keep on ws
'xCounty = MRy.Count
'xStry = xArrNamey(xFNumy)
'For xFFNumy = xCounty To 1 Step -1
'Set xRgy = MRy(1, xFFNumy)
'For xFNumy = 0 To UBound(xArrNamey)
'xStry = xArrNamey(xFNumy)
'If xRgy.Value Like xStry Then xRgy.EntireColumn.Delete
'If xRgy.Value Like "*/searchablePreferredName" Then xRgy.ColumnWidth = 20
'Next xFNumy
'Next

wd.Columns("A:B").ColumnWidth = 25 'increase width in artTitle, abstract cols
wd.Columns("C").ColumnWidth = 10 'increase width in citationCount col
wd.Columns("D").ColumnWidth = 4 'decrease width in Pub year col
wd.Columns("E").ColumnWidth = 18 'increase width in Pub title col
wd.Columns("F:I").ColumnWidth = 15 'increase width in first 4 author columns
wd.Columns("J:M").ColumnWidth = 10 'increase width in last 4 author columns
Application.GoTo Reference:=Range("A2") 'go to cell A2
'replicating what Freeze Panes --> Freeze Top Row does, per https://stackoverflow.com/questions/34094445/excel-vba-freeze-pane-without-select
With ActiveWindow
    If .FreezePanes Then .FreezePanes = False
    .SplitColumn = 0
    .SplitRow = 1
    .FreezePanes = True
End With

End If 'this is for the end of entire macro
Application.GoTo Reference:=wd.Range("A2")
Application.ScreenUpdating = True
End Sub

</code>```

Body:
My macro works for a good chunk of the team wants, but the problem arises when certain columns don't generate in the same order.

You can test this on any IEEE Xplore advanced search URL (no institutional signup or even personal login is needed for this) such as this (this link automatically selects Per page = 100 to generate at least 100 results)

(You can optionally substitute another source for initial output if you prefer: In the Chrome Dev Tools > Network tab, sort the left-hand column Name parameters, click the one called "source" then select cURL as Bash and export to http://konklone.io/json/ or similar to generate a CSV containing all 100 rows allowed so you're starting with what I provide here for what Excel VBA needs. You can press Ctrl+R to Reload if the Name columns aren't showing what I have here.)

Some of the authors' values (names and partial IEEE path URLs) are generated and the macro generates a new first spreadsheet tab Destination which populates those (replacing the authors/0 id, authors/1 id, values in the column and inserts a hyperlink for those values so the author names hyperlink to the actual IEEE profile). But it seems to break down after the first few author columns (I see the author names but nothing hyperlinks after that point). Clearly, the columns must change sometimes after a given Network > Konklone output and now the macro can't match the right hyperlinks and names. This problem also happens occasionally with some Network/Konklone output columns further to the right. I just need the author (id/0, /1, /2 to the end) links and articles links (documentLink is one URL/value for each row of authors). The good news is the header row of the Network/Konklone output is consistent regardless of how many rows of results shown, so is there a way to exclude generating hyperlinks where no corresponding URL exists in the corresponding offset column/row? (I've read a little about Step -1 as a way to iterate through the first row so one can identify the row headings across the columns, but that is far above my VBA skillset.) Don't assume I'm very good so fine to spell out a solution for a noob! Many thanks in advance!

Sub DOoNOToUSEoIEEEAdvancedSearchReformat()
'starting from a page like https://ieeexplore.ieee.org/search/searchresult.jsp?action=search&matchBoolean=true&queryText=(%22All%20Metadata%22:cuda)%20AND%20(%22All%20Metadata%22:gpu)%20NOT%20(%22Author%20Affiliations%22:nvidia)&highlight=true&returnType=SEARCH&matchPubs=true&rowsPerPage=100&searchWithin=speed&returnFacets=ALL&pageNumber=1
'export it using JSON per How to do IEEExplore Advanced (Network console JSON to Excel).docx

Dim a As Long, i As Long, j As Long, LC As Long, LR As Long, z As Long
Dim cell As Range, M As Range, OneRange As Range, SortCell As Range
Dim celltourl As String, unlinked As String
Dim ws As Worksheet, wd As Worksheet, wa As Worksheet

If ActiveWorkbook.Name = ThisWorkbook.Name Then 'you are in the wrong file because the macro is not stored in the exported IEEExplore file
    MsgBox ("You do not have the IEEExplore Excel file generated by Konklone selected in the foreground. Also make sure:" & vbNewLine & _
    "1) column headings row is the 1st row" & vbNewLine & _
    "2) you didn't delete any other rows copied from Konklone" & vbNewLine & _
    "Then re-run macro by selecting View --> Macros --> View Macros --> select IEEEAdvSearchReformat macro --> Run.")
    Exit Sub
ElseIf ActiveSheet.Cells(1, 1).Value2 <> "authors/0/preferredName" Then
    MsgBox "It appears you have some extra rows above the column headings row, or maybe extra columns preceding Candidate Name. Please delete those then re-run macro."
    Exit Sub

Else
'Copy first sheet to a new sheet per https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.copy
    Set ws = ActiveSheet
'we will rename its tab later:   ws.Name = "IEEExploreSearchResultCleaned"
    Sheets.Add 'if no argument provided, Excel uses the default values and adds 1 worksheet before the active sheet, and now it is the active sheet
    Set wd = ActiveSheet 'provides a short variable reference to this sheet going forward
    wd.Name = "Destination" 'name its tab as well

'turn off screen updating and unfreeze all worksheets
Application.ScreenUpdating = False
For Each wa In Application.ActiveWorkbook.Worksheets
    wa.Activate
    With Application.ActiveWindow
        .FreezePanes = False
    End With
Next

ws.Activate 'make orig sheet active again before the next code section

'delete all columns containing these strings in the header row
'below adapted from https://www.extendoffice.com/documents/excel/3086-excel-delete-columns-based-on-header.html
Dim xFNum, xFFNum, xCount As Integer
Dim xStr As String
Dim xArrName As Variant
Dim MR, xRg As Range
On Error Resume Next
Set MR = Range("A1:CP1")
xArrName = Array("preferredName", "*/normalizedName", "patentCitation*", "accessType*", "publicationNumber", "articleNumber", "doi", "isNumber", "showHtml", "showAlgorithm", _
"showDataset", "showVideo", "ephemera", "vj", "rightsLink", "rightslinkFlag", "pdfSize", "startPage", "endPage", "publicationDate", "htmlLink", "publisher", "showCheckbox", "redline", "handleProduct", "highlightedTitle", "publicationTitle", _
"pdfLink", "articleContentType", "isStandard", "isConference", "isJournalAndMagazine", "isEarlyAccess", "isMagazine", "isJournal", "isBook", "course", "displayContentType", "docIdentifier", "isBookWithoutChapters", "volume", "issue", "majorTopic")
'enclose each column name (or partial name with wildcard to use with Like below) with quotes and separate by comma
'alternatively, have the array contain only substrings and surround with wildcards, e.g., .Range.Replace "*" & Array(i) & "*",
xCount = MR.Count
xStr = xArrName(xFNum)
For xFFNum = xCount To 1 Step -1
Set xRg = MR(1, xFFNum)
For xFNum = 0 To UBound(xArrName)
xStr = xArrName(xFNum)
If xRg.Value Like xStr Then xRg.EntireColumn.Delete
Next xFNum
Next

'only one not working is the articleTitle isn't hyperlinking in the test sheet (which means URL won't carry over to Destination Col A either

On Error Resume Next
Set M = Range("A1:AR1") 'AR is authors/7/id column
For i = 1 To M.Count
    If Cells(1, i).Value Like "*/id" Then 'i is an author column number
    For j = 2 To Cells(Rows.Count, i).End(xlUp).Row 'last non-blank cell in column i
        celltourl = Cells(j, i).Value
        'another way: If Not IsEmpty(Cells(j, i).Value)
        If celltourl <> "" Then
        Cells(j, i).Value = "https://ieeexplore.ieee.org/author/" + celltourl 'prepend to row j value
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(j, i).Offset(0, -1), Address:=Cells(j, i).Value
        End If 'for inner If celltourl
    Next j 'done with authors
    ElseIf Cells(1, i).Value Like "documentLink" Then 'i is an article link column number, ie documentLink
    For j = 2 To Cells(Rows.Count, i).End(xlUp).Row 'last non-blank cell in column i
        celltourl = Cells(j, i).Value
        If celltourl <> "" Then
        Cells(j, i).Value = "https://ieeexplore.ieee.org" + celltourl 'prepend to row j value
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(j, i).Offset(0, 3), Address:=Cells(j, i).Value 'add URL to articleTitle 3 cols to the right
        End If 'for inner If celltourl
    Range("U1:U101").Copy wd.Range("A1:A101") 'was col AL, now col U; copy/paste article links to Dest tab col A
    Next j 'done with article title/link
    ElseIf Cells(1, i).Value Like "publicationLink" Then 'i is pub link column number, ie PublicationLink
    For j = 2 To Cells(Rows.Count, i).End(xlUp).Row 'last non-blank cell in column i
        celltourl = Cells(j, i).Value
        If celltourl <> "" Then
        Cells(j, i).Value = "https://ieeexplore.ieee.org" + celltourl 'prepend to row j value
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(j, i).Offset(0, 5), Address:=Cells(j, i).Value 'add URL to displayPublicationTitle 5 cols to the right
        End If 'for inner If celltourl
    Next j 'done with publication title/link
    ElseIf Cells(1, i).Value Like "citationsLink" Then 'i is citations link column number, ie citationsLink
    For j = 2 To Cells(Rows.Count, i).End(xlUp).Row 'last non-blank cell in column i
        celltourl = Cells(j, i).Value
        If celltourl <> "" Then
        Cells(j, i).Value = "https://ieeexplore.ieee.org" + celltourl 'prepend to row j value
        ActiveSheet.Hyperlinks.Add Anchor:=Cells(j, i).Offset(0, -4), Address:=Cells(j, i).Value 'add URL to citationCount 4 cols to the left
        End If 'for inner If celltourl
    Next j 'done with citation count/link
    End If 'done with link columns, now copy special columns to new locations on Destination tab
Next i
'    Range("U1:U101").Copy wd.Range("A1:A101") 'as col AL, now col U; copy/paste article links to Dest tab col A
    Range("AB1:AB101").Copy wd.Range("B1:B101") 'copy/paste abstract text to Dest tab col B
    Range("T1:T101").Copy wd.Range("C1:C101") 'copy/paste citation links to Dest tab col C
    Range("S1:S101").Copy wd.Range("D1:D101") 'copy/paste pub year to Dest tab col D
    Range("AA1:AA101").Copy wd.Range("E1:E101") 'copy/paste publication links to Dest tab col E
    Range("D1:D101").Copy wd.Range("F1:F101") 'copy/paste author 0 to Dest tab
    Range("H1:H101").Copy wd.Range("G1:G101") 'copy/paste author 1 to Dest tab
    Range("L1:L101").Copy wd.Range("H1:H101") 'copy/paste author 2 to Dest tab
    Range("P1:P101").Copy wd.Range("I1:I101") 'copy/paste author 3 to Dest tab
    Range("AE1:AE101").Copy wd.Range("J1:J101") 'copy/paste author 4 to Dest tab
    Range("AI1:AI101").Copy wd.Range("K1:K101") 'copy/paste author 5 to Dest tab
    Range("AM1:AM101").Copy wd.Range("L1:L101") 'copy/paste author 6 to Dest tab
    Range("AQ1:AQ101").Copy wd.Range("M1:M101") 'copy/paste author 7 to Dest tab

wd.Activate 'bring focus to Destination worksheet
'below works, but don't need it because above just copying over certain columns
'ws.Range("A1:AQ101").Copy wd.Range("E1:AS101") 'don't need to copy over all other columns, just leave them on ws tab for referennce
'On Error Resume Next
'Dim xFNumy, xFFNumy, xCounty As Integer
'Dim xStry As String
'Dim xArrNamey As Variant
'Dim MRy, xRgy As Range
'Set MRy = Range("A1:AS1")
'xArrNamey = Array("authors/0/preferredName", "*/firstName", "*/lastName", "*/id") 'delete some columns on wd, but keep on ws
'xCounty = MRy.Count
'xStry = xArrNamey(xFNumy)
'For xFFNumy = xCounty To 1 Step -1
'Set xRgy = MRy(1, xFFNumy)
'For xFNumy = 0 To UBound(xArrNamey)
'xStry = xArrNamey(xFNumy)
'If xRgy.Value Like xStry Then xRgy.EntireColumn.Delete
'If xRgy.Value Like "*/searchablePreferredName" Then xRgy.ColumnWidth = 20
'Next xFNumy
'Next

wd.Columns("A:B").ColumnWidth = 25 'increase width in artTitle, abstract cols
wd.Columns("C").ColumnWidth = 10 'increase width in citationCount col
wd.Columns("D").ColumnWidth = 4 'decrease width in Pub year col
wd.Columns("E").ColumnWidth = 18 'increase width in Pub title col
wd.Columns("F:I").ColumnWidth = 15 'increase width in first 4 author columns
wd.Columns("J:M").ColumnWidth = 10 'increase width in last 4 author columns
Application.GoTo Reference:=Range("A2") 'go to cell A2
'replicating what Freeze Panes --> Freeze Top Row does, per https://stackoverflow.com/questions/34094445/excel-vba-freeze-pane-without-select
With ActiveWindow
    If .FreezePanes Then .FreezePanes = False
    .SplitColumn = 0
    .SplitRow = 1
    .FreezePanes = True
End With

End If 'this is for the end of entire macro
Application.GoTo Reference:=wd.Range("A2")
Application.ScreenUpdating = True
End Sub


问:
There's something in the 'conexaoHttp' método that's not working
```<code>package controllers;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.Collections;
import java.util.List;

import models.Aparelho;
import models.Status;
import play.data.validation.Valid;
import play.mvc.Controller;
import play.mvc.With;
import security.Seguranca;

public class Aparelhos extends Controller {

    public static void form(Aparelho aparelho) {
        render(aparelho);
    }

    public static void menu() {
        render();
    }

    public static void salvar(@Valid Aparelho aparelho) {
        long qtd = Aparelho.count("nome = ?1 and id <> ?2", aparelho.nome, aparelho.id);
        if (validation.hasErrors()) {
            validation.keep();
            form(aparelho);
        }

        if (qtd == 0) {
            aparelho.status = Status.desligado;
            aparelho.save();
            flash.success("Cadastro realizado com sucesso.");
        } else {
            flash.error("O aparelho informado já possui cadastro.");
        }
        listar();
    }

    public static void listar() {
        String termo = params.get("termo");

        List<Aparelho> aparelhos = Collections.EMPTY_LIST;
        if (termo == null || termo.isEmpty()) {
            aparelhos = Aparelho.findAll();
        } else {
            aparelhos = Aparelho.find(
                    "(lower(nome) like ?1 OR lower(enderecoIp) like ?2 "
                            + " OR lower(enderecoMac) like ?3 OR lower(local) like ?4)",
                    "%" + termo.toLowerCase() + "%", "%" + termo.toLowerCase() + "%", "%" + termo.toLowerCase() + "%",
                    "%" + termo.toLowerCase() + "%").fetch();
        }
        render(aparelhos, termo);
    }

    public static void funcionar(Long id) throws IOException, InterruptedException {
        Aparelho ap = Aparelho.findById(id);
        String ip = ap.enderecoIp;
        String cod;

        if (ap.status == Status.ligado) {
            cod = ap.codIrDesligar;
            conexaoHttp(ip, cod);
            ap.status = Status.desligado;
        } else {
            cod = ap.codIrLigar;
            conexaoHttp(ip, cod);
            ap.status = Status.ligado;
        }

        ligados();
    }

    public static void conexaoHttp(String ip, String cod) throws IOException, InterruptedException {

        HttpRequest request = HttpRequest.newBuilder()
                .POST(BodyPublishers.ofString("{\"ip address\": \"" + ip + "\", \"codigo\": \" " + cod + "\"}"))
                .uri(URI.create("")).headers("Accept", "application/json")

                .timeout(Duration.ofSeconds(5)).build();

        HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3))
                .followRedirects(Redirect.NORMAL).build();

        httpClient.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::body);
    }
</code>```

The message that appears is:
The file /app/controllers/Aparelhos.java could not be compiled. Error raised is : java.net.http.HttpClient cannot be resolved

It's my first time trying to make an http connection with java. I'm using play! Framework

In this case, what I want to happen is for the 'conexaoHttp' method to send to the url that I put only an ip address and a code that are registered in my database.

Body:
package controllers;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.Collections;
import java.util.List;

import models.Aparelho;
import models.Status;
import play.data.validation.Valid;
import play.mvc.Controller;
import play.mvc.With;
import security.Seguranca;

public class Aparelhos extends Controller {

    public static void form(Aparelho aparelho) {
        render(aparelho);
    }

    public static void menu() {
        render();
    }

    public static void salvar(@Valid Aparelho aparelho) {
        long qtd = Aparelho.count("nome = ?1 and id <> ?2", aparelho.nome, aparelho.id);
        if (validation.hasErrors()) {
            validation.keep();
            form(aparelho);
        }

        if (qtd == 0) {
            aparelho.status = Status.desligado;
            aparelho.save();
            flash.success("Cadastro realizado com sucesso.");
        } else {
            flash.error("O aparelho informado já possui cadastro.");
        }
        listar();
    }

    public static void listar() {
        String termo = params.get("termo");

        List<Aparelho> aparelhos = Collections.EMPTY_LIST;
        if (termo == null || termo.isEmpty()) {
            aparelhos = Aparelho.findAll();
        } else {
            aparelhos = Aparelho.find(
                    "(lower(nome) like ?1 OR lower(enderecoIp) like ?2 "
                            + " OR lower(enderecoMac) like ?3 OR lower(local) like ?4)",
                    "%" + termo.toLowerCase() + "%", "%" + termo.toLowerCase() + "%", "%" + termo.toLowerCase() + "%",
                    "%" + termo.toLowerCase() + "%").fetch();
        }
        render(aparelhos, termo);
    }

    public static void funcionar(Long id) throws IOException, InterruptedException {
        Aparelho ap = Aparelho.findById(id);
        String ip = ap.enderecoIp;
        String cod;

        if (ap.status == Status.ligado) {
            cod = ap.codIrDesligar;
            conexaoHttp(ip, cod);
            ap.status = Status.desligado;
        } else {
            cod = ap.codIrLigar;
            conexaoHttp(ip, cod);
            ap.status = Status.ligado;
        }

        ligados();
    }

    public static void conexaoHttp(String ip, String cod) throws IOException, InterruptedException {

        HttpRequest request = HttpRequest.newBuilder()
                .POST(BodyPublishers.ofString("{\"ip address\": \"" + ip + "\", \"codigo\": \" " + cod + "\"}"))
                .uri(URI.create("")).headers("Accept", "application/json")

                .timeout(Duration.ofSeconds(5)).build();

        HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3))
                .followRedirects(Redirect.NORMAL).build();

        httpClient.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::body);
    }

The message that appears is:
The file /app/controllers/Aparelhos.java could not be compiled. Error raised is : java.net.http.HttpClient cannot be resolved

It's my first time trying to make an http connection with java. I'm using play! Framework

In this case, what I want to happen is for the 'conexaoHttp' method to send to the url that I put only an ip address and a code that are registered in my database.


问:
How to differentiate development environment of production environment on cloud functions?
I would like to know if there is a way to find out if I'm in development or production. I have a BASE_URL that it should have localhost if I'm running the emulator but when I'm deploy to prod it should be my domain for example

const BASE_URL = isProd ? 'https://mydomain' : 'http://localhost:3000'


问:
Submitting a form causes a TypeError: Cannot read properties of null (reading 'addEventListener')
I am trying to submit a form that queries JSON data saved in localStorage. I want to have it so it transfers the user to another local page named "results.html" and inserts a div class "card" inside another (existing) div #search-results.

```<code>const data = {
    "properties": [
        {
            "id":"prop1",
            "type":"House",
            "bedrooms":3,
            "price":750000,
            "tenure":"Freehold",
            "description":"Attractive three bedroom semi-detached family home situated within 0.5 miles of Petts Wood station with fast trains to London and within easy walking distance of local shops, schools, bus routes and National Trust woodland. The property comprises; two receptions, fitted 18'9 x 10'1 kitchen/breakfast room and conservatory. The property also benefits from having a utility room and cloakroom. To the first floor there are three bedrooms and a family bathroom with separate WC. Additional features include double glazing, gas central heating and a well presented interior...",
            "location":"Petts Wood Road, Petts Wood, Orpington BR5",
            "picture":"images/prop1pic1small.jpg",
            "url":"properties/prop1.html",
            "added": {
                "month":"October",
                "day":12,
                "year":2022
            }
        },
        {
            "id":"prop2",
            "type":"Flat",
            "bedrooms":2,
            "price":399995,
            "tenure":"Freehold",
            "description":"Presented in excellent decorative order throughout is this two double bedroom, two bathroom, garden flat. <br>The modern fitted kitchen is open plan to the living room which boasts solid wooden floors and includes integrated appliances including a dishwasher & a washing machine. This large open plan benefits from bi folding doors onto a secluded private courtyard garden. Both bedrooms are double sized, and the family bathroom boasts a matching three piece suite a shower attachment over the bath. There is also a separate wet room. There are walnut doors throughout and wiring for Sky TV/aerial points in the living room/kitchen and both bedrooms.<br>This apartment being only five years old, is still under a 10 year building guarantee...",
            "location":"Crofton Road Orpington BR6",
            "picture":"images/prop2pic1small.jpg",
            "url":"properties/prop2.html",
            "added": {
                "month":"September",
                "day":14,
                "year":2022
            }
        },
        {
            "id":"prop3",
            "type":"House",
            "bedrooms":8,
            "price":999995,
            "tenure":"Freehold",
            "description":"Presented in excellent decorative order throughout is this two double bedroom, two bathroom, garden flat. <br>The modern fitted kitchen is open plan to the living room which boasts solid wooden floors and includes integrated appliances including a dishwasher & a washing machine. This large open plan benefits from bi folding doors onto a secluded private courtyard garden. Both bedrooms are double sized, and the family bathroom boasts a matching three piece suite a shower attachment over the bath. There is also a separate wet room. There are walnut doors throughout and wiring for Sky TV/aerial points in the living room/kitchen and both bedrooms.<br>This apartment being only five years old, is still under a 10 year building guarantee...",
            "location":"Buckaroo Road Orpington W12",
            "picture":"images/prop2pic1small.jpg",
            "url":"properties/prop3.html",
            "added": {
                "month":"September",
                "day":14,
                "year":2022
            }
        }
    ]
};

function searchData(searchTerm) {
  const data = JSON.parse(localStorage.getItem('data'));
  const results = data.properties.filter(properties => properties.location.includes(searchTerm));
  return results;
}

localStorage.setItem('data', JSON.stringify(data));

const form = document.getElementById('search-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();
  const searchTerm = document.getElementById('search-input').value;
  const results = searchData(searchTerm);

  window.location.assign("results.html");
  window.onload = function() {
    const searchResultsDiv = document.getElementById('search-results');
    if (results.length > 0) {
      results.forEach(result => {
        searchResultsDiv.innerHTML += `
          <div class="card">
            <a href="${result.url}">Link</a>
            <h2>${result.type}</h2>
            <p>Price: ${result.price}</p>
            <p>Location: ${result.location}</p>
          </div>
        `;
      });
    } else {
      searchResultsDiv.innerHTML += '<p>No results found</p>';
    }
  }
});
</code>```

With the code above ^ I am using "window.location.assign" to change pages however that gives the eventListener null error.

```<code> Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
</code>```
```<code>const form = document.getElementById('search-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();
  const searchTerm = document.getElementById('search-input').value;
  const results = searchData(searchTerm);

  const htmlElement = document.createElement('html')
  htmlElement.innerHTML = `
    <head>
      <title>Search Results</title>
    </head>
    <body>
      <div id="search-results">
  `;
  if (results.length > 0) {
    results.forEach(result => {
      htmlElement.innerHTML += `
        <div class="card">
            <a href="${result.url}">Link</a>
            <h2>${result.type}</h2>
            <p>Price: ${result.price}</p>
            <p>Location: ${result.location}</p>
          </div>
      `;
    });
  } else {
    htmlElement.innerHTML += '<p>No results found</p>';
  }
  htmlElement.innerHTML += '</div></body>';

  const newWindow = window.open("results.html");
  newWindow.document.write(htmlElement.outerHTML);
});
</code>```

IF instead I use document.createElement to create a new HTML page, all the sudden the form submits correctly.

Here are the contents of index.html

```<code> <form id="search-form">
        <input type="text" id="search-input" placeholder="Search...">
        <button type="submit">Search</button>
    </form>
    <script src="script.js"></script>
</code>```

And contents of results.html

```<code><body>
    <div id="search-results">

    </div>
    <script src="script.js"></script>
</code>```

I have tried using window.location.href to no avail, triple checking ID's, divs, forms and etc are set up correctly.

TLDR: on form submission transfer user to local page results.html - using window.location.assign() causes addEventListener Null error for the form.

Let me know if my question is unclear and any possible solutions you guys might have.

Body:
I am trying to submit a form that queries JSON data saved in localStorage. I want to have it so it transfers the user to another local page named "results.html" and inserts a div class "card" inside another (existing) div #search-results.

const data = {
    "properties": [
        {
            "id":"prop1",
            "type":"House",
            "bedrooms":3,
            "price":750000,
            "tenure":"Freehold",
            "description":"Attractive three bedroom semi-detached family home situated within 0.5 miles of Petts Wood station with fast trains to London and within easy walking distance of local shops, schools, bus routes and National Trust woodland. The property comprises; two receptions, fitted 18'9 x 10'1 kitchen/breakfast room and conservatory. The property also benefits from having a utility room and cloakroom. To the first floor there are three bedrooms and a family bathroom with separate WC. Additional features include double glazing, gas central heating and a well presented interior...",
            "location":"Petts Wood Road, Petts Wood, Orpington BR5",
            "picture":"images/prop1pic1small.jpg",
            "url":"properties/prop1.html",
            "added": {
                "month":"October",
                "day":12,
                "year":2022
            }
        },
        {
            "id":"prop2",
            "type":"Flat",
            "bedrooms":2,
            "price":399995,
            "tenure":"Freehold",
            "description":"Presented in excellent decorative order throughout is this two double bedroom, two bathroom, garden flat.
The modern fitted kitchen is open plan to the living room which boasts solid wooden floors and includes integrated appliances including a dishwasher & a washing machine. This large open plan benefits from bi folding doors onto a secluded private courtyard garden. Both bedrooms are double sized, and the family bathroom boasts a matching three piece suite a shower attachment over the bath. There is also a separate wet room. There are walnut doors throughout and wiring for Sky TV/aerial points in the living room/kitchen and both bedrooms.
This apartment being only five years old, is still under a 10 year building guarantee...",
            "location":"Crofton Road Orpington BR6",
            "picture":"images/prop2pic1small.jpg",
            "url":"properties/prop2.html",
            "added": {
                "month":"September",
                "day":14,
                "year":2022
            }
        },
        {
            "id":"prop3",
            "type":"House",
            "bedrooms":8,
            "price":999995,
            "tenure":"Freehold",
            "description":"Presented in excellent decorative order throughout is this two double bedroom, two bathroom, garden flat.
The modern fitted kitchen is open plan to the living room which boasts solid wooden floors and includes integrated appliances including a dishwasher & a washing machine. This large open plan benefits from bi folding doors onto a secluded private courtyard garden. Both bedrooms are double sized, and the family bathroom boasts a matching three piece suite a shower attachment over the bath. There is also a separate wet room. There are walnut doors throughout and wiring for Sky TV/aerial points in the living room/kitchen and both bedrooms.
This apartment being only five years old, is still under a 10 year building guarantee...",
            "location":"Buckaroo Road Orpington W12",
            "picture":"images/prop2pic1small.jpg",
            "url":"properties/prop3.html",
            "added": {
                "month":"September",
                "day":14,
                "year":2022
            }
        }
    ]
};

function searchData(searchTerm) {
  const data = JSON.parse(localStorage.getItem('data'));
  const results = data.properties.filter(properties => properties.location.includes(searchTerm));
  return results;
}

localStorage.setItem('data', JSON.stringify(data));

const form = document.getElementById('search-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();
  const searchTerm = document.getElementById('search-input').value;
  const results = searchData(searchTerm);

  window.location.assign("results.html");
  window.onload = function() {
    const searchResultsDiv = document.getElementById('search-results');
    if (results.length > 0) {
      results.forEach(result => {
        searchResultsDiv.innerHTML += `

            Link

${result.type}

Price: ${result.price}

Location: ${result.location}

        `;
      });
    } else {
      searchResultsDiv.innerHTML += '
No results found
';
    }
  }
});

With the code above ^ I am using "window.location.assign" to change pages however that gives the eventListener null error.

 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

const form = document.getElementById('search-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();
  const searchTerm = document.getElementById('search-input').value;
  const results = searchData(searchTerm);

  const htmlElement = document.createElement('html')
  htmlElement.innerHTML = `

      <title>Search Results</title>

  `;
  if (results.length > 0) {
    results.forEach(result => {
      htmlElement.innerHTML += `

            Link

${result.type}

Price: ${result.price}

Location: ${result.location}

      `;
    });
  } else {
    htmlElement.innerHTML += '
No results found
';
  }
  htmlElement.innerHTML += '
';

  const newWindow = window.open("results.html");
  newWindow.document.write(htmlElement.outerHTML);
});

IF instead I use document.createElement to create a new HTML page, all the sudden the form submits correctly.

Here are the contents of index.html

 <form id="search-form">
        <input type="text" id="search-input" placeholder="Search...">
        <button type="submit">Search</button>
    </form>

And contents of results.html

I have tried using window.location.href to no avail, triple checking ID's, divs, forms and etc are set up correctly.

TLDR: on form submission transfer user to local page results.html - using window.location.assign() causes addEventListener Null error for the form.

Let me know if my question is unclear and any possible solutions you guys might have.


问:
Express is throwing an ERR_HTTP_HEADERS_SENT error when a .catch is chained to the end of a bcryptjs.hash function call
My Express app has the following endpoint:

```<code>app.post('/test', myFunc)
</code>```

with the following endpoint handler function:

```<code>const bcryptjs = require('bcryptjs')

function  myFunc(req, res) {
    let password = 'password1234'
    let saltRounds = 10
    bcryptjs.hash(password, saltRounds, function(err, hash) {
        res.send({success: true})
    })
    .catch(function(err) {
        res.send({success: false})
    })
}
</code>```

Now, I know that a bcryptjs.hash function call doesn't allow a .catch to be chained on the end of it. My question is more about the type of error message that pops up when this endpoint and its handler function are run, which is:

```<code>node:_http_outgoing:576
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
</code>```

In my experience, I've found that this type of error typically pops up when an endpoint handler function does two res.send calls in the same function execution, or something like unto it (doing res.send().json() or res.sendStatus().send(), etc.). But it doesn't look my code is violating that idea, and just to be doubly sure, I've commented out the .catch's res.send (which wasn't being run the first place, anyway), so that there is only one res.send in the whole function:

```<code>const bcryptjs = require('bcryptjs')

function  myFunc(req, res) {
    let password = 'password1234'
    let saltRounds = 10
    bcryptjs.hash(password, saltRounds, function(err, hash) {
        res.send({success: true})
    })
    .catch(function(err) {
        //res.send({success: false})
    })
}
</code>```

But the error still shows up. Just to ensure that it is the mere presence of the .catch that makes the error appear, I change my endpoint handler function to

```<code>const bcryptjs = require('bcryptjs')

function  myFunc(req, res) {
    let password = 'password1234'
    let saltRounds = 10
    bcryptjs.hash(password, saltRounds, function(err, hash) {
        res.send({success: true})
    })
}
</code>```

and no errors are thrown.

My question isn't so much about why an error is thrown when there is a .catch, but more: why this particular error? Are headers actually trying to be set after a response to the client was sent? And if so, what code is setting those headers?

Body:
My Express app has the following endpoint:

app.post('/test', myFunc)

with the following endpoint handler function:

const bcryptjs = require('bcryptjs')

function  myFunc(req, res) {
    let password = 'password1234'
    let saltRounds = 10
    bcryptjs.hash(password, saltRounds, function(err, hash) {
        res.send({success: true})
    })
    .catch(function(err) {
        res.send({success: false})
    })
}

Now, I know that a bcryptjs.hash function call doesn't allow a .catch to be chained on the end of it. My question is more about the type of error message that pops up when this endpoint and its handler function are run, which is:

node:_http_outgoing:576
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

In my experience, I've found that this type of error typically pops up when an endpoint handler function does two res.send calls in the same function execution, or something like unto it (doing res.send().json() or res.sendStatus().send(), etc.). But it doesn't look my code is violating that idea, and just to be doubly sure, I've commented out the .catch's res.send (which wasn't being run the first place, anyway), so that there is only one res.send in the whole function:

const bcryptjs = require('bcryptjs')

function  myFunc(req, res) {
    let password = 'password1234'
    let saltRounds = 10
    bcryptjs.hash(password, saltRounds, function(err, hash) {
        res.send({success: true})
    })
    .catch(function(err) {
        //res.send({success: false})
    })
}

But the error still shows up. Just to ensure that it is the mere presence of the .catch that makes the error appear, I change my endpoint handler function to

const bcryptjs = require('bcryptjs')

function  myFunc(req, res) {
    let password = 'password1234'
    let saltRounds = 10
    bcryptjs.hash(password, saltRounds, function(err, hash) {
        res.send({success: true})
    })
}

and no errors are thrown.

My question isn't so much about why an error is thrown when there is a .catch, but more: why this particular error? Are headers actually trying to be set after a response to the client was sent? And if so, what code is setting those headers?


问:
Rendering a component in material ui datagrid
I am trying to render a material ui modal button inside a datagrid material ui component. The button triggers a modal or MUI dialog on click.

This is the code for my datagrid columns. I try to render the component with a function but it is not being rendered

```<code>const columns: Array<GridColDef | ExtendedGridColDef> = [
    { field: "name", headerName: "Name", width: 70 },
    { field: "price", headerName: "Price", width: 130 },
    { field: "category", headerName: "Category", width: 130 },
    { field: "min Stock", headerName: "Min Stock", width: 130 },
    { field: "status", headerName: "Status", width: 130 },
    { field: "updateDate", headerName: "Last Update", width: 130 },
    { field: "creationDate", headerName: "Creation Date", width: 130 },
    {
      field: "edit",
      headerName: "Edit",
      width: 70,
      cellRenderer: (params: {value:any}) => {

        return <div><EditItemDialog item={params.value} /></div>;
      },
    },
  ];
</code>```

How do i make this happen ?

Body:
I am trying to render a material ui modal button inside a datagrid material ui component. The button triggers a modal or MUI dialog on click.

This is the code for my datagrid columns. I try to render the component with a function but it is not being rendered

const columns: Array<GridColDef | ExtendedGridColDef> = [
    { field: "name", headerName: "Name", width: 70 },
    { field: "price", headerName: "Price", width: 130 },
    { field: "category", headerName: "Category", width: 130 },
    { field: "min Stock", headerName: "Min Stock", width: 130 },
    { field: "status", headerName: "Status", width: 130 },
    { field: "updateDate", headerName: "Last Update", width: 130 },
    { field: "creationDate", headerName: "Creation Date", width: 130 },
    {
      field: "edit",
      headerName: "Edit",
      width: 70,
      cellRenderer: (params: {value:any}) => {

        return
<EditItemDialog item={params.value} />
;
      },
    },
  ];

How do i make this happen ?