问:
Python requests response - unable to write data to csv - "d" wrapped json response from asp.net
I'm trying to download Nifty 100 historical prices data from https://www.niftyindices.com/reports/historical-data

The data is fetched dynamically using javascript from the url: https://www.niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString

```<code>nifty_index_base_url = 'https://www.niftyindices.com'
nifty_index_url = 'https://www.niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString'

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
                         'like Gecko) '
                         'Chrome/80.0.3987.149 Safari/537.36',
           'accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'}

name="NIFTY 100"
data = {
    "name":"NIFTY 100",
    "startDate":"01-Dec-2021",
    "endDate":"05-Dec-2022"
}

session = requests.Session()
request = session.get(nifty_index_base_url, headers=headers, timeout=5)
cookies = dict(request.cookies)
response = session.post(nifty_index_url, headers=headers, json=data, timeout=10, cookies=cookies)
response.status_code
</code>```

response.text gives the following data:

```<code>{
    "d": "[{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"05 Dec 2022\",\"OPEN\":\"18898.00\",\"HIGH\":\"18905.60\",\"LOW\":\"18755.50\",\"CLOSE\":\"18867.65\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"02 Dec 2022\",\"OPEN\":\"18925.85\",\"HIGH\":\"18948.15\",\"LOW\":\"18812.60\",\"CLOSE\":\"18870.25\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"01 Dec 2022\",\"OPEN\":\"19034.20\",\"HIGH\":\"19039.40\",\"LOW\":\"18939.60\",\"CLOSE\":\"18973.05\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"30 Nov 2022\",\"OPEN\":\"18771.35\",\"HIGH\":\"18980.75\",\"LOW\":\"18762.60\",\"CLOSE\":\"18919.55\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"29 Nov 2022\",\"OPEN\":\"18691.55\",\"HIGH\":\"18815.90\",\"LOW\":\"18689.60\",\"CLOSE\":\"18758.35\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"28 Nov 2022\",\"OPEN\":\"18582.55\",\"HIGH\":\"18751.00\",\"LOW\":\"18521.60\",\"CLOSE\":\"18696.75\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"25 Nov 2022\",\"OPEN\":\"18673.80\",\"HIGH\":\"18677.10\",\"LOW\":\"18583.85\",\"CLOSE\":\"18652.05\"}]"
}
</code>```

When I try to write the data to csv using:

```<code>filename = f'nifty_index_{name}_{datetime.now().strftime("%d.%m.%Y")}.csv'
path_to_nifty_index_data = '/Users/ankurjhavery/Documents/Documents - IN-FVFH825RQ05N/PythonProjects/StockAnalysis/nifty_index_data'
open(f'{path_to_nifty_index_data}/{filename}', 'wb').write(response.content)
</code>```

I'm getting all data written in a single line only.

Body:
I'm trying to download Nifty 100 historical prices data from https://www.niftyindices.com/reports/historical-data

The data is fetched dynamically using javascript from the url: https://www.niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString

nifty_index_base_url = 'https://www.niftyindices.com'
nifty_index_url = 'https://www.niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString'

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
                         'like Gecko) '
                         'Chrome/80.0.3987.149 Safari/537.36',
           'accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'}

name="NIFTY 100"
data = {
    "name":"NIFTY 100",
    "startDate":"01-Dec-2021",
    "endDate":"05-Dec-2022"
}

session = requests.Session()
request = session.get(nifty_index_base_url, headers=headers, timeout=5)
cookies = dict(request.cookies)
response = session.post(nifty_index_url, headers=headers, json=data, timeout=10, cookies=cookies)
response.status_code

response.text gives the following data:

{
    "d": "[{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"05 Dec 2022\",\"OPEN\":\"18898.00\",\"HIGH\":\"18905.60\",\"LOW\":\"18755.50\",\"CLOSE\":\"18867.65\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"02 Dec 2022\",\"OPEN\":\"18925.85\",\"HIGH\":\"18948.15\",\"LOW\":\"18812.60\",\"CLOSE\":\"18870.25\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"01 Dec 2022\",\"OPEN\":\"19034.20\",\"HIGH\":\"19039.40\",\"LOW\":\"18939.60\",\"CLOSE\":\"18973.05\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"30 Nov 2022\",\"OPEN\":\"18771.35\",\"HIGH\":\"18980.75\",\"LOW\":\"18762.60\",\"CLOSE\":\"18919.55\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"29 Nov 2022\",\"OPEN\":\"18691.55\",\"HIGH\":\"18815.90\",\"LOW\":\"18689.60\",\"CLOSE\":\"18758.35\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"28 Nov 2022\",\"OPEN\":\"18582.55\",\"HIGH\":\"18751.00\",\"LOW\":\"18521.60\",\"CLOSE\":\"18696.75\"},{\"Index Name\":\"Nifty 100\",\"INDEX_NAME\":\"NIFTY 100\",\"HistoricalDate\":\"25 Nov 2022\",\"OPEN\":\"18673.80\",\"HIGH\":\"18677.10\",\"LOW\":\"18583.85\",\"CLOSE\":\"18652.05\"}]"
}

When I try to write the data to csv using:

filename = f'nifty_index_{name}_{datetime.now().strftime("%d.%m.%Y")}.csv'
path_to_nifty_index_data = '/Users/ankurjhavery/Documents/Documents - IN-FVFH825RQ05N/PythonProjects/StockAnalysis/nifty_index_data'
open(f'{path_to_nifty_index_data}/{filename}', 'wb').write(response.content)

I'm getting all data written in a single line only.


来源: stackexchange

问:
Get Child Site WooCommerce data in Parent MultiSite
I'm new to Multisite and having trouble finding any info on 2 things.

Our Multisite is set up with subdirectories.  Right now we have 1 parent and 1 child for testing. The parent site has WooCommerce installed but is not directly selling any products.  All sales will be done on child sites.  I've done a test sale on the child site.

I need to:

See orders/sales of all child sites on the parent site dashboard.

I'd like to show all child products, sorted in a single "stream" by name, on the parent site front end.  Each one would link to the appropriate child site.

Any code help or links to WPMS and WooCommerce data sharing would be appreciated!

ContentLicense: CC BY-SA 4.0


问:
Can I set a class or id for the Bearer token field in Swagger UI?
I was using the Swagger UI integrated with NestJS.I was wondering if there a way to add a class or id to the Bearer token field or to set the token programmatically?


问:
Is there a way to check the already checked Formik Checkbox on re-rendering?
So basically, I have two screens. One screen has a form which I am rendering through Formik and on the other page I am printing the response from my API based on the form values and a back button to go back to the previous screen (having the form).

My concern is when I enter the fields correctly including the checkbox and then submit the form then go onto second screen and then when I come back to the first screen(form screen), the fields which takes written input as their respective values show as filled but the checkboxes show as unchecked.

My code for useFormik is as following:

```<code>const metalsFormData = useFormik({
        initialValues: {
            metal: [],
            riskLevel: "Select Risk Type",
            age: "",
            retirement: "",
            retirementZipCode: "",
            retirementVehicle: "",
            dependantAge: ""
        },

        validationSchema: Yup.object({
            metal: Yup.array().min(1, 'Please select an option'),
            age: Yup.string().required('Please enter an age.'),
            retirement: Yup.array().min(1, 'Please select an option'),
            retirementZipCode: Yup.string().required('Please enter a zip code.'),
            retirementVehicle: Yup.array().min(1, 'Please select an option')
        }),

        onSubmit: (rawObject) => {
            props.portfolioData(rawObject);
            setStep2(true);
        }
    });
</code>```

My HTML for checkbox is as following:

```<code><div className='secure-checkboxes'>
  <div role="group" aria-labelledby="checkbox-group">
    <label>
      <input type="checkbox" name="retirement" value="Yes" onChange={metalsFormData.handleChange} onBlur={metalsFormData.handleBlur} />
      <span>Yes</span>
    </label>
    <label className='ml-4'>
      <input type="checkbox" name="retirement" value="No" onChange={metalsFormData.handleChange} onBlur={metalsFormData.handleBlur} />
      <span>No</span>
    </label>
  </div>
</div>

</code>```

I would like that when I come to the second screen after filling all the fields including checkboxes and then come back to the first screen having the form, all the fields should be prefilled with the values I had written and the checkboxes shall be shown as checked.

Body:
So basically, I have two screens. One screen has a form which I am rendering through Formik and on the other page I am printing the response from my API based on the form values and a back button to go back to the previous screen (having the form).

My concern is when I enter the fields correctly including the checkbox and then submit the form then go onto second screen and then when I come back to the first screen(form screen), the fields which takes written input as their respective values show as filled but the checkboxes show as unchecked.

My code for useFormik is as following:

const metalsFormData = useFormik({
        initialValues: {
            metal: [],
            riskLevel: "Select Risk Type",
            age: "",
            retirement: "",
            retirementZipCode: "",
            retirementVehicle: "",
            dependantAge: ""
        },

        validationSchema: Yup.object({
            metal: Yup.array().min(1, 'Please select an option'),
            age: Yup.string().required('Please enter an age.'),
            retirement: Yup.array().min(1, 'Please select an option'),
            retirementZipCode: Yup.string().required('Please enter a zip code.'),
            retirementVehicle: Yup.array().min(1, 'Please select an option')
        }),

        onSubmit: (rawObject) => {
            props.portfolioData(rawObject);
            setStep2(true);
        }
    });

My HTML for checkbox is as following:

      <input type="checkbox" name="retirement" value="Yes" onChange={metalsFormData.handleChange} onBlur={metalsFormData.handleBlur} />
      Yes

      <input type="checkbox" name="retirement" value="No" onChange={metalsFormData.handleChange} onBlur={metalsFormData.handleBlur} />
      No

I would like that when I come to the second screen after filling all the fields including checkboxes and then come back to the first screen having the form, all the fields should be prefilled with the values I had written and the checkboxes shall be shown as checked.


问:
Suggest a best order for the ciphers, Macs and Kexalgo in sshd config
I am aware that ciphers, Macs and kexalgortithm order in which we configure will be the order of preference in sshd_config. Excluding algorithms which use sha-1 and CBC ciphers, I would like to include all other algorithms which is recommended by system-wide crypto policies (comes along with openssh el8 version).

Is there any standard/suggested order of ciphers, Macs and kexalgorithm that we can configure in the aspect of security and best algorithm in a comparative manner? It would be really helpful if possibly provide references or link some documentation on your answer. Thanks in advance!!


问:
SPARQL recursive queries task
I found a SPARQL task that I can't finish. I am a beginner at SPARQL so I would be glad for some help. The endpoint is https://query.wikidata.org/.

Write a SELECT query:

