问:
Elasticsearch - Simple Query String not returning result: Multiple Fields with Boost Values
I have a simple_query_string query with multiple fields, each field has different boost values. However, if there is a match of a query in any of the fields with less or no boost value the query returns no result. Is it a known issue or am I doing something wrong?

The phrase 'Peace for Change' is there in the title field only but the query returns no result.

Here's my query:

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "simple_query_string": {
            "query": "Peace for Change",
            "default_operator": "AND",
            "flags": "PREFIX|PHRASE|NOT|AND|OR|FUZZY|WHITESPACE",
            "fields": [
              "*",
              "systemNumber^5",
              "global_search",
              "objectType^2",
              "partTypes.text",
              "partTypes.id",
              "people^2",
              "person^2",
              "org^2",
              "title^2",
              "Location.displayName",
              "briefDescription",
              "physicalDescription",
              "summaryDescription",
              "flatPersonsNameId",
              "flatPeoplesNameId",
              "flatOrganisationsNameId",
              "primaryDate",
              "primaryDateEarliest",
              "primaryDateLatest"
            ]
          }
        }
      ]
    }
  }
}```

```

Body:
I have a simple_query_string query with multiple fields, each field has different boost values. However, if there is a match of a query in any of the fields with less or no boost value the query returns no result. Is it a known issue or am I doing something wrong?

The phrase 'Peace for Change' is there in the title field only but the query returns no result.

Here's my query:

{
  "query": {
    "bool": {
      "must": [
        {
          "simple_query_string": {
            "query": "Peace for Change",
            "default_operator": "AND",
            "flags": "PREFIX|PHRASE|NOT|AND|OR|FUZZY|WHITESPACE",
            "fields": [
              "*",
              "systemNumber^5",
              "global_search",
              "objectType^2",
              "partTypes.text",
              "partTypes.id",
              "people^2",
              "person^2",
              "org^2",
              "title^2",
              "Location.displayName",
              "briefDescription",
              "physicalDescription",
              "summaryDescription",
              "flatPersonsNameId",
              "flatPeoplesNameId",
              "flatOrganisationsNameId",
              "primaryDate",
              "primaryDateEarliest",
              "primaryDateLatest"
            ]
          }
        }
      ]
    }
  }
}```


来源: stackexchange

问:
aws amplify graphql mutations
I have this code here:

```<code>export const updateEcpData = (
  groupId: string,
  version: number
) => {
  return axios({
    url: URL,
    method: 'post',
    headers: {
      'x-api-key': KEY,
    },
    data: {
      query: print(gql(updateGroup)),
      variables: {
        input: {
          id: groupId,
          _version: version,
        },
      },
    },
  })
}
</code>```

To update some data i always need to provide an higher _version number. In my case i first query the data, and then i increase the queried version + 1 to update it.

My question: This requires 1 additional query to the database just to get the version number. Isnt it better to use Date.now() as the version number? Whenever i update something the Date.now() will always be higher then the previous one

ContentLicense: CC BY-SA 4.0

Title: aws amplify graphql mutations

Body:
I have this code here:

export const updateEcpData = (
  groupId: string,
  version: number
) => {
  return axios({
    url: URL,
    method: 'post',
    headers: {
      'x-api-key': KEY,
    },
    data: {
      query: print(gql(updateGroup)),
      variables: {
        input: {
          id: groupId,
          _version: version,
        },
      },
    },
  })
}

To update some data i always need to provide an higher _version number. In my case i first query the data, and then i increase the queried version + 1 to update it.

My question: This requires 1 additional query to the database just to get the version number. Isnt it better to use Date.now() as the version number? Whenever i update something the Date.now() will always be higher then the previous one


问:
How to use an installed x509 Certificate as a Client certificate when programming a web request in python?
I am working on a python script that is supposed to do web request using a client certificate from a store (so not from a file path). The certificate is already installed and the webrequest is already succeeding (when programmed in C# in a way similar to this).

My python code is failing and I do not know how to fix this.
Here is the failing code (the variables url and in_subject are set on top of the file).

```<code>import ssl
from cryptography import x509
import requests

def get_certificate(to_find_in_subject: str):
    for store in ["CA", "ROOT", "MY"]:
        for cert, encoding, trust in ssl.enum_certificates(store):
            certificate = x509.load_der_x509_certificate(cert, backend=None)
            if to_find_in_subject in f'{certificate.subject}':
                return certificate

certifcate = get_certificate(in_subject)
print(certifcate is None)
response = requests.request(method="GET", url=url, cert=certifcate)

print(response.text)
</code>```

This is the output (shown below). Apparently, I cannot set the certificate as a certificate argument. That is not a big problem if I know what to do instead. So what is that, what to do instead? How to use an installed x509 Certificate as a Client certificate when programming a web request in python?

False

Traceback (most recent call last):

File "C:\Users\daan\PycharmProjects\certificateCall\reproduceforStackoverflow.py", line 19, in

response = requests.request(method="GET", url=url, cert=certifcate)

.........

TypeError: 'builtins.Certificate' object is not subscriptable

Process finished with exit code 1

Body:
I am working on a python script that is supposed to do web request using a client certificate from a store (so not from a file path). The certificate is already installed and the webrequest is already succeeding (when programmed in C# in a way similar to this).

My python code is failing and I do not know how to fix this.
Here is the failing code (the variables url and in_subject are set on top of the file).

import ssl
from cryptography import x509
import requests

def get_certificate(to_find_in_subject: str):
    for store in ["CA", "ROOT", "MY"]:
        for cert, encoding, trust in ssl.enum_certificates(store):
            certificate = x509.load_der_x509_certificate(cert, backend=None)
            if to_find_in_subject in f'{certificate.subject}':
                return certificate

certifcate = get_certificate(in_subject)
print(certifcate is None)
response = requests.request(method="GET", url=url, cert=certifcate)

print(response.text)

This is the output (shown below). Apparently, I cannot set the certificate as a certificate argument. That is not a big problem if I know what to do instead. So what is that, what to do instead? How to use an installed x509 Certificate as a Client certificate when programming a web request in python?

False

Traceback (most recent call last):

File "C:\Users\daan\PycharmProjects\certificateCall\reproduceforStackoverflow.py", line 19, in

response = requests.request(method="GET", url=url, cert=certifcate)

.........

TypeError: 'builtins.Certificate' object is not subscriptable

Process finished with exit code 1


问:
Dependency diagram creation via Powershell
We need to create a DAG / Dependency graph based on dictionary variables.

Below is my scenario :

```<code>$Trigger=@{} #Key vaule pair variable
$Connection=@{} #Key vaule pair variable
$Data=@{} #Key vaule pair variable

$Trigger Key Value
A {P1,P2}
B {P1,P5,B1}

$Connection Key Value
X {P1,J1}
y {P5}

$Data Key Value
S {X,R1}
</code>```

Output should be as below:

Is there any way to create this DAG/Dependency graph in powershell based on key value variables?

In our organization, we need to use only PowerShell and avoid open packages as much as possible. So is there any way to do it in PowerShell only?
Also we don't want to pay for (or install) a tool to do it.

Note - I did go through Mermaid and PSGraph for this dependency flow but that was rejected in my organization.

Body:
We need to create a DAG / Dependency graph based on dictionary variables.

Below is my scenario :

$Trigger=@{} #Key vaule pair variable
$Connection=@{} #Key vaule pair variable
$Data=@{} #Key vaule pair variable

$Trigger Key Value
A {P1,P2}
B {P1,P5,B1}

$Connection Key Value
X {P1,J1}
y {P5}

$Data Key Value
S {X,R1}

Output should be as below:

Is there any way to create this DAG/Dependency graph in powershell based on key value variables?

In our organization, we need to use only PowerShell and avoid open packages as much as possible. So is there any way to do it in PowerShell only?
Also we don't want to pay for (or install) a tool to do it.

Note - I did go through Mermaid and PSGraph for this dependency flow but that was rejected in my organization.


问:
elasticsearch maximum requests per seconde
I installed elasticseach on a linux server, I have a single node of it. I have a csv file of several tens of thousands of lines which contains IDs, the goal is to iterate over this file and retrieve the data from the elasticsearch index.
The problem is that after a few thousand requests, elasticsearch crashes.
Please how much is the number of requests per second for a neod elasticsearch?
Thanks</p>


问:
How to set the output of the objective function to return an integer in LPP in r?
This is the equation :

```<code>lp.control(model, sense='max')
set.objfn(model,c(3,5)
.....eqns
</code>```

I want the output of

```<code>get.variables(model) to be an integer.
</code>```

I tried :

```<code>lp.control(model, sense = 'max', all.int = True)
</code>```

but this didn't help.

Can someone help ?

Body:
This is the equation :

lp.control(model, sense='max')
set.objfn(model,c(3,5)
.....eqns

I want the output of

get.variables(model) to be an integer.

I tried :

lp.control(model, sense = 'max', all.int = True)

but this didn't help.

Can someone help ?


问:
How to use mutableSetOf in SnapshotStateList in jetpack compose
I want to make a list of unique items in my list in jetpack compose. So I am trying to use MutableSet in my project. I know that mutableStateListOf is using for list in jetpack compose. I have another reason to use of mutableStateListOf in my project. So is there is way we can use of MutableSet with mutableStateListOf ?

```<code> val list by lazy { mutableStateListOf<ScanResult>() }
</code>```

Many Thanks

Body:
I want to make a list of unique items in my list in jetpack compose. So I am trying to use MutableSet in my project. I know that mutableStateListOf is using for list in jetpack compose. I have another reason to use of mutableStateListOf in my project. So is there is way we can use of MutableSet with mutableStateListOf ?

 val list by lazy { mutableStateListOf<ScanResult>() }

Many Thanks


问:
Instagram Bot with nodejs and puppeteer
I wrote a bot to login in instagram with nodejs and puppeteer. but when I click on login this error will appear : CSRF token missing or incorrect, How can I resolve it ?

```<code>
   const browser = await puppeteer.launch({
        headless: false,
    });
    const page = await browser.newPage();

    await page.setUserAgent("Mozilla/5.0 (X11; CrOS x86_64 10066.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36");

    // Load Instagram
    await page.goto('https://www.instagram.com/accounts/login/',{waitUntil:'networkidle2'});
    await page.waitForSelector(cnf.username_field, {timeout: 100000});

    await page.screenshot({ path: `screenshots/1.jpeg` });

    // Login
    await page.click(cnf.username_field);
    await page.keyboard.type(cnf.username);
    await page.click(cnf.password_field);
    await page.keyboard.type(cnf.password);

    await page.screenshot({ path: `screenshots/2.jpeg` });

    await page.click(cnf.login_button);

    browser.close();

</code>```

enter image description here

Title: Instagram Bot with nodejs and puppeteer

Body:
I wrote a bot to login in instagram with nodejs and puppeteer. but when I click on login this error will appear : CSRF token missing or incorrect, How can I resolve it ?

   const browser = await puppeteer.launch({
        headless: false,
    });
    const page = await browser.newPage();

    await page.setUserAgent("Mozilla/5.0 (X11; CrOS x86_64 10066.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36");

    // Load Instagram
    await page.goto('https://www.instagram.com/accounts/login/',{waitUntil:'networkidle2'});
    await page.waitForSelector(cnf.username_field, {timeout: 100000});

    await page.screenshot({ path: `screenshots/1.jpeg` });

    // Login
    await page.click(cnf.username_field);
    await page.keyboard.type(cnf.username);
    await page.click(cnf.password_field);
    await page.keyboard.type(cnf.password);

    await page.screenshot({ path: `screenshots/2.jpeg` });

    await page.click(cnf.login_button);

    browser.close();

enter image description here


问:
deselect item will reselect automatically MultiComboBox
Hi i'm using MultiComboBox

```<code> <MultiComboBox
    selectedKeys="{$this>/itemSearchSelectedKeys}"
    items="{
        path: '$this>/items',
        sorter: [{ path: 'sortOrder' }]
    }"
    selectionChange="onItemSelectionChange">
    <c:Item key="{$this>retailitemId}" text="{$this>retailitemId} ({$this>value})" />