Find all ingredients (parts, wdt:P527) of pad thai, recursively. So, also include parts of parts and parts of parts of parts, etc.

Find all things that have at least one ingredient in common with the pad thai. Here also make this recursive, so include parts of parts, etc.

Include only things that are a part of (wdt:P361) a European cuisine. There are many European cuisines – look recursively for subclasses (wdt:P279) of the “European cuisine” item.

In the results include:

The URI of the food.

The food’s English label with its description together in format like “label – description”. If there is no description for the food, output only the label.

English labels of all parts that this food has in common with pad thai, with “; “ as the separator between values.

English labels of all European cuisines that this food belongs to, with “; “ as the separator.

I found out that I can search title and combine it with description thanks to:

```<code>WHERE
{
  wd:Q730298 wdt:P527* ?ingredient .
  wd:Q579316 ^wdt:P279* ?europeanCuisines.
  ?food wdt:P527+ ?ingredient;
              wdt:P361 ?europeanCuisines.
</code>```

but it is black magic to me how to finish the rest.

Title: SPARQL recursive queries task

Body:
I found a SPARQL task that I can't finish. I am a beginner at SPARQL so I would be glad for some help. The endpoint is https://query.wikidata.org/.

Write a SELECT query:

Find all ingredients (parts, wdt:P527) of pad thai, recursively. So, also include parts of parts and parts of parts of parts, etc.

Find all things that have at least one ingredient in common with the pad thai. Here also make this recursive, so include parts of parts, etc.

Include only things that are a part of (wdt:P361) a European cuisine. There are many European cuisines – look recursively for subclasses (wdt:P279) of the “European cuisine” item.

In the results include:

The URI of the food.

The food’s English label with its description together in format like “label – description”. If there is no description for the food, output only the label.

English labels of all parts that this food has in common with pad thai, with “; “ as the separator between values.

English labels of all European cuisines that this food belongs to, with “; “ as the separator.

I found out that I can search title and combine it with description thanks to:

WHERE
{
  wd:Q730298 wdt:P527* ?ingredient .
  wd:Q579316 ^wdt:P279* ?europeanCuisines.
  ?food wdt:P527+ ?ingredient;
              wdt:P361 ?europeanCuisines.

but it is black magic to me how to finish the rest.


问:
Unable read file parameter when using Jenkins pipeline. Works well when it's a freestyle
I created 2 Jenkins jobs which fetch from git a py file:

```<code>import os
if __name__ == "__main__":

    # folder path
    dir_path = './'

    # list to store files
    res = []

    # Iterate directory
    for path in os.listdir(dir_path):
        # check if current path is a file
        if os.path.isfile(os.path.join(dir_path, path)):
            res.append(path)
    print(res)
</code>```

, which in his turn outputs content of workspace. No logic, just a test. The problem what I deal: when I create Freestyle job and try to run my python script it with added File parameter it works just fine and outputs : ['Test.xlsx', 'Jenkinsfile', 'main.py'], BUT when I run pipeline job with same repo, same File parameter it return's me ['Jenkinsfile', 'main.py'], basically file parameter couldn't be read. How to make it work in pipeline ?

Pipeline is straight and forward:

```<code>pipeline {
    agent {
        label 'Slave_Packager_Ubuntu'
    }

stages {

    stage("test") {
        steps {
            script {
                sh """
                    python3 main.py
                """
            }
        }
    }
}
</code>```

Body:
I created 2 Jenkins jobs which fetch from git a py file:

import os
if __name__ == "__main__":

    # folder path
    dir_path = './'

    # list to store files
    res = []

    # Iterate directory
    for path in os.listdir(dir_path):
        # check if current path is a file
        if os.path.isfile(os.path.join(dir_path, path)):
            res.append(path)
    print(res)

, which in his turn outputs content of workspace. No logic, just a test. The problem what I deal: when I create Freestyle job and try to run my python script it with added File parameter it works just fine and outputs : ['Test.xlsx', 'Jenkinsfile', 'main.py'], BUT when I run pipeline job with same repo, same File parameter it return's me ['Jenkinsfile', 'main.py'], basically file parameter couldn't be read. How to make it work in pipeline ?

Pipeline is straight and forward:

pipeline {
    agent {
        label 'Slave_Packager_Ubuntu'
    }

stages {

    stage("test") {
        steps {
            script {
                sh """
                    python3 main.py
                """
            }
        }
    }
}


问:
Shortest way to trigger an exception in Python
I would like to know the shortest possible way to throw an exception in Python that is not itself a SyntaxError.

For context, I use an IPython shell for development while editing the source in a different file and use live reload to bring in the changes. To set a break point in code, I usually insert import ipdb; ipdb.set_trace() to where I need the break point. A different way is triggering an arbitrary Exception, then use the %debug magic command on the interpreter to enter post-mortem debugging. I usually use 1/0 for this purpose, which raises a ZeroDivisionError. SyntaxError on the other hand is precluded, because then the program would not run at all.

The shortest one I can think of is using a non-existent variable, such as a, which results in a NameError: name 'a' is not defined. However this is not guaranteed to always work and requires me to be aware of the current scope. Is there a better way?


问:
Read Data from ADXL343 Accelerometer using C
I am trying to read x, y and z values from ADXL343 accelerometer. I am using PIC16 microcontroller. I also have an Arduino board and I can read values fine using Arduino board, but I can't seem to set-up a proper code in C to read the values. I am reading the values using i2c and I am using CCS C compiler. Here is my code:

adxl343.h

```<code>enum {
  adxl343_IIC_ADDR1 = 0x53 , /* Normal Address */
  adxl343_I2C_WRITE = 0xa6,
  adxl343_I2C_READ  = 0xa7,
};
</code>```

main.h

```<code>iic_power_enable();
delay_ms(1000);
adxl343_write_reg(adxl343_IIC_ADDR1,adxl343_REG_POWER_CTL,0x08);
delay_ms(2000);

errorReadData=0;
adxl343_t xyz;
int i = 0;
int8 lsb = 0;
int8 msb = 0;
int ack = 0;
i2c_custom_start();
ack = i2c_custom_write(iic_addr | adxl343_I2C_WRITE);
errorReadData+=i2c_ACK != ack;
assert(i2c_ACK == ack);
ack = i2c_custom_write(adxl343_OUT_X_MSB);
errorReadData+=i2c_ACK != ack;
assert(i2c_ACK == ack);
i2c_custom_start();
ack = i2c_custom_write(iic_addr | adxl343_I2C_READ);
errorReadData+=i2c_ACK != ack;
assert(i2c_ACK == ack);

msb = i2c_custom_read(TRUE);
lsb = i2c_custom_read(TRUE);
xyz.x = make16(lsb, msb);
msb = i2c_custom_read(TRUE);
lsb = i2c_custom_read(TRUE);
xyz.y = make16(lsb, msb);
msb = i2c_custom_read(TRUE);
lsb = i2c_custom_read(FALSE); /* End register reading. */
xyz.z = make16(lsb, msb);
i2c_custom_stop();

TRACE1("\r\nZ=%Lu", xyz.z);
TRACE1("\r\nX=%Lu", xyz.x);
TRACE1("\r\nY=%Lu", xyz.y);
</code>```

i2c_custom.h

```<code>int i2c_custom_read(int ack) {return i2c_read(ack);}
int i2c_custom_write(int8 data) {return i2c_write(data);}
void i2c_custom_stop() {i2c_stop();}
</code>```

Output is always:
X=65535
Y-65535
Z=65535

I am not sure what I am doing wrong here.

Body:
I am trying to read x, y and z values from ADXL343 accelerometer. I am using PIC16 microcontroller. I also have an Arduino board and I can read values fine using Arduino board, but I can't seem to set-up a proper code in C to read the values. I am reading the values using i2c and I am using CCS C compiler. Here is my code:

adxl343.h

enum {
  adxl343_IIC_ADDR1 = 0x53 , /* Normal Address */
  adxl343_I2C_WRITE = 0xa6,
  adxl343_I2C_READ  = 0xa7,
};

main.h

iic_power_enable();
delay_ms(1000);
adxl343_write_reg(adxl343_IIC_ADDR1,adxl343_REG_POWER_CTL,0x08);
delay_ms(2000);

errorReadData=0;
adxl343_t xyz;
int i = 0;
int8 lsb = 0;
int8 msb = 0;
int ack = 0;
i2c_custom_start();
ack = i2c_custom_write(iic_addr | adxl343_I2C_WRITE);
errorReadData+=i2c_ACK != ack;
assert(i2c_ACK == ack);
ack = i2c_custom_write(adxl343_OUT_X_MSB);
errorReadData+=i2c_ACK != ack;
assert(i2c_ACK == ack);
i2c_custom_start();
ack = i2c_custom_write(iic_addr | adxl343_I2C_READ);
errorReadData+=i2c_ACK != ack;
assert(i2c_ACK == ack);

msb = i2c_custom_read(TRUE);
lsb = i2c_custom_read(TRUE);
xyz.x = make16(lsb, msb);
msb = i2c_custom_read(TRUE);
lsb = i2c_custom_read(TRUE);
xyz.y = make16(lsb, msb);
msb = i2c_custom_read(TRUE);
lsb = i2c_custom_read(FALSE); /* End register reading. */
xyz.z = make16(lsb, msb);
i2c_custom_stop();

TRACE1("\r\nZ=%Lu", xyz.z);
TRACE1("\r\nX=%Lu", xyz.x);
TRACE1("\r\nY=%Lu", xyz.y);

i2c_custom.h

int i2c_custom_read(int ack) {return i2c_read(ack);}
int i2c_custom_write(int8 data) {return i2c_write(data);}
void i2c_custom_stop() {i2c_stop();}

Output is always:
X=65535
Y-65535
Z=65535

I am not sure what I am doing wrong here.


问:
in R How to compare NA and NA, and return TRUE or FALSE?
I would like to have a way to compare NA and NA and return TRUE or FALSE.

For example,

```<code>a = c(1,2,3,NA)
b = c(1,2,NA,NA)
</code>```

And suppose we would like to compare a and b. The R default output is

```<code>a>=b
# TRUE TRUE   NA   NA
a>b
# FALSE FALSE    NA    NA
a==b
# TRUE TRUE   NA   NA
</code>```

Is there a simple function or method to have a return like the following result?

```<code>a>=b
# TRUE TRUE   NA   TRUE
a>b
# FALSE FALSE    NA    FALSE
a==b
# TRUE TRUE   NA   TRUE
</code>```

This should be logical because NA (in a) is the same as NA (in b).

Body:
I would like to have a way to compare NA and NA and return TRUE or FALSE.

For example,

a = c(1,2,3,NA)
b = c(1,2,NA,NA)

And suppose we would like to compare a and b. The R default output is

a>=b
# TRUE TRUE   NA   NA
a>b
# FALSE FALSE    NA    NA
a==b
# TRUE TRUE   NA   NA

Is there a simple function or method to have a return like the following result?

a>=b
# TRUE TRUE   NA   TRUE
a>b
# FALSE FALSE    NA    FALSE
a==b
# TRUE TRUE   NA   TRUE

This should be logical because NA (in a) is the same as NA (in b).


问:
include png in xml file for xls sheet

Possible Duplicate:

  excel: including svg / png / vml image directly in xls sheet

can we include directly a png file into a xml structured xls file in base64?

my excel sheet looks like this:

```<code><Worksbook>
 <Worksheet>
  <Row>
   <Cell>
    <Data>
    </Data>
   </Cell>
  </Row>
 </Worksheet>
</Workbook>
</code>```

ContentLicense: CC BY-SA 3.0

Title: include png in xml file for xls sheet

Body:
Possible Duplicate:

  excel: including svg / png / vml image directly in xls sheet

can we include directly a png file into a xml structured xls file in base64?

my excel sheet looks like this:

<Worksbook>
 <Worksheet>
  <Row>
   <Cell>
    <Data>
    </Data>
   </Cell>
  </Row>
 </Worksheet>
</Workbook>


问:
How to use Selenium with IntelliJ IDE
I followed the very detailed How to use IntelliJ IDE & Selenium word for word, but in the end I'm still not be able to use Selenium, getting the errors of:

java: package org.openqa.selenium does not exist

I'm wondering what else I'm missing from such detailed how-to article (e.g., has the selenium java package been named differently since then?).

Title: How to use Selenium with IntelliJ IDE


问:
KivyMD: How to display widgets in rows and columns
I'm trying to display widgets in rows and columns in KivyMD. Currently, I have implemented a box layout which contains four other box layout corresponding to four rows. Each row include labels, buttons, checkbox and DropDownItems for a maximum of five columns.
However, the 4x5 matrix is not completely full: some possible missing widgets are present. The layout should organize and align the wigets according to a grid style leaving blank spaces where widgets are missing.
The project is organized into two files: .py and .kv.
File .py contains:

```<code>from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.app import MDApp
from kivy.lang import Builder

class InitializeComponent(MDBoxLayout):
    pass

class MainApp(MDApp):
    def build(self):
        Builder.load_file('Layout_Designer.kv')
        return InitializeComponent()

if __name__ == '__main__':
    MainApp().run()
</code>```

File .kv contains:

```<code><InitializeComponent>:
   orientation: 'vertical'
   padding: 20

   BoxLayout:
      MDLabel:
         text: 'ROW 1'
      MDRaisedButton:
         text: "Button 1"
      Widget:
      MDCheckbox:
      MDLabel:
         text: 'CHECKLABEL'

   BoxLayout:
      MDLabel:
         text: 'ROW 2__________________'
      MDRaisedButton:
         text: "Button 2"
      MDCheckbox:
      MDLabel:
         text: 'CHECKLABEL'
      MDDropDownItem:
         text: "Select"
         items: "A", "B"

   BoxLayout:
      MDLabel:
         text: 'ROW_____3'
      MDCheckbox:
      MDLabel:
         text: 'CHECKLABEL'
      MDRaisedButton:
         text: "Button 3"
      MDDropDownItem:
         text: "Select"
         items: "C", "D"

   BoxLayout:
      MDRaisedButton:
         text: 'SAVE'
</code>```

This code produces this layout:

Why buttons and drop down items behave differently from labels and checkbox? Why they are not displayed at the same height?
Widgets of the second column (Button1, button2, checkbox),  are not aligned together. How can I align widgets in rows and columns?
Moreover how can I reduce the space between the checkbox and the corresponding label?

Body:
I'm trying to display widgets in rows and columns in KivyMD. Currently, I have implemented a box layout which contains four other box layout corresponding to four rows. Each row include labels, buttons, checkbox and DropDownItems for a maximum of five columns.
However, the 4x5 matrix is not completely full: some possible missing widgets are present. The layout should organize and align the wigets according to a grid style leaving blank spaces where widgets are missing.
The project is organized into two files: .py and .kv.
File .py contains:

from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.app import MDApp
from kivy.lang import Builder

class InitializeComponent(MDBoxLayout):
    pass

class MainApp(MDApp):
    def build(self):
        Builder.load_file('Layout_Designer.kv')
        return InitializeComponent()

if __name__ == '__main__':
    MainApp().run()

File .kv contains:

<InitializeComponent>:
   orientation: 'vertical'
   padding: 20

   BoxLayout:
      MDLabel:
         text: 'ROW 1'
      MDRaisedButton:
         text: "Button 1"
      Widget:
      MDCheckbox:
      MDLabel:
         text: 'CHECKLABEL'

   BoxLayout:
      MDLabel:
         text: 'ROW 2__________________'
      MDRaisedButton:
         text: "Button 2"
      MDCheckbox:
      MDLabel:
         text: 'CHECKLABEL'
      MDDropDownItem:
         text: "Select"
         items: "A", "B"

   BoxLayout:
      MDLabel:
         text: 'ROW_____3'
      MDCheckbox:
      MDLabel:
         text: 'CHECKLABEL'
      MDRaisedButton:
         text: "Button 3"
      MDDropDownItem:
         text: "Select"
         items: "C", "D"

   BoxLayout:
      MDRaisedButton:
         text: 'SAVE'

This code produces this layout:

Why buttons and drop down items behave differently from labels and checkbox? Why they are not displayed at the same height?
Widgets of the second column (Button1, button2, checkbox),  are not aligned together. How can I align widgets in rows and columns?
Moreover how can I reduce the space between the checkbox and the corresponding label?


问:
Assigning an Excel Shape an RGB Color - Optimize my routine
I'm attempting to set a Shape Color to the color of an associated cell from a lookup in VBA.  i.e.:

```<code>CellColor = Worksheets("Config").Range("C5").DisplayFormat.Interior.Color
</code>```

Provides me with a color that I can use to assign to a shape:

```<code>With Selection.ShapeRange.Fill
            .Visible = msoTrue
            .ForeColor.rgb = CellColor
</code>```

What I can't get to work is looking up a respective cell and then assigning the associated color...  I have a Configuration Tab with 2 columns, Category and Color.  The Category column is a list of categories.  Next to that is a column of the colors that I want assigned to the Category, meaning that the color is physically visible to the user, not a name or numeric referencing the color.

I'd like to do something like the below where the txtImpactCategory is the field I need to drive the lookup of the Shape color:

```<code>CellColor = WorksheetFunction.Lookup(txtImpactCategory, Worksheets("Config").Range("B2:B12").Value, Worksheets("Config").Range("C2:C12").DisplayFormat.Interior.Color)
</code>```

When I do this, I get a Run-time error 1004: Unable to get the Lookup property of the WorksheetFunction class.

If I change the above lookup to return the Value of column C2:C12, i.e. Worksheets("Config").Range("C2:C12").Value it returns the text in that field so programmatically it's executing the lookup properly.  I just can't get the color to return.

Any help direction would be appreciated.

Thanks
Rob

Body:
I'm attempting to set a Shape Color to the color of an associated cell from a lookup in VBA.  i.e.:

CellColor = Worksheets("Config").Range("C5").DisplayFormat.Interior.Color

Provides me with a color that I can use to assign to a shape:

With Selection.ShapeRange.Fill
            .Visible = msoTrue
            .ForeColor.rgb = CellColor

What I can't get to work is looking up a respective cell and then assigning the associated color...  I have a Configuration Tab with 2 columns, Category and Color.  The Category column is a list of categories.  Next to that is a column of the colors that I want assigned to the Category, meaning that the color is physically visible to the user, not a name or numeric referencing the color.

I'd like to do something like the below where the txtImpactCategory is the field I need to drive the lookup of the Shape color:

CellColor = WorksheetFunction.Lookup(txtImpactCategory, Worksheets("Config").Range("B2:B12").Value, Worksheets("Config").Range("C2:C12").DisplayFormat.Interior.Color)

When I do this, I get a Run-time error 1004: Unable to get the Lookup property of the WorksheetFunction class.

If I change the above lookup to return the Value of column C2:C12, i.e. Worksheets("Config").Range("C2:C12").Value it returns the text in that field so programmatically it's executing the lookup properly.  I just can't get the color to return.

Any help direction would be appreciated.

Thanks
Rob


问:
Adapting old iomemory-vsl driver to a new Linux kernel
These are old fusion-io PCIe drives which otherwise are long lasting SLC/MLC available in great quantities for cheap but of course being old lack support. I was using few with older Linux kernel v5.10 but was forced to upgrade to v5.19 due WiFi module support and performance fixes.

Apparently I discovered some changes were made to kernel v5.19 making compilation impossible without changes. I don't have large experience with coding beyond embedded system but definitely I am not Linux kernel/driver developer.

Long story short, I made the driver work, it is compiling, loading and in general working but I have concerns as to some guessing and figuring it out and how "unsafe" it became.

Specifically this may affect data in transit on device detach, does not happen every day but data is data.

What I discovered: pci_*() got replaced with dma_*(), PDE_DATA with pde_data (key change!), PCI_DMA_* with DMA_* and considerable changes to block device queue flags and functions to operate them where some were removed.

-    blk_queue_flag_set(QUEUE_FLAG_DISCARD, rq);
+    blk_queue_max_discard_sectors(rq, 0);

-    pci_unmap_sg(lsg->pci_dev, lsg->sl, lsg->num_entries,
-                 lsg->pci_dir == IODRIVE_DMA_DIR_READ ? PCI_DMA_FROMDEVICE : PCI_DMA_TODEVICE);
+    dma_unmap_sg(&lsg->pci_dev->dev, lsg->sl, lsg->num_entries,
+                 lsg->pci_dir == IODRIVE_DMA_DIR_READ ? DMA_FROM_DEVICE : DMA_TO_DEVICE);

-    return PDE_DATA(ip);
+    return pde_data(ip);

-    return pci_set_dma_mask((struct pci_dev *)pdev, mask);
+    return dma_set_mask(&((struct pci_dev *)pdev)->dev, mask);

```
<p>These were the easier changes, but there are also changes to allocation of queues. And here I have some questions.</p>
<p><code>QUEUE_FLAG_DISCARD</code> is no longer available, do I get similar result with <code>blk_queue_max_discard_sectors(rq, 0);</code>?</p>
<p><code>QUEUE_FLAG_DEAD</code> is no longer available, do I get similar result with <code>blk_queue_flag_set(QUEUE_FLAG_DYING, disk->rq);</code>? Assume should stop accepting new IO as it is DYING and prevent data loss?</p>
<p>And here is the main culprit, <code>blk_cleanup_queue()</code> is also not directly available anymore in v5.19. For now I have removed this completely and wondering how bad it is. I tried with <code>blk_mq_destroy_queue()</code> but since entire driver is built around <code>blk_queue_make_request()</code> when I trigger <code>blk_mq_destroy_queue(disk->rq);</code> I get exception and stack trace points to blk_mq_destroy, quite sure because driver is not using <code>blk_mq_init_queue()</code>?</p>
<p>How bad is to leave it like this? Drive gets detached without exceptions but <code>disk->rq = NULL;</code> clears only rq, not queues. But is <code>del_gendisk(disk->gd);</code> not clearing all disk related data/structures?</p>
<pre class="lang-c prettyprint-override"><code>void kfio_destroy_disk(kfio_disk_t *disk, destroy_type_t dt)
{
    if (disk->gd != NULL) {
        set_capacity(disk->gd, 0);

        if (disk->queue_lock != NULL)
            fusion_spin_lock_irqsave(disk->queue_lock);

        /* Stop delivery of new io from user. */
//      set_bit(QUEUE_FLAG_DEAD, &disk->rq->queue_flags);
        blk_queue_flag_set(QUEUE_FLAG_DYING, disk->rq);
        /*
         * Prevent request_fn callback from interfering with
         * the queue shutdown.
         */
        blk_mq_stop_hw_queues(disk->rq);
        /*
         * The queue is stopped and dead and no new user requests will be
         * coming to it anymore. Fetch remaining already queued requests
         * and fail them,
         */
        if (use_workqueue == USE_QUEUE_RQ)
            kfio_kill_requests(disk->rq);
        if (use_workqueue != USE_QUEUE_RQ) {
            /* Fail all bio's already on internal bio queue. */
            struct bio *bio;

            while ((bio = disk->bio_head) != NULL) {
                disk->bio_head = bio->bi_next;
                __kfio_bio_complete(bio,  0, -EIO);
            }
            disk->bio_tail = NULL;
        }

        if (disk->queue_lock != NULL)
            fusion_spin_unlock_irqrestore(disk->queue_lock);

        del_gendisk(disk->gd);

        put_disk(disk->gd);
        disk->gd = NULL;
    }

    if (disk->rq != NULL) {
//      blk_mq_destroy_queue(disk->rq);
//      blk_cleanup_queue(disk->rq);
        disk->rq = NULL;
    }

    fusion_condvar_destroy(&disk->state_cv);
    fusion_cv_lock_destroy(&disk->state_lk);
}
</code>```

Body:
These are old fusion-io PCIe drives which otherwise are long lasting SLC/MLC available in great quantities for cheap but of course being old lack support. I was using few with older Linux kernel v5.10 but was forced to upgrade to v5.19 due WiFi module support and performance fixes.

Apparently I discovered some changes were made to kernel v5.19 making compilation impossible without changes. I don't have large experience with coding beyond embedded system but definitely I am not Linux kernel/driver developer.

Long story short, I made the driver work, it is compiling, loading and in general working but I have concerns as to some guessing and figuring it out and how "unsafe" it became.

Specifically this may affect data in transit on device detach, does not happen every day but data is data.

What I discovered: pci_*() got replaced with dma_*(), PDE_DATA with pde_data (key change!), PCI_DMA_* with DMA_* and considerable changes to block device queue flags and functions to operate them where some were removed.

-    blk_queue_flag_set(QUEUE_FLAG_DISCARD, rq);
+    blk_queue_max_discard_sectors(rq, 0);

-    pci_unmap_sg(lsg->pci_dev, lsg->sl, lsg->num_entries,
-                 lsg->pci_dir == IODRIVE_DMA_DIR_READ ? PCI_DMA_FROMDEVICE : PCI_DMA_TODEVICE);
+    dma_unmap_sg(&lsg->pci_dev->dev, lsg->sl, lsg->num_entries,
+                 lsg->pci_dir == IODRIVE_DMA_DIR_READ ? DMA_FROM_DEVICE : DMA_TO_DEVICE);

-    return PDE_DATA(ip);
+    return pde_data(ip);

-    return pci_set_dma_mask((struct pci_dev *)pdev, mask);
+    return dma_set_mask(&((struct pci_dev *)pdev)->dev, mask);

These were the easier changes, but there are also changes to allocation of queues. And here I have some questions.

QUEUE_FLAG_DISCARD is no longer available, do I get similar result with blk_queue_max_discard_sectors(rq, 0);?

QUEUE_FLAG_DEAD is no longer available, do I get similar result with blk_queue_flag_set(QUEUE_FLAG_DYING, disk->rq);? Assume should stop accepting new IO as it is DYING and prevent data loss?

And here is the main culprit, blk_cleanup_queue() is also not directly available anymore in v5.19. For now I have removed this completely and wondering how bad it is. I tried with blk_mq_destroy_queue() but since entire driver is built around blk_queue_make_request() when I trigger blk_mq_destroy_queue(disk->rq); I get exception and stack trace points to blk_mq_destroy, quite sure because driver is not using blk_mq_init_queue()?

How bad is to leave it like this? Drive gets detached without exceptions but disk->rq = NULL; clears only rq, not queues. But is del_gendisk(disk->gd); not clearing all disk related data/structures?

void kfio_destroy_disk(kfio_disk_t *disk, destroy_type_t dt)
{
    if (disk->gd != NULL) {
        set_capacity(disk->gd, 0);

        if (disk->queue_lock != NULL)
            fusion_spin_lock_irqsave(disk->queue_lock);

        /* Stop delivery of new io from user. */
//      set_bit(QUEUE_FLAG_DEAD, &disk->rq->queue_flags);
        blk_queue_flag_set(QUEUE_FLAG_DYING, disk->rq);
        /*
         * Prevent request_fn callback from interfering with
         * the queue shutdown.
         */
        blk_mq_stop_hw_queues(disk->rq);
        /*
         * The queue is stopped and dead and no new user requests will be
         * coming to it anymore. Fetch remaining already queued requests
         * and fail them,
         */
        if (use_workqueue == USE_QUEUE_RQ)
            kfio_kill_requests(disk->rq);
        if (use_workqueue != USE_QUEUE_RQ) {
            /* Fail all bio's already on internal bio queue. */
            struct bio *bio;

            while ((bio = disk->bio_head) != NULL) {
                disk->bio_head = bio->bi_next;
                __kfio_bio_complete(bio,  0, -EIO);
            }
            disk->bio_tail = NULL;
        }

        if (disk->queue_lock != NULL)
            fusion_spin_unlock_irqrestore(disk->queue_lock);

        del_gendisk(disk->gd);

        put_disk(disk->gd);
        disk->gd = NULL;
    }

    if (disk->rq != NULL) {
//      blk_mq_destroy_queue(disk->rq);
//      blk_cleanup_queue(disk->rq);
        disk->rq = NULL;
    }

    fusion_condvar_destroy(&disk->state_cv);
    fusion_cv_lock_destroy(&disk->state_lk);
}


问:
how to remove hash values using regex in Splunk queries
How to remove hash value(separated and non separated with comma) from the subject field, subject field being the user, using regex in a Splunk query?
I tried the following but it is not working:</p>
```<code>|rex field=subject "(?i)^(?<subject>.+?)([^a-fA-F\d]{32})"
</code>```

Body:
How to remove hash value(separated and non separated with comma) from the subject field, subject field being the user, using regex in a Splunk query?
I tried the following but it is not working:

|rex field=subject "(?i)^(?<subject>.+?)([^a-fA-F\d]{32})"


问:
How to get user input to export to environment variables with makefile
I want to create a makefile which will ask users to input info and then export them as environment variables example of region, access key, access id for AWS account.

I have tried below but no luck. where am i doing wrong?

```<code>build:
    read -p "Enter a Region:" region;
    echo export TF_VAR_region=$$region
    echo export PKR_VAR_region=$$TF_VAR_region
</code>```

Body:
I want to create a makefile which will ask users to input info and then export them as environment variables example of region, access key, access id for AWS account.

I have tried below but no luck. where am i doing wrong?

build:
    read -p "Enter a Region:" region;
    echo export TF_VAR_region=$$region
    echo export PKR_VAR_region=$$TF_VAR_region


问:
JRE is missing after installing jdk17
I just started my journey with Java, I installed openjdk17 and found that the jre is not present inside Library/***/Home dir.
For openjdk8 it present on the same location.

I just upgrade my software and to run my app i need jre inside /Library/***/Home dir for jdk17 so please can someone help me to fix it.

I am using MacBook Pro and i used the following cmd to install the jdk17

brew install openjdk@17

Title: JRE is missing after installing jdk17


问:
What is the best way to achieve a constant callback every X seconds to a script within Twilio?
I need to be able to alert a caller the moment an event (external database change) occurs.

This change can occur anytime from a few seconds into their call or after a few minutes, leaving them on hold until the script called returns a TRUE value, basically having it check the script every 5-10 seconds until it indicates what action to perform or the value the caller is waiting for.

I've looked into chron jobs but due to the projected volume of calls, starting then logging and managing each chron job with possible multiple calls every minute of every hour of the day isn't feasible. The problem with any PHP functionality to emulate "waiting" then calling itself again (sleep()) is since PHP is server-side along with the entire Twilio API it doesn't "load" then magically 10 seconds later the function is performed, the entire load simply does not complete until after the script and entire chain of events is "done" which can result in loading or timeout errors if used as a URL directly in any Twilio callback.

One option would be as Twilio evangelists have suggested setting up a "call bot" and having it enter the room from the beginning in silence, then </Hangup> after a 10 second <Pause /> setting it to Callback a script that does use "wait" methods (sleep()) since as a callback would no longer be "holding up" Twilio then performing the same call bot action after the 10 second sleep() having it re-enter the room for 10 seconds then leave as before, thus effectively creating a continuous 10 second "callback loop" that constantly checks the database until whatever we're waiting on is available which would then modify the call/conference and inform the user of the response all within 10 seconds of it becoming available.

I have a secondary Twilio phone number that does exactly this using this PHP and TwiML:

PHP (silently enter the Conference, leave after 10 seconds calling script that "re-enters" Conference after 10 more seconds with or without status update)

```<code>$client->conferences($sid)->participants->create( TWILIO_NUMBER, TWILIO_BOT_NUMBER, [ 'label' => '10SecondBot', 'statusCallback' => 'reEnterConferenceAfter10Seconds.php?conferenceId=' . $sid, 'statusCallbackEvent' => 'complete' ] );
</code>```

TwiML Bin (TWILIO_BOT_NUMBER)

```<code><Response>
<Pause length="10" />
<Hangup/>
</Response>
</code>```

reEnterConferenceAfter10Seconds.php

Step 1) Ensure call/conference is active then check database for update (if found simply modify call/conference resource then end script, no need for bot)

Step 2) If not found, wait 10 seconds (sleep(10);), then repeat Step 1 before continuing to Step 3