</MultiComboBox>
</code>```

and the code

```<code> onItemSelectionChange(oEvent) {

            var aSelectedItems = oEvent.getSource().getSelectedItems().map(oItem =>
            oItem.getBindingContext("$this").getObject());

            this.setSelectedStores(aSelectedItems);
            this.onFilterChange();
        }

</code>```

By default 6 items selected automatically once the application is loaded.  My problem is that deselect some items will cause that some items will be reselected again

Body:
Hi i'm using MultiComboBox

 <MultiComboBox
    selectedKeys="{$this>/itemSearchSelectedKeys}"
    items="{
        path: '$this>/items',
        sorter: [{ path: 'sortOrder' }]
    }"
    selectionChange="onItemSelectionChange">
    <c:Item key="{$this>retailitemId}" text="{$this>retailitemId} ({$this>value})" />
</MultiComboBox>

and the code

 onItemSelectionChange(oEvent) {

            var aSelectedItems = oEvent.getSource().getSelectedItems().map(oItem =>
            oItem.getBindingContext("$this").getObject());

            this.setSelectedStores(aSelectedItems);
            this.onFilterChange();
        }

By default 6 items selected automatically once the application is loaded.  My problem is that deselect some items will cause that some items will be reselected again


Title: How to decode data from uniswap transaction in python

Body:
I am getting stuck decoding data transaction from a swap using uniswap protocol (Uniswap V3: Router 2 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45). In other words, I'd like to know if it exists a function that given a smart contract address and the data of the transaction, returns the decoded data (the path of all the smart contract addresses that the transaction executes).

I tried to use the method decode_function_input from Web3, but it worked only for certain protocol.

When I tried for a swap on uniswap or a transaction on opensea I did not get any results.

address = 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45

data = 0x5ae401dc0000000000000000000000000000000000000000000000000000000063bd8fab00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000e404e45aaf000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec700000000000000000000000000000000000000000000000000000000000001f4000000000000000000000000dc06b8c890e100ba78888fede3d0c4bc769f41b400000000000000000000000000000000000000000000000000b08416c4bb7d2e0000000000000000000000000000000000000000000000000000000003eb71f4000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

contract_instance = w3.eth.contract(address=address, abi=abi)
func_obj, func_params = contract_instance.decode_function_input(data)
print(func_params)

I don't get any result although the addresses I want to retrieve are in the data. I want a way to convert the data to addresses.


问:
How to change Copy Paste Menu Color in EditText for Android Jetpack Compose

I set my background color in android:Theme.Material.Light.NoActionBar to purple

<item name="android:background">#4B367C</item>

Now that purple is also reflecting in Copy/past menu making it unreadable

Any way to explicitly set the color for copy/past menu.


问:
Rendering before MUI Slide transition effect
I have this react component (i know its not great - improvement suggestions also welcome),  issue i have to focus on is that the render of formElements happens, then the transition effect takes place for Slide, so there is a flash of the component then the transition effect.

How do i prevent / delay the render of the formElements so that the transition happens before the render.

I have tried onEntered - setting showInputArea as true, onEntering - showInputArea as false, but that seems to stick at false and not trigger the callback to set true / show formElements, and removing the timeout, but that removes the transition effect or does not set as true to show elements.

```<code>import { Container, Slide } from '@material-ui/core';
import { useEffect, useState } from 'react';
import { FormElement } from '..';
import { shouldAutoAdvance } from '../Page/page.helpers';

const InputArea = ({
  components,
  currentPage,
  formInputsParentRef,
  iFrameId,
  pageComponentIds,
  slideDirection,
  visiblePageComponents,
}) => {
  // When the app is first loaded we should show the inputArea with no transition.
  const isFirstLoad = slideDirection === undefined;
  const [showInputArea, setShowInputArea] = useState(isFirstLoad);
  useEffect(() => {
    // When a user navigates through the form we trigger a slide transition by briefly hiding
    // then showing the inputArea thereby triggering the transition.
    setShowInputArea(isFirstLoad);
    setTimeout(() => {
      if (slideDirection !== undefined) {
        setShowInputArea(true);
      }
    }, 0.1);
  }, [currentPage]);
  const formElements = pageComponentIds.map((componentId) => {
    const elementData = components[`component_${componentId}`];
    const { component, input } = elementData;
    const { type, duration, text, mappedQuestionId } = component;

    return (
      // TODO here we are passing all the data we need down, but in some components we are also selecting from the store - investigate if / how we can and try to improve this
      <FormElement
        autoAdvance={shouldAutoAdvance(elementData, visiblePageComponents)}
        componentId={componentId}
        currentPage={currentPage}
        duration={duration}
        iFrameId={iFrameId}
        isVisible={visiblePageComponents.includes(elementData)}
        key={componentId}
        mappedQuestionId={mappedQuestionId}
        slideDirection={slideDirection}
        text={text}
        type={type}
        value={input?.value}
      />
    );
  });

  return (
    <Slide
      direction={slideDirection}
      in={showInputArea}
      exit={false}
      appear={false}
      timeout={500}
    >
      <Container ref={formInputsParentRef} maxWidth="md">
        {formElements}
      </Container>
    </Slide>
  );
};

export default InputArea;

</code>```

Body:
I have this react component (i know its not great - improvement suggestions also welcome),  issue i have to focus on is that the render of formElements happens, then the transition effect takes place for Slide, so there is a flash of the component then the transition effect.

How do i prevent / delay the render of the formElements so that the transition happens before the render.

I have tried onEntered - setting showInputArea as true, onEntering - showInputArea as false, but that seems to stick at false and not trigger the callback to set true / show formElements, and removing the timeout, but that removes the transition effect or does not set as true to show elements.

import { Container, Slide } from '@material-ui/core';
import { useEffect, useState } from 'react';
import { FormElement } from '..';
import { shouldAutoAdvance } from '../Page/page.helpers';

const InputArea = ({
  components,
  currentPage,
  formInputsParentRef,
  iFrameId,
  pageComponentIds,
  slideDirection,
  visiblePageComponents,
}) => {
  // When the app is first loaded we should show the inputArea with no transition.
  const isFirstLoad = slideDirection === undefined;
  const [showInputArea, setShowInputArea] = useState(isFirstLoad);
  useEffect(() => {
    // When a user navigates through the form we trigger a slide transition by briefly hiding
    // then showing the inputArea thereby triggering the transition.
    setShowInputArea(isFirstLoad);
    setTimeout(() => {
      if (slideDirection !== undefined) {
        setShowInputArea(true);
      }
    }, 0.1);
  }, [currentPage]);
  const formElements = pageComponentIds.map((componentId) => {
    const elementData = components[`component_${componentId}`];
    const { component, input } = elementData;
    const { type, duration, text, mappedQuestionId } = component;

    return (
      // TODO here we are passing all the data we need down, but in some components we are also selecting from the store - investigate if / how we can and try to improve this
      <FormElement
        autoAdvance={shouldAutoAdvance(elementData, visiblePageComponents)}
        componentId={componentId}
        currentPage={currentPage}
        duration={duration}
        iFrameId={iFrameId}
        isVisible={visiblePageComponents.includes(elementData)}
        key={componentId}
        mappedQuestionId={mappedQuestionId}
        slideDirection={slideDirection}
        text={text}
        type={type}
        value={input?.value}
      />
    );
  });

  return (
    <Slide
      direction={slideDirection}
      in={showInputArea}
      exit={false}
      appear={false}
      timeout={500}
    >
      <Container ref={formInputsParentRef} maxWidth="md">
        {formElements}
      </Container>
    </Slide>
  );
};

export default InputArea;


问:
EKS - ALB ingress unable to annotate backend port for Target group(K8S)
I have been using alb ingress to route traffic to my pods in backend but while annotating alb ingress I am unable to annotate backend port using alb.ingress.kubernetes.io/backend-port: 10987 only able to annotate protocol alb.ingress.kubernetes.io/backend-protocol: HTTPS.
By default it was taking port 1 as shown below

but I need the port to be 10987. Is it a bug or do we have any fix for this?

Ingress yaml

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: test-ingress
  namespace: development
  labels:
    app: test-ingress
  annotations:
    # Ingress Core Settings
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/scheme: internal
    alb.ingress.kubernetes.io/target-type: ip
    alb.ingress.kubernetes.io/load-balancer-name: test-alb
    alb.ingress.kubernetes.io/target-group-attributes: deregistration_delay.timeout_seconds=10
    alb.ingress.kubernetes.io/ip-address-type: dualstack
    # Health Check Settings
    alb.ingress.kubernetes.io/healthcheck-protocol: HTTPS
    alb.ingress.kubernetes.io/healthcheck-port: '10987'
    alb.ingress.kubernetes.io/healthcheck-interval-seconds: '15'
    alb.ingress.kubernetes.io/healthcheck-timeout-seconds: '5'
    alb.ingress.kubernetes.io/success-codes: '200'
    alb.ingress.kubernetes.io/healthy-threshold-count: '3'
    ## SSL Settings
    alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS":19065}]'
    alb.ingress.kubernetes.io/backend-protocol: HTTPS
    alb.ingress.kubernetes.io/backend-port: '10987'
spec:
    defaultBackend:
       service:
          name: some-test
          port:
             number: 10987
</code>```