Step 3) Repeat original PHP adding silent bot that leaves after 10 seconds calling back this script

--

This basically creates a continuous 10 second "check" during the duration of the call/conference, updating the user if/when the value is available. However, much like the chron job option, the scenario of simultaneous ongoing calls every minute becomes burdensome.

A.)
Can a single Twilio number using a hosted TwiML Bin (not an exteral webhook) perform this function simultaneously across multiple ongoing calls/conferences?

B.)
Is there another, preferred way to achieve this effect?

C.)
Would setting the <Conference> <Dial> timeLimit to 10 seconds followed by a <Redirect> back to the original <Conference> after checking the database value be more efficient seeing as there would be no need for a bot and secondary Twilio number? Having a single and constant <Conference> someone can join in on/give announcements to regardless of call state would be nice, but not required.

Timing is a huge factor and may make all the difference in user engagement and overall success of many user-based services. This check may even wish to be performed every 5 seconds for sake of up-to-the-minute accuracy.

Body:
I need to be able to alert a caller the moment an event (external database change) occurs.

This change can occur anytime from a few seconds into their call or after a few minutes, leaving them on hold until the script called returns a TRUE value, basically having it check the script every 5-10 seconds until it indicates what action to perform or the value the caller is waiting for.

I've looked into chron jobs but due to the projected volume of calls, starting then logging and managing each chron job with possible multiple calls every minute of every hour of the day isn't feasible. The problem with any PHP functionality to emulate "waiting" then calling itself again (sleep()) is since PHP is server-side along with the entire Twilio API it doesn't "load" then magically 10 seconds later the function is performed, the entire load simply does not complete until after the script and entire chain of events is "done" which can result in loading or timeout errors if used as a URL directly in any Twilio callback.

One option would be as Twilio evangelists have suggested setting up a "call bot" and having it enter the room from the beginning in silence, then </Hangup> after a 10 second <Pause /> setting it to Callback a script that does use "wait" methods (sleep()) since as a callback would no longer be "holding up" Twilio then performing the same call bot action after the 10 second sleep() having it re-enter the room for 10 seconds then leave as before, thus effectively creating a continuous 10 second "callback loop" that constantly checks the database until whatever we're waiting on is available which would then modify the call/conference and inform the user of the response all within 10 seconds of it becoming available.

I have a secondary Twilio phone number that does exactly this using this PHP and TwiML:

PHP (silently enter the Conference, leave after 10 seconds calling script that "re-enters" Conference after 10 more seconds with or without status update)

$client->conferences($sid)->participants->create( TWILIO_NUMBER, TWILIO_BOT_NUMBER, [ 'label' => '10SecondBot', 'statusCallback' => 'reEnterConferenceAfter10Seconds.php?conferenceId=' . $sid, 'statusCallbackEvent' => 'complete' ] );

TwiML Bin (TWILIO_BOT_NUMBER)

<Response>
<Pause length="10" />
<Hangup/>
</Response>

reEnterConferenceAfter10Seconds.php

Step 1) Ensure call/conference is active then check database for update (if found simply modify call/conference resource then end script, no need for bot)

Step 2) If not found, wait 10 seconds (sleep(10);), then repeat Step 1 before continuing to Step 3

Step 3) Repeat original PHP adding silent bot that leaves after 10 seconds calling back this script

--

This basically creates a continuous 10 second "check" during the duration of the call/conference, updating the user if/when the value is available. However, much like the chron job option, the scenario of simultaneous ongoing calls every minute becomes burdensome.

A.)
Can a single Twilio number using a hosted TwiML Bin (not an exteral webhook) perform this function simultaneously across multiple ongoing calls/conferences?

B.)
Is there another, preferred way to achieve this effect?

C.)
Would setting the <Conference> <Dial> timeLimit to 10 seconds followed by a <Redirect> back to the original <Conference> after checking the database value be more efficient seeing as there would be no need for a bot and secondary Twilio number? Having a single and constant <Conference> someone can join in on/give announcements to regardless of call state would be nice, but not required.

Timing is a huge factor and may make all the difference in user engagement and overall success of many user-based services. This check may even wish to be performed every 5 seconds for sake of up-to-the-minute accuracy.


问:
TypeLoadException: Could not load type 'System.Net.Http.SocketsHttpHandler
Is there any way that i can overcome this error:

System.TypeInitializationException: 'The type initializer for 'Azure.Core.Pipeline.HttpClientTransport' threw an exception.'

TypeLoadException: Could not load type 'System.Net.Http.SocketsHttpHandler' from assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

The Framework that i was using is 4.7 and i was getting this error, when i try to get this value. SmsClient smsClient = new SmsClient(connectionString);

Here i've tried Bind Redirect to the latest version & the particular Version mentioned in the error 4.0.0.0 .

But still i was getting the same. Any suggestions for this...


问:
How to get USD / USDZ model metersPerUnit value in iOS?
I've been trying for a few years to find out how to get the USD / USDZ metersPerUnit value in an iOS / macCatalyst app but so far have not discovered any solution. The issue has become more important as our users utilize more of their own USDZ models to create multi-model 3D and AR scenes in our app.

From Apple's SceneKit documentation I would expect that SCNSceneSource.getProperty(forKey: SCNSceneSourceAssetUnitKey) would provide the value, but I have not found the getProperty API to ever return any value other than nil for any type of model file including: .obj, .scn, .dae, .usdc, .usdz.

According to Pixar's USD spec, the default value for metersPerUnit if unspecified is 0.01 (i.e., centimeters) and some USDZ sources like Sketchfab seem to nearly always set it to 0.01. But Apple's apps like RealityConverter and usdconvert enable the user to set the value directly so we're seeing lots of models with other values.

I'd like to do something like the sample code below, but I cannot get it to work.Since SCNSource seems to use ModelIO I would have thought ModelIO would have an API for this, but I have not discovered it.  Is there some API anyone can suggest to get the metersPerUnit value?

```<code>            do {
            var options: [SCNSceneSource.LoadingOption : Any] = [
                .animationImportPolicy: SCNSceneSource.AnimationImportPolicy.doNotPlay
                                                            ]
            if let modelSource = SCNSceneSource(url: url)  {

                if let units = modelSource.property(forKey: SCNSceneSourceAssetUnitKey) as? [String : Any] {
                    if let metersPerUnit = units[SCNSceneSourceAssetUnitMeterKey] as? Float {
                        options[.convertUnitsToMeters] = NSNumber(value: metersPerUnit)
                    }
                }
                let scene = try modelSource.scene(options: options)

            }

        } catch {
            throw NSError(domain: "OurApp", code: 0, userInfo: [NSLocalizedDescriptionKey: "Model \(url.lastPathComponent) cannot be loaded"])
        }
</code>```

Body:
I've been trying for a few years to find out how to get the USD / USDZ metersPerUnit value in an iOS / macCatalyst app but so far have not discovered any solution. The issue has become more important as our users utilize more of their own USDZ models to create multi-model 3D and AR scenes in our app.

From Apple's SceneKit documentation I would expect that SCNSceneSource.getProperty(forKey: SCNSceneSourceAssetUnitKey) would provide the value, but I have not found the getProperty API to ever return any value other than nil for any type of model file including: .obj, .scn, .dae, .usdc, .usdz.

According to Pixar's USD spec, the default value for metersPerUnit if unspecified is 0.01 (i.e., centimeters) and some USDZ sources like Sketchfab seem to nearly always set it to 0.01. But Apple's apps like RealityConverter and usdconvert enable the user to set the value directly so we're seeing lots of models with other values.

I'd like to do something like the sample code below, but I cannot get it to work.Since SCNSource seems to use ModelIO I would have thought ModelIO would have an API for this, but I have not discovered it.  Is there some API anyone can suggest to get the metersPerUnit value?

            do {
            var options: [SCNSceneSource.LoadingOption : Any] = [
                .animationImportPolicy: SCNSceneSource.AnimationImportPolicy.doNotPlay
                                                            ]
            if let modelSource = SCNSceneSource(url: url)  {

                if let units = modelSource.property(forKey: SCNSceneSourceAssetUnitKey) as? [String : Any] {
                    if let metersPerUnit = units[SCNSceneSourceAssetUnitMeterKey] as? Float {
                        options[.convertUnitsToMeters] = NSNumber(value: metersPerUnit)
                    }
                }
                let scene = try modelSource.scene(options: options)

            }

        } catch {
            throw NSError(domain: "OurApp", code: 0, userInfo: [NSLocalizedDescriptionKey: "Model \(url.lastPathComponent) cannot be loaded"])
        }


问:
Nginx 10 minute timeout occurring
I have an AWS-hosted web application that initiates a long-running server process (more than 10 mintues). An Nginx reverse proxy server sits between the application load balancer (ALB) and the service. Both the Nginx server and the service reside within separate Kubernetes pods running on an EC2 instance.

I'm experiencing an issue with a connection being closed. The Nginx logs show a HTTP 499 error:

(][05/Dec/2022:12:02:27 +0000] "POST -------------- HTTP/1.1" 499 0
"https://------------.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0
Safari/537.36")

The issue is repeatable and occurs exactly 10 minutes after the request was initiated. Despite my having set the ALB, Nginx, and SQL Alchemy timeouts to be much longer than 10 minutes, I suspect a timeout is occurring with a default value of 10 minutes, but I can't figure out where.

Nginx is the product I'm least familiar with and so I suspect that I have failed to make the necessary timeout configs in its conf file. I have set this:

```<code>proxy_read_timeout          20m;
</code>```

Can anyone suggest where in the system the default timeout is occurring?

Title: Nginx 10 minute timeout occurring

Body:
I have an AWS-hosted web application that initiates a long-running server process (more than 10 mintues). An Nginx reverse proxy server sits between the application load balancer (ALB) and the service. Both the Nginx server and the service reside within separate Kubernetes pods running on an EC2 instance.

I'm experiencing an issue with a connection being closed. The Nginx logs show a HTTP 499 error:

(][05/Dec/2022:12:02:27 +0000] "POST -------------- HTTP/1.1" 499 0
"https://------------.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0
Safari/537.36")