Body:
I have been using alb ingress to route traffic to my pods in backend but while annotating alb ingress I am unable to annotate backend port using alb.ingress.kubernetes.io/backend-port: 10987 only able to annotate protocol alb.ingress.kubernetes.io/backend-protocol: HTTPS.
By default it was taking port 1 as shown below

but I need the port to be 10987. Is it a bug or do we have any fix for this?

Ingress yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: test-ingress
  namespace: development
  labels:
    app: test-ingress
  annotations:
    # Ingress Core Settings
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/scheme: internal
    alb.ingress.kubernetes.io/target-type: ip
    alb.ingress.kubernetes.io/load-balancer-name: test-alb
    alb.ingress.kubernetes.io/target-group-attributes: deregistration_delay.timeout_seconds=10
    alb.ingress.kubernetes.io/ip-address-type: dualstack
    # Health Check Settings
    alb.ingress.kubernetes.io/healthcheck-protocol: HTTPS
    alb.ingress.kubernetes.io/healthcheck-port: '10987'
    alb.ingress.kubernetes.io/healthcheck-interval-seconds: '15'
    alb.ingress.kubernetes.io/healthcheck-timeout-seconds: '5'
    alb.ingress.kubernetes.io/success-codes: '200'
    alb.ingress.kubernetes.io/healthy-threshold-count: '3'
    ## SSL Settings
    alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS":19065}]'
    alb.ingress.kubernetes.io/backend-protocol: HTTPS
    alb.ingress.kubernetes.io/backend-port: '10987'
spec:
    defaultBackend:
       service:
          name: some-test
          port:
             number: 10987


问:
How to close opened excel file from excel application using python?
I want to close excel file using python when excel workbook is open but i am not able to close.

I did tried file.close() but it's throwing error so please can you guys guide what should i do.


问:
Error in chol.default(crossprod(x)) : the leading minor of order 1 is not positive definite in FRD
Here is my code:

```<code>DGF<-function(n,a){
  x<-runif(n,-a,a)
  y<-ifelse(x>=0,1+x^2+10,1+x^2+1)
  w_s<-ifelse(x>=0,1,0)
  data<-data.frame(x,y,w_s)
  return(data)
}
##non-parametric method:
## we will see the treatment effect when the kernel is triangular:
a<-c()
b1_t<-c()
b2_t<-c()
b3_t<-c()
b4_t<-c()
for (i in 1:T){
  a[i]<-runif(1,min=0,max=10)
  data<-DGF(n,a[i])
  locfit1<-rdrobust(data$y,data$x,p=1,c=0,kernel="triangular")
  b1_t[i]<-locfit1$coef[1]
  locfit2<-rdrobust(data$y,data$x,p=2,c=0,kernel="triangular")
  b2_t[i]<-locfit2$coef[1]
  locfit3<-rdrobust(data$y,data$x,p=3,c=0,kernel="triangular")
  b3_t[i]<-locfit3$coef[1]
  locfit4<-rdrobust(data$y,data$x,p=4,c=0,kernel="triangular")
  b4_t[i]<-locfit4$coef[1]
}
</code>```

when I run it, it always shows that

```<code>Error in chol.default(crossprod(x)) :
  the leading minor of order 1 is not positive definite
</code>```

I don't konw how to fix it,is anyone can help me with this?thank you very much

I trid to wide the range of a, but it doesn't work.

Body:
Here is my code:

DGF<-function(n,a){
  x<-runif(n,-a,a)
  y<-ifelse(x>=0,1+x^2+10,1+x^2+1)
  w_s<-ifelse(x>=0,1,0)
  data<-data.frame(x,y,w_s)
  return(data)
}
##non-parametric method:
## we will see the treatment effect when the kernel is triangular:
a<-c()
b1_t<-c()
b2_t<-c()
b3_t<-c()
b4_t<-c()
for (i in 1:T){
  a[i]<-runif(1,min=0,max=10)
  data<-DGF(n,a[i])
  locfit1<-rdrobust(data$y,data$x,p=1,c=0,kernel="triangular")
  b1_t[i]<-locfit1$coef[1]
  locfit2<-rdrobust(data$y,data$x,p=2,c=0,kernel="triangular")
  b2_t[i]<-locfit2$coef[1]
  locfit3<-rdrobust(data$y,data$x,p=3,c=0,kernel="triangular")
  b3_t[i]<-locfit3$coef[1]
  locfit4<-rdrobust(data$y,data$x,p=4,c=0,kernel="triangular")
  b4_t[i]<-locfit4$coef[1]
}

when I run it, it always shows that

Error in chol.default(crossprod(x)) :
  the leading minor of order 1 is not positive definite

I don't konw how to fix it,is anyone can help me with this?thank you very much

I trid to wide the range of a, but it doesn't work.


问:
Django links, url parameters overwriting
I've got django template with table/list with sorting action:

```<code><a href="?order_by=name">Name</a>
</code>```

and later I've got paging:

```<code> <a href="?page=1">first</a>
</code>```

What I want to achieve is a link:
http://localhost:8000/list/?page=3&order_by=name

but, while  - clicking a link, I can get either page or order_by.

How to solve it the 'django way'? (for 2 and more parameters).

More details -

```<code>def list_view(request):
    items_list = model.objects.all()
    # Filter
    request_filter = request.GET.get('filter',"")
    if request_filter:
        items_list = items_list.filter(model__icontains=request_filter)

    # Paging
    paginator = Paginator(list, 2) # Show 2 items per page.
    page_number = request.GET.get('page',1)
    page_obj = paginator.get_page(page_number)
    items_list = paginator.page(page_number)

    return render(request,'list.html', {'list' : items_list, 'filter':request_filter, 'page_obj': page_obj})
</code>```

and template: (related parts)

```<code>  <form action="" method="GET">
        <input type="text"  name="filter" value={{filter}} >
        <button  class="btn btn-sm btn-outline-success" type="submit">Filtruj</button>
    </form>

<table class="table">
        <thead>
            <tr>
                <th><a href="?order_by=name">Name</a></th>

etc </table>

<div class="pagination">
        <span class="step-links">
            {% if page_obj.has_previous %}
                <a href="?page=1">« first</a>
                <a href="?page={{ page_obj.previous_page_number }}">previous</a>
            {% endif %}
</code>```

Body:
I've got django template with table/list with sorting action:

Name

and later I've got paging:

 first

What I want to achieve is a link:
http://localhost:8000/list/?page=3&order_by=name

but, while  - clicking a link, I can get either page or order_by.

How to solve it the 'django way'? (for 2 and more parameters).

More details -

def list_view(request):
    items_list = model.objects.all()
    # Filter
    request_filter = request.GET.get('filter',"")
    if request_filter:
        items_list = items_list.filter(model__icontains=request_filter)

    # Paging
    paginator = Paginator(list, 2) # Show 2 items per page.
    page_number = request.GET.get('page',1)
    page_obj = paginator.get_page(page_number)
    items_list = paginator.page(page_number)

    return render(request,'list.html', {'list' : items_list, 'filter':request_filter, 'page_obj': page_obj})

and template: (related parts)

  <form action="" method="GET">
        <input type="text"  name="filter" value={{filter}} >
        <button  class="btn btn-sm btn-outline-success" type="submit">Filtruj</button>
    </form>

                Name

etc

            {% if page_obj.has_previous %}
                « first
                previous
            {% endif %}


问:
Gatsby blog featured image "cannot return null for non-nullable field WPNodeWithFeaturedImageToMediaItemConnectionEdgeType.node"
I hope this is the right place to put this, I think it’s an issue with wp-graphql / woographql. Just a bit of background - I’ve been trying to get a WooCommerce / Gatsby project with around 2,200 products to build for over a month now. I initially set up a Lightsail server to deal with the wordpress side of things, but in gatsby-source-wordpress I had to set the requestConcurrency / perPage to 1 or it would crash the server. This was painfully slow, so I’ve moved over to a DigitalOcean server which is faster (requestConcurrency of 2 and a perPage of 5), however it is bringing up a recurring issue I’ve had on previous test WP instances.

I have a custom taxonomy called ‘Collections’. Within this custom taxonomy I have created a ACF Post Object field called ‘featured product’, which is just a WooCommerce product. I’ve created 40+ collections and attached a featured WooCommerce product for each.

I have a custom taxonomy called ‘Collections’. Within this custom taxonomy I have created a ACF Post Object field called ‘featured product’, which is just a WooCommerce product. I’ve created 40+ collections and attached a featured WooCommerce product for each. The data for the featured product pulls through fine, all except for the products featured image, for which it doesn’t seem to have created a node for:

These products definitely have featured images attached, it just doesn’t seem to be pulling this data through. When I run this on the WP server using GraphiQL you can see the Product does has an image:

Deprecated function?

This is also repeatedly appearing in my debug.log:

[02-Jan-2023 18:42:55 UTC] PHP Deprecated: Function WPGraphQL\Connection\TermObjects::get_connection_config is deprecated since version 1.13.0! Use \WPGraphQL\Type\Connection\TermObjects::get_connection_config instead. in /var/www/html/wp-includes/functions.php on line 5383`

Plugins Used

I’m using the following plugins on the WP server:

WP Gatsby (v2.3.3)

WP GraphQL (v1.12.2 - I’ve used so many different versions of this now that I’ve lost count, including the current version, but it has definitely built using this version before )

WPGraphQL for Advanced Custom Fields (v0.6.1)

WPGraphQL WooCommerce (WooGraphQL) (v0.11.2) (I have tried all this version and 12.0.0 - this version has built in the past)

WooCommerce (v7.2.2)

Advanced Custom Fields Pro (V 6.0.6 )

Custom Post Type UI (v1.13.1)

And on my local gatsby package.json:

```<code>{
    "gatsby": "^5.3.3",
    "gatsby-alias-imports": "^1.0.6",
    "gatsby-link": "5.3.1",
    "gatsby-plugin-algolia": "^1.0.2",
    "gatsby-plugin-apollo": "^4.0.3",
    "gatsby-plugin-image": "^3.3.2",
    "gatsby-plugin-manifest": "^5.3.1",
    "gatsby-plugin-offline": "^6.3.1",
    "gatsby-plugin-react-helmet": "^6.3.0",
    "gatsby-plugin-s3": "^0.3.8",
    "gatsby-plugin-sharp": "^5.3.2",
    "gatsby-plugin-sitemap": "^6.3.1",
    "gatsby-plugin-svgr": "^3.0.0-beta.0",
    "gatsby-plugin-svgr-svgo": "^2.0.0",
    "gatsby-react-router-scroll": "^6.3.0",
    "gatsby-source-filesystem": "^5.3.1",
    "gatsby-source-wordpress": "7.3.2",
    "gatsby-transformer-sharp": "^5.3.1"
}
</code>```

It has built on the AWS server before with this same plugins, it just seems to occur when I moved the server to Digital Ocean - has anyone seen anything like this before?

I have tried different combinations of WP-graphQL versions on wordpress, and as well as many other combos of plugins on both gatsby and wordpress.

Tried updating gatsby from v4 to v5, and relevant source plugins

Had another server on lightsail running fine, but very slow to build.

I have deleted the lock file, and restored it afterwards since it made no difference.

Interestingly, I've disabled all wordpress plugins, and now the featured images for the blog on the homepage are showing up again.

Body:
I hope this is the right place to put this, I think it’s an issue with wp-graphql / woographql. Just a bit of background - I’ve been trying to get a WooCommerce / Gatsby project with around 2,200 products to build for over a month now. I initially set up a Lightsail server to deal with the wordpress side of things, but in gatsby-source-wordpress I had to set the requestConcurrency / perPage to 1 or it would crash the server. This was painfully slow, so I’ve moved over to a DigitalOcean server which is faster (requestConcurrency of 2 and a perPage of 5), however it is bringing up a recurring issue I’ve had on previous test WP instances.

I have a custom taxonomy called ‘Collections’. Within this custom taxonomy I have created a ACF Post Object field called ‘featured product’, which is just a WooCommerce product. I’ve created 40+ collections and attached a featured WooCommerce product for each.

I have a custom taxonomy called ‘Collections’. Within this custom taxonomy I have created a ACF Post Object field called ‘featured product’, which is just a WooCommerce product. I’ve created 40+ collections and attached a featured WooCommerce product for each. The data for the featured product pulls through fine, all except for the products featured image, for which it doesn’t seem to have created a node for:

These products definitely have featured images attached, it just doesn’t seem to be pulling this data through. When I run this on the WP server using GraphiQL you can see the Product does has an image:

Deprecated function?

This is also repeatedly appearing in my debug.log:

[02-Jan-2023 18:42:55 UTC] PHP Deprecated: Function WPGraphQL\Connection\TermObjects::get_connection_config is deprecated since version 1.13.0! Use \WPGraphQL\Type\Connection\TermObjects::get_connection_config instead. in /var/www/html/wp-includes/functions.php on line 5383`

Plugins Used

I’m using the following plugins on the WP server:

WP Gatsby (v2.3.3)

WP GraphQL (v1.12.2 - I’ve used so many different versions of this now that I’ve lost count, including the current version, but it has definitely built using this version before )

WPGraphQL for Advanced Custom Fields (v0.6.1)

WPGraphQL WooCommerce (WooGraphQL) (v0.11.2) (I have tried all this version and 12.0.0 - this version has built in the past)

WooCommerce (v7.2.2)

Advanced Custom Fields Pro (V 6.0.6 )

Custom Post Type UI (v1.13.1)

And on my local gatsby package.json:

{
    "gatsby": "^5.3.3",
    "gatsby-alias-imports": "^1.0.6",
    "gatsby-link": "5.3.1",
    "gatsby-plugin-algolia": "^1.0.2",
    "gatsby-plugin-apollo": "^4.0.3",
    "gatsby-plugin-image": "^3.3.2",
    "gatsby-plugin-manifest": "^5.3.1",
    "gatsby-plugin-offline": "^6.3.1",
    "gatsby-plugin-react-helmet": "^6.3.0",
    "gatsby-plugin-s3": "^0.3.8",
    "gatsby-plugin-sharp": "^5.3.2",
    "gatsby-plugin-sitemap": "^6.3.1",
    "gatsby-plugin-svgr": "^3.0.0-beta.0",
    "gatsby-plugin-svgr-svgo": "^2.0.0",
    "gatsby-react-router-scroll": "^6.3.0",
    "gatsby-source-filesystem": "^5.3.1",
    "gatsby-source-wordpress": "7.3.2",
    "gatsby-transformer-sharp": "^5.3.1"
}

It has built on the AWS server before with this same plugins, it just seems to occur when I moved the server to Digital Ocean - has anyone seen anything like this before?

I have tried different combinations of WP-graphQL versions on wordpress, and as well as many other combos of plugins on both gatsby and wordpress.

Tried updating gatsby from v4 to v5, and relevant source plugins

Had another server on lightsail running fine, but very slow to build.

I have deleted the lock file, and restored it afterwards since it made no difference.

Interestingly, I've disabled all wordpress plugins, and now the featured images for the blog on the homepage are showing up again.


问:
What's the difference between ensure_future and create_task?
Please explain to me when should I use asyncio.ensure_future and create_task and what's the difference.

We can write like this:

```<code>async def run(r):
    url = "http://localhost:8080/{}"
    tasks = []

    # Fetch all responses within one Client session,
    # keep connection alive for all requests.
    async with ClientSession() as session:
        for i in range(r):
            task = asyncio.ensure_future(fetch(url.format(i), session))
            tasks.append(task)

        responses = await asyncio.gather(*tasks)
        # you now have all response bodies in this variable
        print(responses)
</code>```

Or like this:

```<code>async def get_all(*names: str):
    started_at = time.time()

    # Create tasks, so we start requesting all of them concurrently
    tasks = [asyncio.create_task(get_pokemon(name)) for name in names]

    # Await ALL
    results = await asyncio.gather(*tasks)

    for result in results:
        if result:
            pokemon = parse_pokemon(result)
            print(f" {pokemon.name} is of type(s) {','.join(pokemon.types)}")
        else:
            print(f"❌ No data found for...")
</code>```

Body:
Please explain to me when should I use asyncio.ensure_future and create_task and what's the difference.

We can write like this:

async def run(r):
    url = "http://localhost:8080/{}"
    tasks = []

    # Fetch all responses within one Client session,
    # keep connection alive for all requests.
    async with ClientSession() as session:
        for i in range(r):
            task = asyncio.ensure_future(fetch(url.format(i), session))
            tasks.append(task)

        responses = await asyncio.gather(*tasks)
        # you now have all response bodies in this variable
        print(responses)

Or like this:

async def get_all(*names: str):
    started_at = time.time()

    # Create tasks, so we start requesting all of them concurrently
    tasks = [asyncio.create_task(get_pokemon(name)) for name in names]

    # Await ALL
    results = await asyncio.gather(*tasks)

    for result in results:
        if result:
            pokemon = parse_pokemon(result)
            print(f" {pokemon.name} is of type(s) {','.join(pokemon.types)}")
        else:
            print(f"❌ No data found for...")


问:
Lambda function not calling S3 bucket upload
My Lambda function does not call the S3 upload function where it is supposed to send a URL back that will be assigned to the DynamoDB database. I can't seem to pin-point what's wrong here. I have tried to just call the Lambda upload to S3 function without the rest of the code and it work's fine.</p>
```<code>const AWS = require('aws-sdk');
const s3 = new AWS.S3();

const BUCKET_NAME = 'BUCKET_NAME';
const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context) => {
  let body;
  let statusCode = 200;

  const uploadFileToS3 = async (fileBinary) => {
    try {
      const base64File = fileBinary;
      const decodedFile = Buffer.from(
        base64File.replace(/^data:image\/\w+;base64,/, ''),
        'base64'
      );
      const params = {
        Bucket: BUCKET_NAME,
        Key: `images/${new Date().toISOString()}.jpeg`,
        Body: decodedFile,
        ContentType: 'image/jpeg',
      };

      const uploadResult = await s3.upload(params).promise();
      console.log(uploadResult)
      return uploadResult;
    } catch (e) {
      console.error(e);
    }
  };

  try {
    switch (event.routeKey) {
      case 'PUT /items':
        let requestJSON = JSON.parse(event.body);
        const fileURL = await uploadFileToS3(requestJSON.itemPicture);
        await dynamo
          .put({
            TableName: 'TABLE_NAME',
            Item: {
              itemId: requestJSON.itemId,
              userId: requestJSON.userId,
              itemTitle: requestJSON.itemTitle,
              itemDesc: requestJSON.itemDesc,
              itemLocation: requestJSON.itemLocation,
              itemPrice: requestJSON.itemPrice,
              itemPicture: fileURL,
            },
          })
          .promise();
        body = `Put item ${requestJSON.itemId}`;
        break;
      default:
        throw new Error(`Unsupported route: ` + `${event.routeKey}`);
    }
  } catch (err) {
    statusCode = 400;
    body = err.message;
  } finally {
    body = JSON.stringify(body);
  }

  return {
    statusCode,
    body,
    headers,
  };
};

</code>```

Body:
My Lambda function does not call the S3 upload function where it is supposed to send a URL back that will be assigned to the DynamoDB database. I can't seem to pin-point what's wrong here. I have tried to just call the Lambda upload to S3 function without the rest of the code and it work's fine.

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

const BUCKET_NAME = 'BUCKET_NAME';
const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context) => {
  let body;
  let statusCode = 200;

  const uploadFileToS3 = async (fileBinary) => {
    try {
      const base64File = fileBinary;
      const decodedFile = Buffer.from(
        base64File.replace(/^data:image\/\w+;base64,/, ''),
        'base64'
      );
      const params = {
        Bucket: BUCKET_NAME,
        Key: `images/${new Date().toISOString()}.jpeg`,
        Body: decodedFile,
        ContentType: 'image/jpeg',
      };

      const uploadResult = await s3.upload(params).promise();
      console.log(uploadResult)
      return uploadResult;
    } catch (e) {
      console.error(e);
    }
  };

  try {
    switch (event.routeKey) {
      case 'PUT /items':
        let requestJSON = JSON.parse(event.body);
        const fileURL = await uploadFileToS3(requestJSON.itemPicture);
        await dynamo
          .put({
            TableName: 'TABLE_NAME',
            Item: {
              itemId: requestJSON.itemId,
              userId: requestJSON.userId,
              itemTitle: requestJSON.itemTitle,
              itemDesc: requestJSON.itemDesc,
              itemLocation: requestJSON.itemLocation,
              itemPrice: requestJSON.itemPrice,
              itemPicture: fileURL,
            },
          })
          .promise();
        body = `Put item ${requestJSON.itemId}`;
        break;
      default:
        throw new Error(`Unsupported route: ` + `${event.routeKey}`);
    }
  } catch (err) {
    statusCode = 400;
    body = err.message;
  } finally {
    body = JSON.stringify(body);
  }

  return {
    statusCode,
    body,
    headers,
  };
};


问:
Get final query from executeBatch()
How to get the final batch SQL query from Spring boot SQL statement. I am connecting to PostgreSQL database with Java 8 and spring boot.

String sqlQuery = "insert into table1 (id, name) values (?, ?)";

PreparedStatement pstmt = connection.prepareStatement(sqlQuery);
pstmt.setInt(1, 1);
pstmt.setString(2, "name1");
pstmt.addBatch();

pstmt.setInt(1, 2);
pstmt.setString(2, "name2");
pstmt.addBatch();

pstmt.executeBatch();

System.out.println(pstmt);
```
<p><strong>Output:</strong></p>
<pre class="lang-sql prettyprint-override"><code>insert into table1 (id, name) values (2, name2)
</code>```

Expected Output:

insert into table1 (id, name) values (1, name1), (2, name2)
```

I am getting the last SQL query instead of the batch SQL query.

Title: Get final query from executeBatch()

Body:
How to get the final batch SQL query from Spring boot SQL statement. I am connecting to PostgreSQL database with Java 8 and spring boot.

String sqlQuery = "insert into table1 (id, name) values (?, ?)";

PreparedStatement pstmt = connection.prepareStatement(sqlQuery);
pstmt.setInt(1, 1);
pstmt.setString(2, "name1");
pstmt.addBatch();

pstmt.setInt(1, 2);
pstmt.setString(2, "name2");
pstmt.addBatch();

pstmt.executeBatch();

System.out.println(pstmt);

Output:

insert into table1 (id, name) values (2, name2)

Expected Output:

insert into table1 (id, name) values (1, name1), (2, name2)

I am getting the last SQL query instead of the batch SQL query.


问:
php thumbnail image problem (some images flipped or rotated)
i use php to create thumbnail of image on upload. But i have some issues. Sometimes thumbnail is fliped vertically or horizontally or 90º rotated ... and i dont know why... some images are correct some not.

Don´t you know, where could be problem?

UPDATE:
imagecreatefromjpeg load image wrong rotated...

I´m using this code...

```<code>class ThumbImage
{
    private $source;
    public function __construct($sourceImagePath)
    {
        $this->source = $sourceImagePath;
    }
    public function createThumb($destImagePath, $thumbWidth=100)
    {
        $sourceImage = imagecreatefromjpeg($this->source);
        $orgWidth = imagesx($sourceImage);
        $orgHeight = imagesy($sourceImage);
        $thumbHeight = floor($orgHeight * ($thumbWidth / $orgWidth));
        $destImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
        imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $orgWidth, $orgHeight);
        imagejpeg($destImage, $destImagePath,100);
        imagedestroy($sourceImage);
        imagedestroy($destImage);
    }
}
</code>```

and call it with:

```<code>$objThumbImage = new ThumbImage($uploadFilePath);
        $objThumbImage->createThumb($uploadFileThumbPath, 640);
</code>```

Body:
i use php to create thumbnail of image on upload. But i have some issues. Sometimes thumbnail is fliped vertically or horizontally or 90º rotated ... and i dont know why... some images are correct some not.

Don´t you know, where could be problem?

UPDATE:
imagecreatefromjpeg load image wrong rotated...

I´m using this code...

class ThumbImage
{
    private $source;
    public function __construct($sourceImagePath)
    {
        $this->source = $sourceImagePath;
    }
    public function createThumb($destImagePath, $thumbWidth=100)
    {
        $sourceImage = imagecreatefromjpeg($this->source);
        $orgWidth = imagesx($sourceImage);
        $orgHeight = imagesy($sourceImage);
        $thumbHeight = floor($orgHeight * ($thumbWidth / $orgWidth));
        $destImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
        imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $orgWidth, $orgHeight);
        imagejpeg($destImage, $destImagePath,100);
        imagedestroy($sourceImage);
        imagedestroy($destImage);
    }
}

and call it with:

$objThumbImage = new ThumbImage($uploadFilePath);
        $objThumbImage->createThumb($uploadFileThumbPath, 640);


问:
Returnfase is not working eventhough mandatory fields are not filled itsis going to save not stopping.How can i resolve it?This is my script
```<code>

<script>
function po_num(){
//alert ("11")

  var po = document.getElementById('add_service_order_service_order_no').value
//alert(po);
//return false;

    if (po == "")
    {
            alert("Please fill PO Number");
       Event.stop(e);
    }
}

</script>
</code>```

Returnfalse is not working eventhough mandatory fields are not filled it is going to save, not stopping.How can i resolve it?


问:
How can I handle with special characters or scape them on spark version 3.3.0?
Previously I was using spark version 3.2.1 to read data from SAP database by JDBC connector, I had no issues to perform the following steps:

```<code>df_1 = spark.read.format("jdbc") \
.option("url", "URL_LINK") \
.option("dbtable", 'DATABASE."/ABC/TABLE"') \
.option("user", "USER_HERE") \
.option("password", "PW_HERE") \
.option("driver", "com.sap.db.jdbc.Driver") \
.load()

display(df_1)

df_2 = df_1.filter("`/ABC/COLUMN` = 'ID_HERE'")

display(df_2)
</code>```

This code above runs as it should, returning expected rows.

Since I updated my spark version to 3.3.0, because I need to have the new trigger 'availableNow' (trigger from streaming process), this process above started to fail, does not run at all.

Please follow the error message bellow.

```<code>-----------------------------------------------------------------
----------
ParseException                            Traceback (most recent
call last)
<command-963568451378752> in <cell line: 3>()
      1 df_2 = df_1.filter("`/ABC/COLUMN` = 'ID_HERE'")
      2
----> 3 display(df_2)