The issue is repeatable and occurs exactly 10 minutes after the request was initiated. Despite my having set the ALB, Nginx, and SQL Alchemy timeouts to be much longer than 10 minutes, I suspect a timeout is occurring with a default value of 10 minutes, but I can't figure out where.

Nginx is the product I'm least familiar with and so I suspect that I have failed to make the necessary timeout configs in its conf file. I have set this:

proxy_read_timeout          20m;

Can anyone suggest where in the system the default timeout is occurring?


问:
Scala cats import for Id Monad Results in Compilation Failure
I do not understand how such a simple thing would be complicated? I'm trying to use the Id Monad from the typelevel cats library and for this purpose, I have added the following as my sbt dependency:

```<code>val scalaCATS = "org.typelevel" %% "cats-core" % "2.9.0"
val scalaCATSKernel = "org.typelevel" %% "cats-kernel" % "2.9.0"
val scalaCATSEffect = "org.typelevel" %% "cats-effect" % "3.4.2"
</code>```

I then have defined the following in my object like this:

```<code>import cats._

import java.net.URL
import java.time.ZonedDateTime

case class LocationAPIObject[F[_]](
  countryCode: F[String]
)
object Locations {

  val api = LocationAPIObject[Id] //
  ......
  ......
}

[error] 40 |  val api = LocationAPIObject[Id]
[error]    |                              ^^
[error]    |                              Not found: type Id
</code>```

Any ideas as to what else I'm missing here?

Body:
I do not understand how such a simple thing would be complicated? I'm trying to use the Id Monad from the typelevel cats library and for this purpose, I have added the following as my sbt dependency:

val scalaCATS = "org.typelevel" %% "cats-core" % "2.9.0"
val scalaCATSKernel = "org.typelevel" %% "cats-kernel" % "2.9.0"
val scalaCATSEffect = "org.typelevel" %% "cats-effect" % "3.4.2"

I then have defined the following in my object like this:

import cats._

import java.net.URL
import java.time.ZonedDateTime

case class LocationAPIObject[F[_]](
  countryCode: F[String]
)
object Locations {

  val api = LocationAPIObject[Id] //
  ......
  ......
}

[error] 40 |  val api = LocationAPIObject[Id]
[error]    |                              ^^
[error]    |                              Not found: type Id

Any ideas as to what else I'm missing here?


问:
Struggling to work with 1d array from API to spreadsheet
Code that I'm working with:

function BTC_1hour() {

  var url = '/api/v1/market/candles?type=1min&symbol=BTC-USDT&startAt=1566703297';

  var response = UrlFetchApp.fetch(url); // store API fetch in variable named response
  var JSONresponse = JSON.parse(response);
  var formatData = JSONresponse.data;

  for (var i = 0; i < formatData.length; i++)
  {
    for (var j =0; j < formatData[i].length; j++)
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName('1h');
    sheet.getRange(1,1,formatData.length, formatData[0].length).setValues(formatData);
    Logger.log(formatData[i][j])
    {

    }
  }

}
```

output into Google Sheets:

enter image description here

I'm trying to figure out how to no longer get the data that prints in columns F and G as well as format the date in column A from Epoch in seconds to human readable format.

Body:
Code that I'm working with:

function BTC_1hour() {

  var url = '/api/v1/market/candles?type=1min&symbol=BTC-USDT&startAt=1566703297';

  var response = UrlFetchApp.fetch(url); // store API fetch in variable named response
  var JSONresponse = JSON.parse(response);
  var formatData = JSONresponse.data;

  for (var i = 0; i < formatData.length; i++)
  {
    for (var j =0; j < formatData[i].length; j++)
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName('1h');
    sheet.getRange(1,1,formatData.length, formatData[0].length).setValues(formatData);
    Logger.log(formatData[i][j])
    {

    }
  }

}

output into Google Sheets:

enter image description here

I'm trying to figure out how to no longer get the data that prints in columns F and G as well as format the date in column A from Epoch in seconds to human readable format.


问:
Can I access the raw payloads?
Under some circumstances I find myself needing to access the raw payload posted to either a grpc endpoint or to a gateway that exposes it for http1/REST. More specifically invalid payloads are sometimes posted and I have no way of logging the actual payload posted by the client since the struct passed to the handler will only capture the expected bits from the request payload.

I don't see anything in the context object passed to my handler funcs that would allow one to access the original, unadulterated payload. Am I missing something?

Title: Can I access the raw payloads?


问:
How to use a literal in an offset in GNU assembly?
I have a 30k empty string of bytes, I want to write 50 to the 3rd byte and feed it to putchar. I will have a lot of these writes, so I don't want to move 50 to a register first and waste a command. All the offsets are known at compilation time and I just want to put a literal in a command. I tried this:

```<code>    .bss
mem:
    .zero 30000
    .text
    .globl main
main:
    pushq %rbp
    movq %rsp, %rbp
    movq $50, mem($3)
    movzbl mem($3), %edi
    call putchar
    leave
</code>```

It would complain about the literal with the following error:
/out2.s:9: Error: 'junk ($3)' after expression

I tried to store the location of mem in a register and operate on that, by changing the code to the following:

```<code>    .bss
mem:
    .zero 30000
    .text
    .globl main
main:
    pushq %rbp
    movq %rsp, %rbp
    movq mem, %rbx;  we store the location of mem in %rbx and reuse it later
    movq $50, 3(%rbx)
    movzbl 3(%rbx), %edi
    call putchar
    leave
</code>```

But this results in a segementation fault. I use gcc version 11.3.0 (Ubuntu 11.3.0-1ubuntu1~22.04), compiling to x86_64-linux-gnu. Any tips?

Body:
I have a 30k empty string of bytes, I want to write 50 to the 3rd byte and feed it to putchar. I will have a lot of these writes, so I don't want to move 50 to a register first and waste a command. All the offsets are known at compilation time and I just want to put a literal in a command. I tried this:

    .bss
mem:
    .zero 30000
    .text
    .globl main
main:
    pushq %rbp
    movq %rsp, %rbp
    movq $50, mem($3)
    movzbl mem($3), %edi
    call putchar
    leave

It would complain about the literal with the following error:
/out2.s:9: Error: 'junk ($3)' after expression

I tried to store the location of mem in a register and operate on that, by changing the code to the following:

    .bss
mem:
    .zero 30000
    .text
    .globl main
main:
    pushq %rbp
    movq %rsp, %rbp
    movq mem, %rbx;  we store the location of mem in %rbx and reuse it later
    movq $50, 3(%rbx)
    movzbl 3(%rbx), %edi
    call putchar
    leave

But this results in a segementation fault. I use gcc version 11.3.0 (Ubuntu 11.3.0-1ubuntu1~22.04), compiling to x86_64-linux-gnu. Any tips?


问:
How to aggregate data by time series and create a square matrix?
I am trying to plot a dendrogram according to the time series. I should base it on 27x27 matrix (country names in columns) and am only allowed to use R standard package, dplyr and ggplot2 libraries. I used to aggregate the data by mean but it turned out the plot below wasn't done this way. I'm struggling to understand how I am supposed to obtain one value for each country another way.

I should obtain such plot:
goal dendrogram

```<code>library("eurostat")
library("ggplot2")
library("dplyr")

d <- get_eurostat("prc_hicp_manr") %>%
  filter(coicop == "CP00")

d2 <- label_eurostat(d) %>%
  filter(time %in% as.Date("2000-02-01"):as.Date("2022-09-30"),
         geo %in% c("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Chechia", "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", "Hungary",
                    "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia", "Slovenia",
                    "Spain", "Sweden"))

d3 <- d2[,c("geo","values")]
d3

#m <- matrix(?)

dist <- dist(m, method = "minkowski", p = 1.5)

d3_hclust  <- hclust(dist, method = "complete")
d3_dend <- as.dendrogram(d3_hclust)
plot(d3_dend)

</code>```

Body:
I am trying to plot a dendrogram according to the time series. I should base it on 27x27 matrix (country names in columns) and am only allowed to use R standard package, dplyr and ggplot2 libraries. I used to aggregate the data by mean but it turned out the plot below wasn't done this way. I'm struggling to understand how I am supposed to obtain one value for each country another way.

I should obtain such plot:
goal dendrogram

library("eurostat")
library("ggplot2")
library("dplyr")

d <- get_eurostat("prc_hicp_manr") %>%
  filter(coicop == "CP00")

d2 <- label_eurostat(d) %>%
  filter(time %in% as.Date("2000-02-01"):as.Date("2022-09-30"),
         geo %in% c("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Chechia", "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", "Hungary",
                    "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia", "Slovenia",
                    "Spain", "Sweden"))

d3 <- d2[,c("geo","values")]
d3

#m <- matrix(?)

dist <- dist(m, method = "minkowski", p = 1.5)

d3_hclust  <- hclust(dist, method = "complete")
d3_dend <- as.dendrogram(d3_hclust)
plot(d3_dend)


问:
Tail chain parented wrong after using skin modifier
I was using a skin modifier to make a character. I added a tail, but the chain of bones were parented wrong, the tail influences the entire body.
Default Pose
Editing Base of tail

Unfortunately, I can't change the parent myself through
Properties > Bone Properties > Relations > Parent due to it being disabled.

How do I fix this, if possible.


问:
How can I explain these Apache graphs? (idle workers, busy workers, etc.)
I am trying to optimize my Apache web server. That is why I am trying to analyze certain graphs and parameters. I have been able to read a lot of information, but I still have some doubts in my head. One doubt I have in my head is the idle_workers.

In a lot of documentation all over the Internet I have read that the idle workers should never stay at 0. Is this true?

I am going to put for example certain graphs of my server, there are several peaks where you can see that my server runs out of idle workers at certain times, but the vast majority of the time my idle workers are almost never at zero.

My Apache MPM type is prefork.

I am working on an EC2 m5.8xlarge server with the following configuration:

32 vCPU

128 Memory(GiB)

Storage EBS

10 Gbps Network Bandwidth

6,800 Mbps EBS Bandwidth

This server is only dedicated to Apache. My database is in RDS.

Looking at the ram memory utilization of my server, I have almost 120Gb/128Gb free just for my apache. For this reason, following several tutorials on the Internet on how to optimize apache I have obtained and applied the following configurations:

```<code>IfModule mpm_prefork_module>
  ServerLimit 749
  StartServers 225
  MinSpareServers 37
  MaxSpareServers 75
  MaxRequestWorkers 749
  MaxConnectionsPerChild 10000