/databricks/python_shell/dbruntime/display.py in display(self,
input, *args, **kwargs)
     81                     raise Exception('Triggers can only be
set for streaming queries.')
     82
---> 83                 self.add_custom_display_data("table",
input._jdf)
     84
     85         elif isinstance(input, list):

/databricks/python_shell/dbruntime/display.py in
add_custom_display_data(self, data_type, data)
     34     def add_custom_display_data(self, data_type, data):
     35         custom_display_key = str(uuid.uuid4())
---> 36         return_code =
self.entry_point.addCustomDisplayData(custom_display_key,
data_type, data)
     37         ip_display({
     38             "application/vnd.databricks.v1+display":
custom_display_key,

/databricks/spark/python/lib/py4j-0.10.9.5-
src.zip/py4j/java_gateway.py in __call__(self, *args)
   1319
   1320         answer =
self.gateway_client.send_command(command)
-> 1321         return_value = get_return_value(
   1322             answer, self.gateway_client, self.target_id,
self.name)
   1323

/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
    200                 # Hide where the exception came from that
shows a non-Pythonic
    201                 # JVM exception message.
--> 202                 raise converted from None
    203             else:
    204                 raise

ParseException:
[PARSE_SYNTAX_ERROR] Syntax error at or near '/': extra input
'/'(line 1, pos 0)

== SQL ==
/ABC/COLUMN
^^^
</code>```

I've already tried to format in so many different ways, following the instructions on: https://spark.apache.org/docs/latest/sql-ref-literals.html . I've already tried to use function string by previously formatting the string, also tried raw string, but nothing seems to work as supposed.

Another important information, I've tried to create a dummy code for you to be able to replicate the issue, but when I create those tables with slashes '/ABC/TABLE' containing  columns with slashes '/ABC/COLUMN' directly on pyspark, instead of using JDBC connector, it actually works, I was able to filter.

As described above, I am expecting to perform the filter, no matter the spark version.

Body:
Previously I was using spark version 3.2.1 to read data from SAP database by JDBC connector, I had no issues to perform the following steps:

df_1 = spark.read.format("jdbc") \
.option("url", "URL_LINK") \
.option("dbtable", 'DATABASE."/ABC/TABLE"') \
.option("user", "USER_HERE") \
.option("password", "PW_HERE") \
.option("driver", "com.sap.db.jdbc.Driver") \
.load()

display(df_1)

df_2 = df_1.filter("`/ABC/COLUMN` = 'ID_HERE'")

display(df_2)

This code above runs as it should, returning expected rows.

Since I updated my spark version to 3.3.0, because I need to have the new trigger 'availableNow' (trigger from streaming process), this process above started to fail, does not run at all.

Please follow the error message bellow.

-----------------------------------------------------------------
----------
ParseException                            Traceback (most recent
call last)
<command-963568451378752> in <cell line: 3>()
      1 df_2 = df_1.filter("`/ABC/COLUMN` = 'ID_HERE'")
      2
----> 3 display(df_2)

/databricks/python_shell/dbruntime/display.py in display(self,
input, *args, **kwargs)
     81                     raise Exception('Triggers can only be
set for streaming queries.')
     82
---> 83                 self.add_custom_display_data("table",
input._jdf)
     84
     85         elif isinstance(input, list):

/databricks/python_shell/dbruntime/display.py in
add_custom_display_data(self, data_type, data)
     34     def add_custom_display_data(self, data_type, data):
     35         custom_display_key = str(uuid.uuid4())
---> 36         return_code =
self.entry_point.addCustomDisplayData(custom_display_key,
data_type, data)
     37         ip_display({
     38             "application/vnd.databricks.v1+display":
custom_display_key,

/databricks/spark/python/lib/py4j-0.10.9.5-
src.zip/py4j/java_gateway.py in __call__(self, *args)
   1319
   1320         answer =
self.gateway_client.send_command(command)
-> 1321         return_value = get_return_value(
   1322             answer, self.gateway_client, self.target_id,
self.name)
   1323

/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
    200                 # Hide where the exception came from that
shows a non-Pythonic
    201                 # JVM exception message.
--> 202                 raise converted from None
    203             else:
    204                 raise

ParseException:
[PARSE_SYNTAX_ERROR] Syntax error at or near '/': extra input
'/'(line 1, pos 0)

== SQL ==
/ABC/COLUMN
^^^

I've already tried to format in so many different ways, following the instructions on: https://spark.apache.org/docs/latest/sql-ref-literals.html . I've already tried to use function string by previously formatting the string, also tried raw string, but nothing seems to work as supposed.

Another important information, I've tried to create a dummy code for you to be able to replicate the issue, but when I create those tables with slashes '/ABC/TABLE' containing  columns with slashes '/ABC/COLUMN' directly on pyspark, instead of using JDBC connector, it actually works, I was able to filter.

As described above, I am expecting to perform the filter, no matter the spark version.


问:
$gte / $lte filters not working in lokijs
I am generating query based on user input and passing it onto LokiJS to handle. However, query doesn't seem to take effect (everything is returned as it is).

Logic to generate query :-

```<code>function prepareQueryFromOptions(options: GetAllTransactionsOptions) {
  const query: Record<string, any> = {
    timestamp: {
      "$gte": options.dateRange.from.getTime(),
      "$lte": options.dateRange.to.getTime(),
    },
  };
  if (options.accounts) {
    query.accountId = {
      "$in": options.accounts,
    };
  }
  if (options.categories) {
    query.category = {
      "$in": options.categories,
    };
  }

  return query;
}
</code>```

Using above function as below:

```<code>const query: Record<string, any> = prepareQueryFromOptions(options);

const transactions: Transaction[] = transactionsCollection.chain().find(query).simplesort('timestamp').data();
</code>```

My Failing Testcase:

```<code>const AUG_1_2022 = new Date(2022, 7, 1);
const AUG_5_2022 = new Date(2022, 7, 5);
const AUG_12_2022 = new Date(2022, 7, 12);

it('getAllTransactions()', async () => {
    let txs1 = await transactions.getAllTransactions({
      dateRange: {
        from: AUG_1_2022,
        to: AUG_12_2022,
      },
    });
    expect(txs1.length).toBe(2); // Successful (Both transactions are returned)

    let txs = await transactions.getAllTransactions({
      dateRange: {
        from: AUG_1_2022,
        to: AUG_5_2022,
      },
    });
    expect(txs.length).toBe(1); // Failed since again both the transactions are returned
  });
</code>```

Body:
I am generating query based on user input and passing it onto LokiJS to handle. However, query doesn't seem to take effect (everything is returned as it is).

Logic to generate query :-

function prepareQueryFromOptions(options: GetAllTransactionsOptions) {
  const query: Record<string, any> = {
    timestamp: {
      "$gte": options.dateRange.from.getTime(),
      "$lte": options.dateRange.to.getTime(),
    },
  };
  if (options.accounts) {
    query.accountId = {
      "$in": options.accounts,
    };
  }
  if (options.categories) {
    query.category = {
      "$in": options.categories,
    };
  }

  return query;
}

Using above function as below:

const query: Record<string, any> = prepareQueryFromOptions(options);

const transactions: Transaction[] = transactionsCollection.chain().find(query).simplesort('timestamp').data();

My Failing Testcase:

const AUG_1_2022 = new Date(2022, 7, 1);
const AUG_5_2022 = new Date(2022, 7, 5);
const AUG_12_2022 = new Date(2022, 7, 12);

it('getAllTransactions()', async () => {
    let txs1 = await transactions.getAllTransactions({
      dateRange: {
        from: AUG_1_2022,
        to: AUG_12_2022,
      },
    });
    expect(txs1.length).toBe(2); // Successful (Both transactions are returned)

    let txs = await transactions.getAllTransactions({
      dateRange: {
        from: AUG_1_2022,
        to: AUG_5_2022,
      },
    });
    expect(txs.length).toBe(1); // Failed since again both the transactions are returned
  });


问:
magento2 modify Elasticsearch data
I have magento2 elastic search data. I want to add some data into it. Here is result of current data of following elastic search query

```<code>GET /alpha-m2_en_catalog_product_*/_mapping
</code>```

Now i want the result of this query should contain additional "fields" data as shown in below image

```<code>"fields":{
   "Keyword":{
      "type": "keyword"
      "ignore_above" : 256
   }
}
</code>```

How is it possible in Magento2 to grammatically add this data in the result of

```<code>bin/magento indexer:reindex
</code>```

Title: magento2 modify Elasticsearch data

Body:
I have magento2 elastic search data. I want to add some data into it. Here is result of current data of following elastic search query

GET /alpha-m2_en_catalog_product_*/_mapping

Now i want the result of this query should contain additional "fields" data as shown in below image

"fields":{
   "Keyword":{
      "type": "keyword"
      "ignore_above" : 256
   }
}

How is it possible in Magento2 to grammatically add this data in the result of

bin/magento indexer:reindex


问:
Loading dataframe from url on hackerrank
Doing a hackerrank problem and can't figure out why I can't load a dataframe from the URL given

```<code>import pandas as pd
import io
import requests
import urllib

url = "https://hrcdn.net/restoflink.csv"

df = pd.read_csv(url2)
</code>```

I get the following error:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.9/urllib/request.py", line 1346, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "/usr/local/lib/python3.9/http/client.py", line 1253, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/local/lib/python3.9/http/client.py", line 1299, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/local/lib/python3.9/http/client.py", line 1248, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/local/lib/python3.9/http/client.py", line 1008, in _send_output
    self.send(msg)
  File "/usr/local/lib/python3.9/http/client.py", line 948, in send
    self.connect()
  File "/usr/local/lib/python3.9/http/client.py", line 1415, in connect
    super().connect()
  File "/usr/local/lib/python3.9/http/client.py", line 919, in connect
    self.sock = self._create_connection(
  File "/usr/local/lib/python3.9/socket.py", line 822, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/local/lib/python3.9/socket.py", line 953, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -3] Temporary failure in name resolution
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/tmp/submission/20230103/11/53/hackerrank-725270a2c246ce29a6de7a3dd77fab59/code/Solution.py", line 10, in <module>
    df = pd.read_csv(url)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 610, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 462, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 819, in __init__
    self._engine = self._make_engine(self.engine)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 1050, in _make_engine
    return mapping[engine](self.f, **self.options)  # type: ignore[call-arg]
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 1867, in __init__
    self._open_handles(src, kwds)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 1362, in _open_handles
    self.handles = get_handle(
  File "/usr/local/lib/python3.9/site-packages/pandas/io/common.py", line 558, in get_handle
    ioargs = _get_filepath_or_buffer(
  File "/usr/local/lib/python3.9/site-packages/pandas/io/common.py", line 289, in _get_filepath_or_buffer
    req = urlopen(filepath_or_buffer)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/common.py", line 195, in urlopen
    return urllib.request.urlopen(*args, **kwargs)
  File "/usr/local/lib/python3.9/urllib/request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/lib/python3.9/urllib/request.py", line 517, in open
    response = self._open(req, data)
  File "/usr/local/lib/python3.9/urllib/request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "/usr/local/lib/python3.9/urllib/request.py", line 494, in _call_chain
    result = func(*args)
  File "/usr/local/lib/python3.9/urllib/request.py", line 1389, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
  File "/usr/local/lib/python3.9/urllib/request.py", line 1349, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -3] Temporary failure in name resolution>
</code>```

Any help would be greatly appreciated

I have tried using the requests module to load the csv then using pd.read_csv() but I got another error then

Body:
Doing a hackerrank problem and can't figure out why I can't load a dataframe from the URL given

import pandas as pd
import io
import requests
import urllib

url = "https://hrcdn.net/restoflink.csv"

df = pd.read_csv(url2)

I get the following error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/urllib/request.py", line 1346, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "/usr/local/lib/python3.9/http/client.py", line 1253, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/local/lib/python3.9/http/client.py", line 1299, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/local/lib/python3.9/http/client.py", line 1248, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/local/lib/python3.9/http/client.py", line 1008, in _send_output
    self.send(msg)
  File "/usr/local/lib/python3.9/http/client.py", line 948, in send
    self.connect()
  File "/usr/local/lib/python3.9/http/client.py", line 1415, in connect
    super().connect()
  File "/usr/local/lib/python3.9/http/client.py", line 919, in connect
    self.sock = self._create_connection(
  File "/usr/local/lib/python3.9/socket.py", line 822, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/usr/local/lib/python3.9/socket.py", line 953, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -3] Temporary failure in name resolution
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/tmp/submission/20230103/11/53/hackerrank-725270a2c246ce29a6de7a3dd77fab59/code/Solution.py", line 10, in <module>
    df = pd.read_csv(url)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 610, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 462, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 819, in __init__
    self._engine = self._make_engine(self.engine)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 1050, in _make_engine
    return mapping[engine](self.f, **self.options)  # type: ignore[call-arg]
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 1867, in __init__
    self._open_handles(src, kwds)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/parsers.py", line 1362, in _open_handles
    self.handles = get_handle(
  File "/usr/local/lib/python3.9/site-packages/pandas/io/common.py", line 558, in get_handle
    ioargs = _get_filepath_or_buffer(
  File "/usr/local/lib/python3.9/site-packages/pandas/io/common.py", line 289, in _get_filepath_or_buffer
    req = urlopen(filepath_or_buffer)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/common.py", line 195, in urlopen
    return urllib.request.urlopen(*args, **kwargs)
  File "/usr/local/lib/python3.9/urllib/request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/lib/python3.9/urllib/request.py", line 517, in open
    response = self._open(req, data)
  File "/usr/local/lib/python3.9/urllib/request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "/usr/local/lib/python3.9/urllib/request.py", line 494, in _call_chain
    result = func(*args)
  File "/usr/local/lib/python3.9/urllib/request.py", line 1389, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
  File "/usr/local/lib/python3.9/urllib/request.py", line 1349, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -3] Temporary failure in name resolution>

Any help would be greatly appreciated

I have tried using the requests module to load the csv then using pd.read_csv() but I got another error then


问:
I cannot load my ".fxml" file into my method of java class
I'm trying to load my "RecuperoPassw.fxml" file into the method of the class formLogin.java.
I've tried several methods and I understood that all the java files have to be in the same folder of the Main class. But there is any solution to avoid that, in order to have a subfolder like this?

```<code>com.agmg.carsparadise -> GestioneAccount -> Interface -> formLogin
</code>```

Structure of Project

My method to load "RecuperoPassw.fxml" is this:

public void goTo_RecuperoPassw(ActionEvent event) throws IOException { //mi porta alla pagina di recupero password
   // !! brutto da vedere e non generale !!
   String path = "/Users/gabriel/Desktop/CarsParadise/src/main/resources/com/agmg/carsparadise/GestioneAccount/RecuperoPassw.fxml";
   Parent root = FXMLLoader.load(new File(path).toURI().toURL());
   Stage stage = (Stage)((Node)event.getSource()).getScene().getWindow();
   Scene scene = new Scene(root);
   stage.setScene(scene);
   stage.show();
}
```

this method is inside "formLogin.java". I don't want to use the absolute path, I want to use a more general solution. What can I do?
p.s: I've tried also to use
"../../GestioneAccount/RecuperoPassw.fxml" and it doesn't work.

Body:
I'm trying to load my "RecuperoPassw.fxml" file into the method of the class formLogin.java.
I've tried several methods and I understood that all the java files have to be in the same folder of the Main class. But there is any solution to avoid that, in order to have a subfolder like this?

com.agmg.carsparadise -> GestioneAccount -> Interface -> formLogin

Structure of Project

My method to load "RecuperoPassw.fxml" is this:

public void goTo_RecuperoPassw(ActionEvent event) throws IOException { //mi porta alla pagina di recupero password
   // !! brutto da vedere e non generale !!
   String path = "/Users/gabriel/Desktop/CarsParadise/src/main/resources/com/agmg/carsparadise/GestioneAccount/RecuperoPassw.fxml";
   Parent root = FXMLLoader.load(new File(path).toURI().toURL());
   Stage stage = (Stage)((Node)event.getSource()).getScene().getWindow();
   Scene scene = new Scene(root);
   stage.setScene(scene);
   stage.show();
}

this method is inside "formLogin.java". I don't want to use the absolute path, I want to use a more general solution. What can I do?
p.s: I've tried also to use
"../../GestioneAccount/RecuperoPassw.fxml" and it doesn't work.


问:
How to compress a image size to 2Mb in Xamarin forms
I have a Xamarin application which support iOS and UWP.I need to Capture an image and upload that in to server and the image size should be less than or equal to 2MB. But in iOS the captured images are always more than that. How to compress the image. I am using Xamarin.essential.Mediapicker for capture the image. Please help me

in iOS I tried the below using dependency service, but it won't work for bigger size like 10 Mb or more than that

```<code>public async Task<byte[]> CompressImage(ImageSource imagesource)
    {
        UIImage image;
        nfloat compressVal = 0.3F;
        var handler = GetHandler(imagesource);
        image = await handler.LoadImageAsync(imagesource);
        var compressedImage = image.AsJPEG(compressVal);
        byte[] dataBytes = compressedImage.ToArray();

        return dataBytes;
    }

    public IImageSourceHandler GetHandler(ImageSource source)
    {
        IImageSourceHandler returnValue = null;

        if (source is FileImageSource)
        {
            returnValue = new FileImageSourceHandler();
        }
        return returnValue;
    }
</code>```

Body:
I have a Xamarin application which support iOS and UWP.I need to Capture an image and upload that in to server and the image size should be less than or equal to 2MB. But in iOS the captured images are always more than that. How to compress the image. I am using Xamarin.essential.Mediapicker for capture the image. Please help me

in iOS I tried the below using dependency service, but it won't work for bigger size like 10 Mb or more than that

public async Task<byte[]> CompressImage(ImageSource imagesource)
    {
        UIImage image;
        nfloat compressVal = 0.3F;
        var handler = GetHandler(imagesource);
        image = await handler.LoadImageAsync(imagesource);
        var compressedImage = image.AsJPEG(compressVal);
        byte[] dataBytes = compressedImage.ToArray();

        return dataBytes;
    }

    public IImageSourceHandler GetHandler(ImageSource source)
    {
        IImageSourceHandler returnValue = null;

        if (source is FileImageSource)
        {
            returnValue = new FileImageSourceHandler();
        }
        return returnValue;
    }


问:
Resource handler returned message: "No integration defined for method (Service: ApiGateway, Status Code: 400
I want to import a YAML file into API GateWay.
Whenever I do so I get the following error

Resource handler returned message: "No integration defined for method (Service: ApiGateway, Status Code: 400

I use the following code to import the YAML file

const integration = new LambdaIntegration(hello)

const api = new SpecRestApi(this, 'books-api', {
  apiDefinition: ApiDefinition.fromAsset('apiTrial.yaml')
});

const booksResource = api.root.addResource('books')
booksResource.addMethod('GET', integration);

});
```
<p>and my current yaml file is:</p>
<pre class="lang-yaml prettyprint-override"><code>openapi: 3.0.0
info:
  title: "MyFirstAPI"
  version: "1.0.0"
  contact:
    name: Karim Fayed
    email: contact@example.com
    url: https://example.com/
tags:
  - name: Metadata
    description: Metadata related requests
servers:
- url: "https://api.openweathermap.org/data/2.5"
paths:
  /:
    get:
      operationId: getMetadata
      summary: Get metadata from the root of the API
      tags: [ 'Metadata for root' ]
      responses:
        '200':
          description: OK
  /weather:
    get:
      operationId: "getMetadata"
      summary: "Get metadata from weather API"
      tags: ["metadata data for wather"]
      responses:
       200:
        description: successful operation
       400:
        description: Invalid id supplied
       404:
        description: Contact not found
       500:
        description: Server error
</code>```

As you can see I already have a response for code 400 so why would the error keep showing up?

Body:
I want to import a YAML file into API GateWay.
Whenever I do so I get the following error

Resource handler returned message: "No integration defined for method (Service: ApiGateway, Status Code: 400

I use the following code to import the YAML file

const integration = new LambdaIntegration(hello)

const api = new SpecRestApi(this, 'books-api', {
  apiDefinition: ApiDefinition.fromAsset('apiTrial.yaml')
});

const booksResource = api.root.addResource('books')
booksResource.addMethod('GET', integration);

});

and my current yaml file is:

openapi: 3.0.0
info:
  title: "MyFirstAPI"
  version: "1.0.0"
  contact:
    name: Karim Fayed
    email: contact@example.com
    url: https://example.com/
tags:
  - name: Metadata
    description: Metadata related requests
servers:
- url: "https://api.openweathermap.org/data/2.5"
paths:
  /:
    get:
      operationId: getMetadata
      summary: Get metadata from the root of the API
      tags: [ 'Metadata for root' ]
      responses:
        '200':
          description: OK
  /weather:
    get:
      operationId: "getMetadata"
      summary: "Get metadata from weather API"
      tags: ["metadata data for wather"]
      responses:
       200:
        description: successful operation
       400:
        description: Invalid id supplied
       404:
        description: Contact not found
       500:
        description: Server error

As you can see I already have a response for code 400 so why would the error keep showing up?


问:
Make big groups from a lot of small groups (probably some graph problem)
I have a lot of files with groupped IDs.

File-1

id
group_id
unique_id

1
100
200

2
100
201

3
200
210

4
200
211

5
300
200

6
300
221

File-2

id
group_id
unique_id

1
100
221

2
100
231

4
200
240

5
200
241

Rules:

Unique_id means the same across different files (so file-1.unique_id 221 is the same file-2.unique_id).

I also treat unique_id in one group_id as "one" (so at file-1.unique_id 201 means the same as file-1 unique id 200, because they have the same group_id; but file-2.group_id 200 is not the same as file-1.group_id 200).

What I would like to do is to create big groups, across all files.

What I do now:

I make graph:

File-1 semiresult

```<code>201->200
211->210
221->200
</code>```

File-2 semiresult

```<code>231->221
241->240
</code>```

And then find each record in each file to connect files groups, and end up with:

Result

file_id
group_id
big_group

1
100
1

1
200
2

1
300
1

2
100
1

2
200
3

My problem is - the memory. So it's easy to perform this task on two small files, but I do not know what structure/solution should I use to maybe perform it files that contains 100 000 000 records, also I want to make big_group for even 200 files.

I perform on 10/20 RPi's and I have network drive available, but I do not know how to synchronize the process.

I think that it might be some problem that has official name and maybe some implementations.

Body:
I have a lot of files with groupped IDs.

File-1

id
group_id
unique_id

1
100
200

2
100
201

3
200
210

4
200
211

5
300
200

6
300
221

File-2

id
group_id
unique_id

1
100
221

2
100
231

4
200
240

5
200
241

Rules:

Unique_id means the same across different files (so file-1.unique_id 221 is the same file-2.unique_id).

I also treat unique_id in one group_id as "one" (so at file-1.unique_id 201 means the same as file-1 unique id 200, because they have the same group_id; but file-2.group_id 200 is not the same as file-1.group_id 200).

What I would like to do is to create big groups, across all files.

What I do now:

I make graph:

File-1 semiresult

201->200
211->210
221->200

File-2 semiresult

231->221
241->240

And then find each record in each file to connect files groups, and end up with:

Result

file_id
group_id
big_group

1
100
1

1
200
2

1
300
1

2
100
1

2
200
3

My problem is - the memory. So it's easy to perform this task on two small files, but I do not know what structure/solution should I use to maybe perform it files that contains 100 000 000 records, also I want to make big_group for even 200 files.

I perform on 10/20 RPi's and I have network drive available, but I do not know how to synchronize the process.

I think that it might be some problem that has official name and maybe some implementations.


问:
HDMI CEC not working when switching to TV 0.0.0.0 using iobroker docker, node red, and pulse eight adapter
I am attempting to control my HDMI CEC-enabled devices using iobroker running in a docker container on my pc, along with node red and the node red cec plugin. I am using a pulse eight adapter to facilitate communication between the devices.

I have two function nodes in my node red flow, one for switching to HDMI 1 and one for switching to the digital cable source (TV 0.0.0.0). The function node for switching to HDMI 1 is as follows:

```<code>msg.payload = {
    "source": "0x4",
    "target": "0x15",
    "opcode": "0x82",
    "args": "1.0.0.0"
}
return msg;
</code>```

The function node for switching to (TV 0.0.0.0) is as follows:

```<code>msg.payload = {
    "source": "0x0",
    "target": "0x15",
    "opcode": "0x82",
    "args": "0.0.0.0"
};
return msg;
</code>```

Switching to HDMI 1 works fine, but I am having trouble switching back to the old source or to (TV 0.0.0.0). The switch simply does not work in these cases.

I have verified that the adapter and my devices are functioning properly, as switching to HDMI 1 and changing the input work correctly. I have also ensured that the iobroker container has the necessary privileges (--privileged and --cap-add=ALL) and that it is restarting automatically (--restart always).

Here is the command I am using to run the iobroker container:

```<code>docker run -p 8091:8081 -p 1880:1880 --privileged --cap-add=ALL --name iobroker -h iobroker --restart always buanet/iobroker
</code>```

I am not sure what else to try in order to fix this issue. Any help would be greatly appreciated.

I also have a get active source node in my flow:

```<code>msg = {
  "command": "getactivesource"
}
return msg;
</code>```

When I run this node after switching to TV 0.0.0.0, it shows that the active source has indeed switched from 1.0.0.0 to 0.0.0.0, but the TV still displays HDMI 1.

I have dummy tested several sources from 0x0 to 0x5 and have found that I am unable to switch to any of them using the function node for switching to TV 0.0.0.0.

I also have a function node that changes the input on the TV:

```<code>msg.payload = {
    "source": "0x1",
    "target": "0x0",
    "opcode": "0x44",
    "args": "0x34"
}
return msg;
</code>```

This function node works fine for switching inputs, but I do not want to toggle through the inputs. I want to be able to switch directly to a specific input.

I am using docker to run iobroker on multiple devices, and I have followed the instructions in the following readme:

https://github.com/iobroker-community-adapters/ioBroker.cec2

However, I am not using the plugin mentioned in that readme. Instead, I am using the following node red cec plugin:

https://flows.nodered.org/node/node-red-contrib-cec

https://github.com/damoclark/node-red-contrib-cec

https://github.com/senzil/cec-monitor/blob/master/src/HDMI-CEC.1.4.js

I am also using the following docker image for iobroker:

https://hub.docker.com/r/buanet/iobroker

Body:
I am attempting to control my HDMI CEC-enabled devices using iobroker running in a docker container on my pc, along with node red and the node red cec plugin. I am using a pulse eight adapter to facilitate communication between the devices.

I have two function nodes in my node red flow, one for switching to HDMI 1 and one for switching to the digital cable source (TV 0.0.0.0). The function node for switching to HDMI 1 is as follows:

msg.payload = {
    "source": "0x4",
    "target": "0x15",
    "opcode": "0x82",
    "args": "1.0.0.0"
}
return msg;

The function node for switching to (TV 0.0.0.0) is as follows:

msg.payload = {
    "source": "0x0",
    "target": "0x15",
    "opcode": "0x82",
    "args": "0.0.0.0"
};
return msg;

Switching to HDMI 1 works fine, but I am having trouble switching back to the old source or to (TV 0.0.0.0). The switch simply does not work in these cases.

I have verified that the adapter and my devices are functioning properly, as switching to HDMI 1 and changing the input work correctly. I have also ensured that the iobroker container has the necessary privileges (--privileged and --cap-add=ALL) and that it is restarting automatically (--restart always).

Here is the command I am using to run the iobroker container:

docker run -p 8091:8081 -p 1880:1880 --privileged --cap-add=ALL --name iobroker -h iobroker --restart always buanet/iobroker

I am not sure what else to try in order to fix this issue. Any help would be greatly appreciated.

I also have a get active source node in my flow:

msg = {
  "command": "getactivesource"
}
return msg;

When I run this node after switching to TV 0.0.0.0, it shows that the active source has indeed switched from 1.0.0.0 to 0.0.0.0, but the TV still displays HDMI 1.

I have dummy tested several sources from 0x0 to 0x5 and have found that I am unable to switch to any of them using the function node for switching to TV 0.0.0.0.

I also have a function node that changes the input on the TV:

msg.payload = {
    "source": "0x1",
    "target": "0x0",
    "opcode": "0x44",
    "args": "0x34"
}
return msg;

This function node works fine for switching inputs, but I do not want to toggle through the inputs. I want to be able to switch directly to a specific input.

I am using docker to run iobroker on multiple devices, and I have followed the instructions in the following readme:

https://github.com/iobroker-community-adapters/ioBroker.cec2

However, I am not using the plugin mentioned in that readme. Instead, I am using the following node red cec plugin:

https://flows.nodered.org/node/node-red-contrib-cec

https://github.com/damoclark/node-red-contrib-cec

https://github.com/senzil/cec-monitor/blob/master/src/HDMI-CEC.1.4.js

I am also using the following docker image for iobroker:

https://hub.docker.com/r/buanet/iobroker


问:
How to plan ahead sending an e-mail using VBA and Gmail, when PC is off?
I want to plan a sending in VBA for Gmail.

Manually I can achieve this by using the drop down next to send in Gmail.

Sub GMail_Versenden()

Dim Mail As New CDO.Message
Dim ConfigURL As String

ConfigURL = "http://schemas.microsoft.com/cdo/configuration/"

With Mail.Configuration.Fields
    .Item(ConfigURL & "smtpserver") = "smtp.gmail.com"
    .Item(ConfigURL & "smtpusessl") = True
    .Item(ConfigURL & "smtpauthenticate") = True
    .Item(ConfigURL & "smtserverport") = 465
    .Item(ConfigURL & "sendusing") = 2
    .Item(ConfigURL & "sendusername") = "Myemail@gmail.com"
    .Item(ConfigURL & "sendpassword") = "agoodpassword"
    .Update
End With

With Mail
    .From = "Myemail@gmail.com"
    .To = "RechieverEmail"
    .Subject = "Test"
    .HTMLBody = " This is a Test"
    .send
End With

Debug.Print "The Mail was delivered"

End Sub
```

I found some solutions for Outlook such as: DeferredDeliveryTime but Outlook only sends the mails when the program is open. Often times my PC is not turned on when the emails should be delivered.

I am using Outlook, but I want to change to Gmail since it works much smoother and more reliably.

How do I send emails with Gmail at a specific time?

I tried to find a way to send emails at a specific time using Excel VBA with Gmail. I did not find the right way to do so.

Body:
I want to plan a sending in VBA for Gmail.

Manually I can achieve this by using the drop down next to send in Gmail.

Sub GMail_Versenden()

Dim Mail As New CDO.Message
Dim ConfigURL As String

ConfigURL = "http://schemas.microsoft.com/cdo/configuration/"

With Mail.Configuration.Fields
    .Item(ConfigURL & "smtpserver") = "smtp.gmail.com"
    .Item(ConfigURL & "smtpusessl") = True
    .Item(ConfigURL & "smtpauthenticate") = True
    .Item(ConfigURL & "smtserverport") = 465
    .Item(ConfigURL & "sendusing") = 2
    .Item(ConfigURL & "sendusername") = "Myemail@gmail.com"
    .Item(ConfigURL & "sendpassword") = "agoodpassword"
    .Update
End With

With Mail
    .From = "Myemail@gmail.com"
    .To = "RechieverEmail"
    .Subject = "Test"
    .HTMLBody = " This is a Test"
    .send
End With

Debug.Print "The Mail was delivered"

End Sub

I found some solutions for Outlook such as: DeferredDeliveryTime but Outlook only sends the mails when the program is open. Often times my PC is not turned on when the emails should be delivered.

I am using Outlook, but I want to change to Gmail since it works much smoother and more reliably.

How do I send emails with Gmail at a specific time?

I tried to find a way to send emails at a specific time using Excel VBA with Gmail. I did not find the right way to do so.


问:
How to log uncaught errors that are visible in Nextjs console to the (winston) logger?
So I'm trying to log the errors that happen in my application using winston logger. Everything is working smoothly, when error happens on server side, or in client (I'm sending logs to the server to log them). But it's working in cases where I catch the error.

But there are cases where errors happens, because something is undefined somewhere, or I didn't catch the error somewhere. How I can catch this errors? Normally, in Nextjs console I have a whole error described, with error message and stack, but in Datadog it's logged as few lines of normal text (not even error).

The moment the error is happening and it's being shown in the console, I'd like to report it to my logger (winston) as and object. But I don't know how and where to intercept this error.

I have ErrorBoundry in app, but error is not as precise as error in Nextjs console. I do have _error file, but everything is 'undefined' (error and res). This is how my winston configuration looks like:

const logger = createLogger({
  level: "silly",
  format: format.json(),
  handleExceptions: true,
  transports: [new transports.Console({ handleExceptions: true, handleRejections: true })],
  exceptionHandlers: [new transports.Console()],
});```


问:
While building for tvOS, no library for this platform was found
I have integrated two third party libraries into the tvOS project.  I have no clue why I am getting this error.

My Xcode version is 14.0.1.


问:
Express js CORS Middleware not working in my server?
I'am using CORS middleware in express js.

```<code>const express = require ("express")
const cors = require("cors")
const PORT = process.env.PORT || 5000
const app = express()

// ***** 1st solution *****
// app.use((req,res,next)=>{
//     res.header("Access-Control-Allow-Origin","*")
// })

// ***** 2nd solution *****
// app.use(cors())

// ***** 3rd solution *****
// app.options("*",cors())

app.all("*",(req,res,next)=>{res.send("helloooo")})
app.listen(PORT,()=>{console.log(`Server is running on port ${PORT}`)})
</code>```

only first solution works fine but using CORS middleware has no effect

I tried also dynamic origins solution from docs and adding options to my cors with origin containg google url but have the same issues

I test it from google trying to fetch my server like that

```<code>fetch("http://localhost:5000").then((res)=>res.text()).then(console.log())
</code>```

then it gives error
Access to fetch at 'http://localhost:5000/' from origin 'https://www.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

however using thunder client to send request didn't gave me error but working fine

however using thunder client to send request didn't gave me error but working fine.
how can I solve this problem using CORS middleware,
instead of adding header directly to all my responses to all origins

Body:
I'am using CORS middleware in express js.

const express = require ("express")
const cors = require("cors")
const PORT = process.env.PORT || 5000
const app = express()

// ***** 1st solution *****
// app.use((req,res,next)=>{
//     res.header("Access-Control-Allow-Origin","*")
// })

// ***** 2nd solution *****
// app.use(cors())

// ***** 3rd solution *****
// app.options("*",cors())

app.all("*",(req,res,next)=>{res.send("helloooo")})
app.listen(PORT,()=>{console.log(`Server is running on port ${PORT}`)})

only first solution works fine but using CORS middleware has no effect

I tried also dynamic origins solution from docs and adding options to my cors with origin containg google url but have the same issues

I test it from google trying to fetch my server like that

fetch("http://localhost:5000").then((res)=>res.text()).then(console.log())

then it gives error
Access to fetch at 'http://localhost:5000/' from origin 'https://www.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

however using thunder client to send request didn't gave me error but working fine

however using thunder client to send request didn't gave me error but working fine.
how can I solve this problem using CORS middleware,
instead of adding header directly to all my responses to all origins


问:
How to fetch dynamic json with respond.json function using javascript
I want to populate these json file to html and i have tried no avail, i'm hoping someone could put me on the right track.

I tried to fetch this json using the code i tried
json link json File

Added: i have tried https://developer.mozilla.org/en-US/docs/Web/API/Response/json but didn't give result as my json array went up almost 4 level

Here is the code i tried

```<code>    fetch("./data.json")
  .then(function (result) {
    appendData(result);
  })
  .catch(error => console.log('error', error));

  function appendData(result) {
            var mainContainer = document.getElementById("myData");
            for (var i = 0; i < result.length; i++) {

                console.log(data.salaryPaymentDetails.result[i].amount)
            }
        }
</code>```

It give me undefine, don't know what am missing

Body:
I want to populate these json file to html and i have tried no avail, i'm hoping someone could put me on the right track.

I tried to fetch this json using the code i tried
json link json File

Added: i have tried https://developer.mozilla.org/en-US/docs/Web/API/Response/json but didn't give result as my json array went up almost 4 level

Here is the code i tried

    fetch("./data.json")
  .then(function (result) {
    appendData(result);
  })
  .catch(error => console.log('error', error));

  function appendData(result) {
            var mainContainer = document.getElementById("myData");
            for (var i = 0; i < result.length; i++) {

                console.log(data.salaryPaymentDetails.result[i].amount)
            }
        }

It give me undefine, don't know what am missing