</IfModule>
</code>```

Still I am having certain "problems" with idle workers, that actually I don't know if it is problem to stay without idle worker for some minutes (look at graph of my server).

I must say that my site has a concurrency of approximately 600-800 connections. But looking at my server capacity, this should be enough.

Can anyone give me some light on this, is this behavior normal?

Also, I leave you other graphs and values, to see if you think these are normal values or not at all.

Body:
I am trying to optimize my Apache web server. That is why I am trying to analyze certain graphs and parameters. I have been able to read a lot of information, but I still have some doubts in my head. One doubt I have in my head is the idle_workers.

In a lot of documentation all over the Internet I have read that the idle workers should never stay at 0. Is this true?

I am going to put for example certain graphs of my server, there are several peaks where you can see that my server runs out of idle workers at certain times, but the vast majority of the time my idle workers are almost never at zero.

My Apache MPM type is prefork.

I am working on an EC2 m5.8xlarge server with the following configuration:

32 vCPU

128 Memory(GiB)

Storage EBS

10 Gbps Network Bandwidth

6,800 Mbps EBS Bandwidth

This server is only dedicated to Apache. My database is in RDS.

Looking at the ram memory utilization of my server, I have almost 120Gb/128Gb free just for my apache. For this reason, following several tutorials on the Internet on how to optimize apache I have obtained and applied the following configurations:

IfModule mpm_prefork_module>
  ServerLimit 749
  StartServers 225
  MinSpareServers 37
  MaxSpareServers 75
  MaxRequestWorkers 749
  MaxConnectionsPerChild 10000
</IfModule>

Still I am having certain "problems" with idle workers, that actually I don't know if it is problem to stay without idle worker for some minutes (look at graph of my server).

I must say that my site has a concurrency of approximately 600-800 connections. But looking at my server capacity, this should be enough.

Can anyone give me some light on this, is this behavior normal?

Also, I leave you other graphs and values, to see if you think these are normal values or not at all.


问:
sapui5: sap.m.SelectList with context menu
I'm using sap.m.SelectList in the XML-View to give a possibility to choose key/value pairs and need to extend it with context menu which is available in sap.m.List. I have problems with it, because ContextMenu is defined in sap.m.ListBase, sap.m.List inherits it, but sap.m.SelectList does not.

What is the simplest or recommended approach? My restriction is, I've to use XML-View (but can extend it in JS).

Regards,
Annie


问:
Transection in Fragments in android studio using java
Is there any way to create transactions in fragments by sliding the screen as well as touching the fragments in android studio using java? Like in WhatsApp transactions can be done by touching chat, status, or call as well as it is done by sliding the screen left and right.</p>


问:
How to avoid commiting minified react files to source code
I have 2 different react projects, let say projectA , projectB

here i am using projectA build files(minified files, the files which i got after doing npm build) in the projectB public folder

the process which i am doing is manually copying build files into public folder and using those files inside projectB, but the problem  here is i had to  commit the minified files into repository which i should not be doing it ,

is there any way that i can copy or specify the path of projectA dependencies when i build or run the projectB ?

my whole point is to avoid committing minified files to source code


问:
Android: where to put the Intent in login and register Fragment
this is my first android project.
I am making a login and register page for a game i am making, and i'm trying to figure the login/register stuff. my project so far consists of MainActivity.java, LoginFragment and a RegisterFragment.
my question is after declaring the username, password, loginbtn variables how should my Intent intent declaration look like?

note aside, my mainActivity consists of a viewPager which just lets me slide through the login and register pages. but i will supply the code below

mainActivity.java

```<code>package com.example.my_app_2;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.app.Dialog;
import android.content.Intent;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Button btnSignIn, btnSignUp;

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

        //create instance of SQLite Database

        ViewPager viewPager = findViewById(R.id.viewPager);

        AuthenticationPagerAdapter pagerAdapter = new AuthenticationPagerAdapter(getSupportFragmentManager());
        pagerAdapter.addFragmet(new LoginFragment());
        pagerAdapter.addFragmet(new RegisterFragment());
        viewPager.setAdapter(pagerAdapter);
    }

    static class AuthenticationPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> fragmentList = new ArrayList<>();

        public AuthenticationPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return fragmentList.get(i);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        void addFragmet(Fragment fragment) {
            fragmentList.add(fragment);
        }
    }
}

</code>```

LoginFragment:

```<code>package com.example.my_app_2;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

/**
 * A simple {@link Fragment} subclass.
 */
public class LoginFragment extends Fragment {
    EditText username, password;
    Button loginbtn;

    public LoginFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_login, container,false);

        username = v.findViewById(R.id.username);
        password = v.findViewById(R.id.password);
        loginbtn = v.findViewById(R.id.loginbtn);

        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String usernameValue = username.getText().toString();
                String passwordValue = password.getText().toString();

               // i assume the Intent intent goes here, but i have no idea what arugments/parameters pass in the new Intent() part of it
            }
        });

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_login, container, false);

    }

}

</code>```

and same goes with the registerFragment

```<code>package com.example.my_app_2;

import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

/**
 * A simple {@link Fragment} subclass.
 */
public class RegisterFragment extends Fragment {

    EditText username, password, email;
    Button signupbtn;

    public RegisterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_register, container,false);

        username = v.findViewById(R.id.username);
        password = v.findViewById(R.id.password);
        email = v.findViewById(R.id.email);
        signupbtn = v.findViewById(R.id.signupbtn);

        signupbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String usernameValue = username.getText().toString();
                String passwordValue = password.getText().toString();
                String emailValue = email.getText().toString();

                Intent intent = new Intent();

            }
        });

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_register, container, false);
    }

}

</code>```

what i have tried to do...

what i am trying to do is just take the username and password and store them in sharedPreferences.
thanks in advance, i apoligize for the silliness of the question but any help would be appreciated!

i have tried Intent intent = new Intent(this, RegisterFragment); // ??????
honestly im kinda clueless lol xd

(RegisterFragment.this); // ???????

Body:
this is my first android project.
I am making a login and register page for a game i am making, and i'm trying to figure the login/register stuff. my project so far consists of MainActivity.java, LoginFragment and a RegisterFragment.
my question is after declaring the username, password, loginbtn variables how should my Intent intent declaration look like?

note aside, my mainActivity consists of a viewPager which just lets me slide through the login and register pages. but i will supply the code below

mainActivity.java

package com.example.my_app_2;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.app.Dialog;
import android.content.Intent;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Button btnSignIn, btnSignUp;

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

        //create instance of SQLite Database

        ViewPager viewPager = findViewById(R.id.viewPager);

        AuthenticationPagerAdapter pagerAdapter = new AuthenticationPagerAdapter(getSupportFragmentManager());
        pagerAdapter.addFragmet(new LoginFragment());
        pagerAdapter.addFragmet(new RegisterFragment());
        viewPager.setAdapter(pagerAdapter);
    }

    static class AuthenticationPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> fragmentList = new ArrayList<>();

        public AuthenticationPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return fragmentList.get(i);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        void addFragmet(Fragment fragment) {
            fragmentList.add(fragment);
        }
    }
}

LoginFragment:

package com.example.my_app_2;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

/**
 * A simple {@link Fragment} subclass.
 */
public class LoginFragment extends Fragment {
    EditText username, password;
    Button loginbtn;

    public LoginFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_login, container,false);

        username = v.findViewById(R.id.username);
        password = v.findViewById(R.id.password);
        loginbtn = v.findViewById(R.id.loginbtn);

        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String usernameValue = username.getText().toString();
                String passwordValue = password.getText().toString();

               // i assume the Intent intent goes here, but i have no idea what arugments/parameters pass in the new Intent() part of it
            }
        });

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_login, container, false);

    }

}

and same goes with the registerFragment

package com.example.my_app_2;

import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

/**
 * A simple {@link Fragment} subclass.
 */
public class RegisterFragment extends Fragment {

    EditText username, password, email;
    Button signupbtn;

    public RegisterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_register, container,false);

        username = v.findViewById(R.id.username);
        password = v.findViewById(R.id.password);
        email = v.findViewById(R.id.email);
        signupbtn = v.findViewById(R.id.signupbtn);

        signupbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String usernameValue = username.getText().toString();
                String passwordValue = password.getText().toString();
                String emailValue = email.getText().toString();

                Intent intent = new Intent();

            }
        });

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_register, container, false);
    }

}

what i have tried to do...

what i am trying to do is just take the username and password and store them in sharedPreferences.
thanks in advance, i apoligize for the silliness of the question but any help would be appreciated!

i have tried Intent intent = new Intent(this, RegisterFragment); // ??????
honestly im kinda clueless lol xd

(RegisterFragment.this); // ???????


问:
What is best practice for importing a java package or library into a Python project
Researching efforts to write python application to wrap around a java package.

I've found good info on resources to integrate Python with Java classes (you can see a list below), but one thing I can't find a definitive answer is how one could automatically import a .jar package into a Python project.

Is this something pip can handle?

Resources

For CPython, Apache Trift could be a solution: http://thrift.apache.org/

makes additional abstraction layer to integrate your Java code with different languages (not only Python)

Py4J - Bridge between Python and Java

Py4J doesn't contain a JVM, so you must have one living (hence the java program) to let Py4J access the library.

Getting started

Python Wrapper for Java Implementation example

python-javabridge

Appears to be stale

PyJNIus: module to access Java classes as Python classes

JNI could be valuable for low level interface: http://java.sun.com/docs/books/jni/

pip library for installing jdk: install-jdk

pip library for importing java: import-java


问:
Trouble importing sklearn while using joblib
I have a prediction program that predicts binary classifications using classifiers. When I try to run the program I get the same issues over and over again:

```<code>Traceback (most recent call last):
  File ".\predict.py", line 252, in main
    clf = joblib.load('classifier.pkl')
  File "C:\Users\rando\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\joblib\numpy_pickle.py", line 585, in load
    obj = _unpickle(fobj, filename, mmap_mode)
  File "C:\Users\rando\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\joblib\numpy_pickle.py", line 504, in _unpickle
    obj = unpickler.load()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\pickle.py", line 1212, in load
    dispatch[key[0]](self)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\pickle.py", line 1537, in load_stack_global
    self.append(self.find_class(module, name))
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\pickle.py", line 1579, in find_class
    __import__(module, level=0)
ModuleNotFoundError: No module named 'sklearn'

</code>```

I have tried the following:

pip3 install scikit-learn scipy matplotlib numpy

pip3 uninstall joblib && pip3 install joblib sklearn

pip3 uninstall sklearn joblib && pip3 install joblib==1.0.1

It appears that sklearn is being imported somewhere however I don't ever import it?

Body:
I have a prediction program that predicts binary classifications using classifiers. When I try to run the program I get the same issues over and over again:

Traceback (most recent call last):
  File ".\predict.py", line 252, in main
    clf = joblib.load('classifier.pkl')
  File "C:\Users\rando\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\joblib\numpy_pickle.py", line 585, in load
    obj = _unpickle(fobj, filename, mmap_mode)
  File "C:\Users\rando\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\joblib\numpy_pickle.py", line 504, in _unpickle
    obj = unpickler.load()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\pickle.py", line 1212, in load
    dispatch[key[0]](self)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\pickle.py", line 1537, in load_stack_global
    self.append(self.find_class(module, name))
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\pickle.py", line 1579, in find_class
    __import__(module, level=0)
ModuleNotFoundError: No module named 'sklearn'

I have tried the following:

pip3 install scikit-learn scipy matplotlib numpy

pip3 uninstall joblib && pip3 install joblib sklearn

pip3 uninstall sklearn joblib && pip3 install joblib==1.0.1

It appears that sklearn is being imported somewhere however I don't ever import it?


问:
Usage of Modules and stratégie du petit r with navbarPage
I try to understand the usage of modules and stratégie du petit r.
I would like to receive feedback if I used the components correctly?
Also I'm interested: Does it make sense to structure an application in the way that each tabPanel is 1 Module? For Example File Upload, Overview, Clustering, and Reporting.

For this, I built a small application.
A navBarpage with 2 panels. For each tabPanel one module exists which creates the UI and contains the server logic for the panel.

tabPanel 1 / Module "something"

numeric Input -> user can choose between 1,2,3

action button. When pressed the panel View changes.

tabPanel 2 / Module "happend"

shows the chosen number

app_ui (UI-structure and calls module UI)

server_ui (calls Module Servers)

mod_something (Numberinput and actionButton to change panel)

mod_happend ( Displays number)

`

app_ui

```<code>app_ui <- function(request) {
  tagList(
    # Leave this function for adding external resources
    golem_add_external_resources(),
    # Your application UI logic
    fluidPage(
      navbarPage("navBarPage",
                 id = "navBarID",
                 tabPanel("title1",
                          mod_something_ui("something_1")),
                 tabPanel("title2",
                          mod_happend_ui("happend_1")),
      )
    )
  )
}
</code>```

app_server

```<code>app_server <- function(input, output, session) {
  # Your application server logic
  r <- reactiveValues()
  #mod_Navigation_server("navigation1",r)
  mod_something_server("something_1", r = r,parent = session)
  mod_happend_server("happend_1",r)
  #?moduleServer
}
</code>```

mod_something

```<code>mod_something_ui <- function(id){
  ns <- NS(id)
  tagList(
    selectInput(inputId = ns("numberInput"), label = "choose", choices = c(1,2,3)),
    actionButton(inputId = ns("doSomething"),label = "Change Page!"),

  )
}

mod_something_server <- function(id,r,parent){
  moduleServer(id, function(input, output, session){
    ns <- session$ns
    observe({
      r$numberInput <- input$numberInput
    })
    observeEvent(eventExpr = input$doSomething,
                 updateNavbarPage(session = parent, inputId = "navBarID", selected = "title2"))

  })
}
</code>```

mod_happend

```<code>mod_happend_ui <- function(id){
  ns <- NS(id)
  tagList(
  p("the Number is"),
  textOutput(ns("choosenNumber")),
  )
}

#' happend Server Functions
#'
#' @noRd
mod_happend_server <- function(id,r){
  moduleServer( id, function(input, output, session){
    ns <- session$ns
    number <- reactive(r$numberInput)
    output$choosenNumber <- renderText(number())

  })
}
</code>```

`

Body:
I try to understand the usage of modules and stratégie du petit r.
I would like to receive feedback if I used the components correctly?
Also I'm interested: Does it make sense to structure an application in the way that each tabPanel is 1 Module? For Example File Upload, Overview, Clustering, and Reporting.

For this, I built a small application.
A navBarpage with 2 panels. For each tabPanel one module exists which creates the UI and contains the server logic for the panel.

tabPanel 1 / Module "something"

numeric Input -> user can choose between 1,2,3

action button. When pressed the panel View changes.

tabPanel 2 / Module "happend"

shows the chosen number

app_ui (UI-structure and calls module UI)

server_ui (calls Module Servers)

mod_something (Numberinput and actionButton to change panel)

mod_happend ( Displays number)

`

app_ui

app_ui <- function(request) {
  tagList(
    # Leave this function for adding external resources
    golem_add_external_resources(),
    # Your application UI logic
    fluidPage(
      navbarPage("navBarPage",
                 id = "navBarID",
                 tabPanel("title1",
                          mod_something_ui("something_1")),
                 tabPanel("title2",
                          mod_happend_ui("happend_1")),
      )
    )
  )
}

app_server

app_server <- function(input, output, session) {
  # Your application server logic
  r <- reactiveValues()
  #mod_Navigation_server("navigation1",r)
  mod_something_server("something_1", r = r,parent = session)
  mod_happend_server("happend_1",r)
  #?moduleServer
}

mod_something

mod_something_ui <- function(id){
  ns <- NS(id)
  tagList(
    selectInput(inputId = ns("numberInput"), label = "choose", choices = c(1,2,3)),
    actionButton(inputId = ns("doSomething"),label = "Change Page!"),

  )
}

mod_something_server <- function(id,r,parent){
  moduleServer(id, function(input, output, session){
    ns <- session$ns
    observe({
      r$numberInput <- input$numberInput
    })
    observeEvent(eventExpr = input$doSomething,
                 updateNavbarPage(session = parent, inputId = "navBarID", selected = "title2"))

  })
}

mod_happend

mod_happend_ui <- function(id){
  ns <- NS(id)
  tagList(
  p("the Number is"),
  textOutput(ns("choosenNumber")),
  )
}

#' happend Server Functions
#'
#' @noRd
mod_happend_server <- function(id,r){
  moduleServer( id, function(input, output, session){
    ns <- session$ns
    number <- reactive(r$numberInput)
    output$choosenNumber <- renderText(number())

  })
}

`


问:
Meta box not displaying on the plugin page
I am working on a plugin and I am creating a meta box on my page using the below code but it's not displaying anything.

Any idea where is the issue with my code?

```<code>class bt_dashboard {
    function __construct() {
        add_meta_box( 'metaboxes-sidebox-1', 'Sidebox 1 Title', array( $this, 'welcome_bt' ), 'welcomebt', 'advanced', 'default' );
    }

    function setup() {
        // setup class, maybe add hooks
    }

    function welcome_bt() {
        ?>
        <h2>Wellcome to metabox</h2>
        <?php
    }
}
</code>```

Meta box not displaying on the plugin page

Body:
I am working on a plugin and I am creating a meta box on my page using the below code but it's not displaying anything.

Any idea where is the issue with my code?

class bt_dashboard {
    function __construct() {
        add_meta_box( 'metaboxes-sidebox-1', 'Sidebox 1 Title', array( $this, 'welcome_bt' ), 'welcomebt', 'advanced', 'default' );
    }

    function setup() {
        // setup class, maybe add hooks
    }

    function welcome_bt() {
        ?>

Wellcome to metabox

        <?php
    }
}

Meta box not displaying on the plugin page


问:
Is there any way to view app engine endpoints latency?
I need to view the average response time of different endpoints on my app engine application. Is there any way to do so? Setting a response header maybe? Generating a log?

I need to know which endpoints are slow to see if they need optimization.

I've seen that you can get the average response time of all endpoints but i don't know if you can be more specific.


问:
PasswordSignInAsync return always false identity ASP NET
after adding the user to the database, i try to log in but PasswordSignInAsync doesn't work, it always returns failed.

so i tried to find out what was going on. it turns out that the CheckPasswordAsync method, which compares the password provided by the form with the database, returns false.
does anyone know how to fix this so i can log in?

the password in the database and in the form are the same (I checked)

Controller

```<code>var user = await _userManager.FindByEmailAsync(model.Email);
            var checkPass = await _userManager.CheckPasswordAsync(user, model.Password);
</code>```

Program

```<code>builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddIdentityCore<ApplicationUser>(options => { options.SignIn.RequireConfirmedAccount = false;
    options.SignIn.RequireConfirmedEmail = false;
    options.SignIn.RequireConfirmedPhoneNumber = false;
})
    .AddEntityFrameworkStores<AppDbContext>();
builder.Services.Configure<IdentityOptions>(options =>
{

    // Password settings.
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
    options.Password.RequiredUniqueChars = 1;

    // Lockout settings.
    //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    //options.Lockout.MaxFailedAccessAttempts = 5;
    //options.Lockout.AllowedForNewUsers = true;

    // User settings.
    options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    options.User.RequireUniqueEmail = false;
});

builder.Services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = "/Identity/Account/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.SlidingExpiration = true;
});

builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<IAuthRepo, AuthRepo>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IUser, User>();
builder.Services.AddScoped<AuthRepo>();
builder.Services.AddScoped<HashPassword>();

builder.Services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = "/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.SlidingExpiration = true;
});

app.UseAuthentication();
app.UseAuthorization();
</code>```

Body:
after adding the user to the database, i try to log in but PasswordSignInAsync doesn't work, it always returns failed.

so i tried to find out what was going on. it turns out that the CheckPasswordAsync method, which compares the password provided by the form with the database, returns false.
does anyone know how to fix this so i can log in?

the password in the database and in the form are the same (I checked)

Controller

var user = await _userManager.FindByEmailAsync(model.Email);
            var checkPass = await _userManager.CheckPasswordAsync(user, model.Password);

Program

builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddIdentityCore<ApplicationUser>(options => { options.SignIn.RequireConfirmedAccount = false;
    options.SignIn.RequireConfirmedEmail = false;
    options.SignIn.RequireConfirmedPhoneNumber = false;
})
    .AddEntityFrameworkStores<AppDbContext>();
builder.Services.Configure<IdentityOptions>(options =>
{

    // Password settings.
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
    options.Password.RequiredUniqueChars = 1;

    // Lockout settings.
    //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    //options.Lockout.MaxFailedAccessAttempts = 5;
    //options.Lockout.AllowedForNewUsers = true;

    // User settings.
    options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    options.User.RequireUniqueEmail = false;
});

builder.Services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = "/Identity/Account/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.SlidingExpiration = true;
});

builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<IAuthRepo, AuthRepo>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IUser, User>();
builder.Services.AddScoped<AuthRepo>();
builder.Services.AddScoped<HashPassword>();

builder.Services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

    options.LoginPath = "/Login";
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.SlidingExpiration = true;
});

app.UseAuthentication();
app.UseAuthorization();


问:
Add Attachments to Nodeemailer based on a condition
I am trying to figure out a good way of doing this. In my node emailer , I may or may not have attachments depending on user interaction , how can I add attachments to my transport at run time.

I am creating two different options bodies right now one with the attachments and one without. Is this a good practice?