问:
mysql2 gem Segmentation fault at 0x0000000000000000 Aborted (core dumped)
I am using Ruby 3.0.4 with Rails 7.0.4 with rvm.
I have a Rails project, but when I try to do anything with the mysql database (create or setup), it throws a segmentation fault.

I am on Ubuntu Ubuntu 22.04.1 LTS. The mysql version is Ver 8.0.31-0ubuntu0.22.04.1 for Linux on x86_64 ((Ubuntu)).

Here is some of the error:

```<code>```
Top level ::CompositeIO is deprecated, require 'multipart/post' and use `Multipart::Post::CompositeReadIO` instead!
Top level ::Parts is deprecated, require 'multipart/post' and use `Multipart::Post::Parts` instead!
W, [2023-01-12T12:59:10.830314 #125121]  WARN -- Skylight: [SKYLIGHT] [5.3.4] Running Skylight in development mode. No data will be reported until you deploy your app.
(To disable this message for all local apps, run `skylight disable_dev_warning`.)
/External-drive/Personal/Projects/breakabletoy/vendor/bundle/ruby/3.0.0/gems/mysql2-0.5.4/lib/mysql2/client.rb:95: [BUG] Segmentation fault at 0x0000000000000000
ruby 3.0.4p208 (2022-04-12 revision 3fa771dded) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0049 p:---- s:0274 e:000273 CFUNC  :connect
c:0048 p:0623 s:0262 e:000261 METHOD /External-drive/Personal/Projects/breakabletoy/vendor/bundle/ruby/3.0.0/gems/mysql2-0.5.4/lib/mysql2/client.rb:95 [FINISH]
```
</code>```

...and, at the end...

```<code>```
7f91e72b2000-7f91e72dc000 r-xp 00002000 103:02 31066233                  /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f91e72dc000-7f91e72e7000 r--p 0002c000 103:02 31066233                  /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f91e72e7000-7f91e72e8000 r-xp 00000000 00:00 0
7f91e72e8000-7f91e72ea000 r--p 00037000 103:02 31066233                  /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f91e72ea000-7f91e72ec000 rw-p 00039000 103:02 31066233                  /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7ffedcfb9000-7ffedd7b8000 rw-p 00000000 00:00 0                          [stack]
7ffedd7bc000-7ffedd7c0000 r--p 00000000 00:00 0                          [vvar]
7ffedd7c0000-7ffedd7c2000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0                  [vsyscall]

Aborted (core dumped)
```
</code>```

The fix at mysql2 Segmentation fault at 0x0000000000000000 doesn't work, given that sudo apt install libmariadbclient-dev isn't found.

I've also installed the dependencies required in the github of the page https://github.com/brianmario/mysql2.
I've also uninstalled and reinstalled my rvm, but nothing works.
Any help would be greatly appreciated.

Body:
I am using Ruby 3.0.4 with Rails 7.0.4 with rvm.
I have a Rails project, but when I try to do anything with the mysql database (create or setup), it throws a segmentation fault.

I am on Ubuntu Ubuntu 22.04.1 LTS. The mysql version is Ver 8.0.31-0ubuntu0.22.04.1 for Linux on x86_64 ((Ubuntu)).

Here is some of the error:

```
Top level ::CompositeIO is deprecated, require 'multipart/post' and use `Multipart::Post::CompositeReadIO` instead!
Top level ::Parts is deprecated, require 'multipart/post' and use `Multipart::Post::Parts` instead!
W, [2023-01-12T12:59:10.830314 #125121]  WARN -- Skylight: [SKYLIGHT] [5.3.4] Running Skylight in development mode. No data will be reported until you deploy your app.
(To disable this message for all local apps, run `skylight disable_dev_warning`.)
/External-drive/Personal/Projects/breakabletoy/vendor/bundle/ruby/3.0.0/gems/mysql2-0.5.4/lib/mysql2/client.rb:95: [BUG] Segmentation fault at 0x0000000000000000
ruby 3.0.4p208 (2022-04-12 revision 3fa771dded) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0049 p:---- s:0274 e:000273 CFUNC  :connect
c:0048 p:0623 s:0262 e:000261 METHOD /External-drive/Personal/Projects/breakabletoy/vendor/bundle/ruby/3.0.0/gems/mysql2-0.5.4/lib/mysql2/client.rb:95 [FINISH]
```

...and, at the end...

```
7f91e72b2000-7f91e72dc000 r-xp 00002000 103:02 31066233                  /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f91e72dc000-7f91e72e7000 r--p 0002c000 103:02 31066233                  /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f91e72e7000-7f91e72e8000 r-xp 00000000 00:00 0
7f91e72e8000-7f91e72ea000 r--p 00037000 103:02 31066233                  /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f91e72ea000-7f91e72ec000 rw-p 00039000 103:02 31066233                  /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7ffedcfb9000-7ffedd7b8000 rw-p 00000000 00:00 0                          [stack]
7ffedd7bc000-7ffedd7c0000 r--p 00000000 00:00 0                          [vvar]
7ffedd7c0000-7ffedd7c2000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0                  [vsyscall]

Aborted (core dumped)
```

The fix at mysql2 Segmentation fault at 0x0000000000000000 doesn't work, given that sudo apt install libmariadbclient-dev isn't found.

I've also installed the dependencies required in the github of the page https://github.com/brianmario/mysql2.
I've also uninstalled and reinstalled my rvm, but nothing works.
Any help would be greatly appreciated.


来源: stackexchange

问:
Git for Windows Commits
I've been tasked to make a presentation about a topic, but every slide should be added into a repository as a commit using Git for Windows. My question is if I just add the file each time manually to the repository, will it look different then if i did it by Git for Windows? Thank you

Tried adding the file manually but im a noob so i dont know if theres a difference

ContentLicense: CC BY-SA 4.0

Title: Git for Windows Commits


问:
Show URLs as links in markers when viewing Google My Maps in iOS app
I have created a custom map in Google's "My Maps" tool. I have created several location markers by importing data from a Google Sheet. One of the columns in my sheet has a URL in it.

The import works fine, and my map works well, for the most part. However, I have an issue with how the URLs are displayed.

When someone views my map in a desktop browser, this URLs are automatically converted to links and the user can easily click them to navigate to the location. Example:

Unfortunately, if you view the same map on iOS, it launches in the Google Maps app (which is fine, I guess) and when you open the details for the location marker the URL is displayed as plain text and is not clickable. Example:

Any ideas? Can I change something in the map configuration? Or in the data itself?


问:
Black screen in react code - possible firebase auth issue
this code is giving me a blank screen i have no idea as to why i would assume its firebase auth or the logic giving me trouble im running this in vscode and its compiling sucessfully

```<code>import { createUserWithEmailAndPassword } from "firebase/auth";
import React, { useState } from "react";
import { auth } from "../firebase";
import { Link } from "react-router-dom";

const SignUp = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [error, setError] = useState("");

  const signUp = (e) => {
    e.preventDefault();
    auth.createUserWithEmailAndPassword(email, password).then((userCredential) => {
        userCredential.user
          .updateProfile({
            displayName: name,
          })
          .then(() => {
            console.log("user name added");
          })
          .catch((error) => {
            console.log(error);
          });
      })
      .catch((error) => {
        setError(error.message);
      });
  };

  return (
    <div className="container mx-auto flex justify-center pt-6">
      <form className="bg-white p-6 rounded-lg shadow-xl" onSubmit={signUp}>
        <div className="mb-4">
          <label
            className="block text-gray-700 font-medium mb-2"
            htmlFor="name"
          >
            Name
          </label>
          <input
            className="w-full border border-gray-400 p-2 rounded-md"
            id="name"
            type="text"
            placeholder="Enter your name"
            onChange={(e) => setName(e.target.value)}
          />
        </div>
        <div className="mb-4">
          <label
            className="block text-gray-700 font-medium mb-2"
            htmlFor="email"
          >
            Email
          </label>
          <input
                        className="w-full border border-gray-400 p-2 rounded-md"
                        id="email"
                        type="email"
                        placeholder="Enter your email"
                        onChange={(e) => setEmail(e.target.value)}
                      />
                    </div>
                    <div className="mb-4">
                      <label
                        className="block text-gray-700 font-medium mb-2"
                        htmlFor="password"
                      >
                        Password
                      </label>
                      <input
                        className="w-full border border-gray-400 p-2 rounded-md"
                        id="password"
                        type="password"
                        placeholder="Enter your password"
                        onChange={(e) => setPassword(e.target.value)}
                      />
                    </div>
                    <div className="text-red-500 text-xs mb-4">{error}</div>
                    <button
                      className="bg-indigo-500 hover:bg-indigo-600 text-white py-2 px-4
                      rounded-md"
                      type="submit"
                    >
                      Sign Up
                    </button>
                    <Link
                      to="/login"
                      className="text-indigo-500 hover:text-indigo-600 font-medium py-2 px-4"
                    >
                      Already have an account?
                    </Link>
                  </form>
                </div>

              );
            };

            export default SignUp;
</code>```

was trying to make a signup page for my website that took in email and password to authenticate but also took a name to display on profile

Body:
this code is giving me a blank screen i have no idea as to why i would assume its firebase auth or the logic giving me trouble im running this in vscode and its compiling sucessfully

import { createUserWithEmailAndPassword } from "firebase/auth";
import React, { useState } from "react";
import { auth } from "../firebase";
import { Link } from "react-router-dom";

const SignUp = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [error, setError] = useState("");

  const signUp = (e) => {
    e.preventDefault();
    auth.createUserWithEmailAndPassword(email, password).then((userCredential) => {
        userCredential.user
          .updateProfile({
            displayName: name,
          })
          .then(() => {
            console.log("user name added");
          })
          .catch((error) => {
            console.log(error);
          });
      })
      .catch((error) => {
        setError(error.message);
      });
  };

  return (

      <form className="bg-white p-6 rounded-lg shadow-xl" onSubmit={signUp}>

            Name

          <input
            className="w-full border border-gray-400 p-2 rounded-md"
            id="name"
            type="text"
            placeholder="Enter your name"
            onChange={(e) => setName(e.target.value)}
          />

            Email

          <input
                        className="w-full border border-gray-400 p-2 rounded-md"
                        id="email"
                        type="email"
                        placeholder="Enter your email"
                        onChange={(e) => setEmail(e.target.value)}
                      />

                        Password

                      <input
                        className="w-full border border-gray-400 p-2 rounded-md"
                        id="password"
                        type="password"
                        placeholder="Enter your password"
                        onChange={(e) => setPassword(e.target.value)}
                      />

{error}

                    <button
                      className="bg-indigo-500 hover:bg-indigo-600 text-white py-2 px-4
                      rounded-md"
                      type="submit"
                    >
                      Sign Up
                    </button>
                    <Link
                      to="/login"
                      className="text-indigo-500 hover:text-indigo-600 font-medium py-2 px-4"
                    >
                      Already have an account?
                    </Link>
                  </form>

              );
            };

            export default SignUp;

was trying to make a signup page for my website that took in email and password to authenticate but also took a name to display on profile


问:
Error Preparing metadata (setup.py) ... error while installing STAMP
I am trying to install (linux) STAMP so I can analyze my PICRUST output. The code I'm following is:

sudo apt-get install libblas-dev liblapack-dev gfortran
sudo apt-get install freetype* python-pip python-dev python-numpy python-scipy python-matplotlib
sudo pip install STAMP

The error I get is:

```<code>Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─\> \[1 lines of output\]
Only Python 2.7 and 3.3 are supported.
\[end of output\]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─\> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

I created a conda environment with python 2.7 and another one with python 3.3 but in both of them I keep getting the same error. Any ideas on how I could install STAMP?

Body:
I am trying to install (linux) STAMP so I can analyze my PICRUST output. The code I'm following is:

sudo apt-get install libblas-dev liblapack-dev gfortran
sudo apt-get install freetype* python-pip python-dev python-numpy python-scipy python-matplotlib
sudo pip install STAMP

The error I get is:

Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─\> \[1 lines of output\]
Only Python 2.7 and 3.3 are supported.
\[end of output\]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─\> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

I created a conda environment with python 2.7 and another one with python 3.3 but in both of them I keep getting the same error. Any ideas on how I could install STAMP?


问:
GET request with useQuery passing a parameter in custom hook
I have to make a simple api call to an endpoint passing an id using react query.
I made my custom hook:

```<code>const useGetData = (id: string, onSuccess = noop, onError = noop) => {
  return {
    ...useQuery<string, Error>(
      ['my-key', id],
      async (): Promise<string> => {
        return await getSomeData(id);
      },

      {
        enabled: false,
        onError,
        onSuccess,
      }
    ),
  };
};
</code>```

getSomeData is something like that:

```<code>const getSomeData = async (id: any): Promise<string> => {
  try {
    const { data } = await http.get(`/api/${id}`);
    return data;
  } catch (err) {
    console.log('error');
  }
};
</code>```

In my component

```<code> const { isLoading, refetch: getDataFn } = useGetData(
    id,
    onSuccessFn
  );
</code>```

I have a button with a onClick handler that executes getDataFn.

In a page, I have a list of elements. I map that list and, for each element, I render the previous component.

The code seems to work fine but I have two question:

is this the correct way to pass a parameter via useQuery?

why even though it is "enabled: false" and no calls are made (from the network in the browser inspect no calls appear until I click the button), from the ReactQueryDevtoolsPanel I see a list of calls in stale?

Thanks!

Body:
I have to make a simple api call to an endpoint passing an id using react query.
I made my custom hook:

const useGetData = (id: string, onSuccess = noop, onError = noop) => {
  return {
    ...useQuery<string, Error>(
      ['my-key', id],
      async (): Promise<string> => {
        return await getSomeData(id);
      },

      {
        enabled: false,
        onError,
        onSuccess,
      }
    ),
  };
};

getSomeData is something like that:

const getSomeData = async (id: any): Promise<string> => {
  try {
    const { data } = await http.get(`/api/${id}`);
    return data;
  } catch (err) {
    console.log('error');
  }
};

In my component

 const { isLoading, refetch: getDataFn } = useGetData(
    id,
    onSuccessFn
  );

I have a button with a onClick handler that executes getDataFn.

In a page, I have a list of elements. I map that list and, for each element, I render the previous component.

The code seems to work fine but I have two question:

is this the correct way to pass a parameter via useQuery?

why even though it is "enabled: false" and no calls are made (from the network in the browser inspect no calls appear until I click the button), from the ReactQueryDevtoolsPanel I see a list of calls in stale?

Thanks!


问:
Dynamic condition formatting in excel
I'm trying to improve one of my sheets and implement some smart conditioning in it.
The sheet holds information about 3 KPIs regarding parts in a production process.
Now those KPIs are measured on a monthly basis.
If each of them is smaller than 1% for 6 consecutive months the sample size reduces to a lower sampling tier from 100% to 50%.
If such a trend is seen for the next 6 months, the sample size will reduce again to a lower tier from 50% to 25%.

There are four tiers together, with the last tier being 10%.

Now in case any of the KPIs is above 1% the sample size goes back to the previous sample tier. For example, the KPIs were under 1% for 13 months. The sample size was reduced to 25%. In the 14th month, one KPI was 2%, so the sample size must increase to the previous threshold which is 50%.

Currently, I'm using an excel file that marks in the sheet a 0 next to KPI that failed for a specific month and 1 for the ones that have passed. As the next step, those values are dropped into one cell, creating a string of 1 and 0 for each KPIs. Then I need to manually analyse each string and establish the sample size.
Please keep in mind that every month new data is added.

Added a picture and sample data:
https://docs.google.com/spreadsheets/d/1g2tMkUHb_gn4EYegr0aPp3bqr5dwYusg/edit?usp=share_link&ouid=108643160822075860310&rtpof=true&sd=true

Does anyone have an idea how this could be automated?

Title: Dynamic condition formatting in excel


问:
How can I export a default object with interfaces in it in TypeScript?
```<code>import A from './A';
import type { AProps } from './A';

import B from './B';
import type { BProps } from './B';

export default {
    A, AProps,
    B, BProps
}
</code>```

I want to export a default object with interfaces inside it.

The code above causes exception under vite because AProps and BProps variables are not defined in the output js file.

I tried another way which can solve this problem:

```<code>export A from './A';
export type { AProps } from './A';

export B from './B';
export type { BProps } from './B';
</code>```

And use import * as X from './xx'. But I prefer to use import X from './xx', which means I have to export a default value from the file.

Then I create another file with code export * as default from './xx' in it and it's working well.

My question is if I can put all the export code in a single file?

Body:
import A from './A';
import type { AProps } from './A';

import B from './B';
import type { BProps } from './B';

export default {
    A, AProps,
    B, BProps
}

I want to export a default object with interfaces inside it.

The code above causes exception under vite because AProps and BProps variables are not defined in the output js file.

I tried another way which can solve this problem:

export A from './A';
export type { AProps } from './A';

export B from './B';
export type { BProps } from './B';

And use import * as X from './xx'. But I prefer to use import X from './xx', which means I have to export a default value from the file.

Then I create another file with code export * as default from './xx' in it and it's working well.

My question is if I can put all the export code in a single file?


问:
Django Views not getting POST Data from api call
I am not using django rest frame work

but in normal views.py I have a simple views

#views.py

```<code>def api_post_operations(request):
    pdb.set_trace()
    if request.POST:
        print(request.POST["name"])
        print(request.POST["address"])

</code>```

now I call it

```<code>import requests
url = "http://localhost:8000/api_post_operations"
payload = {"name":"raj", "address": "asasass" }
rees = requests.post(url, data=payload, headers={})
</code>```

it is comming

```<code>(Pdb) request.POST
<QueryDict: {}>
</code>```

Any reason why it is comming {} balnk

```<code>request.body also comming blank
</code>```

Body:
I am not using django rest frame work

but in normal views.py I have a simple views

#views.py

def api_post_operations(request):
    pdb.set_trace()
    if request.POST:
        print(request.POST["name"])
        print(request.POST["address"])

now I call it

import requests
url = "http://localhost:8000/api_post_operations"
payload = {"name":"raj", "address": "asasass" }
rees = requests.post(url, data=payload, headers={})

it is comming

(Pdb) request.POST
<QueryDict: {}>

Any reason why it is comming {} balnk

request.body also comming blank


问:
I am unable to upload variant image to shopify using laravel
I have been trying since days but I can not. I want to upload products with multiple options/variants and its images, product images its variant & options are uploaded but variant images are not being assigned. What I have tried since. Event it does not show the error, products are uploading but not variant images

1# Using Shopify SDK

```<code>$shopify = new ShopifySDK($config);
 $products = $shopify->Product->post($product_array);
 $productVariants = $shopify->ProductVariant->post($id, $variant_array);
 $image = $shopify->Image->post($v_id, $images_array)
</code>```

2# Using

```<code>Signifly\Shopify\Shopify;
</code>```
```<code> $product = $shopify->createProduct($array);            // inserting whole product, variant, options and images at a time
</code>```

and uploading separately

```<code>$shopify->createProduct($product_array);
$shopify->createVariant($id, $variant_array);
$shopify->createProductImage($id, $images_array);
</code>```

#3 Using Rest api

```<code> $client = new Rest('mystore-6842.myshopify.com', 'shpat_*********************');
        $response = $client->get('products');
            $products_array = array(
                "product" => array(
                    "title"        => 'title of product',
                    "body_html"    => 'description',
                    "vendor"       => "vendor of product",
                    "published"    => true ,
                    "variants"     => array(
                        array(
                            "sku"     => 'sku of product',
                            "price"   => 'product price',
                            "taxable" => false,
                            "inventory_quantity"=> 'available quantity',
                        )
                    )
                )
            );

            $shop = Shopify::shop();

            $products=$shop->api()->rest('POST','admin/api/2023-01/products.json',$products_array);
</code>```

in the rest api package is unable to locate my shop.

Body:
I have been trying since days but I can not. I want to upload products with multiple options/variants and its images, product images its variant & options are uploaded but variant images are not being assigned. What I have tried since. Event it does not show the error, products are uploading but not variant images

1# Using Shopify SDK

$shopify = new ShopifySDK($config);
 $products = $shopify->Product->post($product_array);
 $productVariants = $shopify->ProductVariant->post($id, $variant_array);
 $image = $shopify->Image->post($v_id, $images_array)

2# Using

Signifly\Shopify\Shopify;

 $product = $shopify->createProduct($array);            // inserting whole product, variant, options and images at a time

and uploading separately

$shopify->createProduct($product_array);
$shopify->createVariant($id, $variant_array);
$shopify->createProductImage($id, $images_array);

#3 Using Rest api

 $client = new Rest('mystore-6842.myshopify.com', 'shpat_*********************');
        $response = $client->get('products');
            $products_array = array(
                "product" => array(
                    "title"        => 'title of product',
                    "body_html"    => 'description',
                    "vendor"       => "vendor of product",
                    "published"    => true ,
                    "variants"     => array(
                        array(
                            "sku"     => 'sku of product',
                            "price"   => 'product price',
                            "taxable" => false,
                            "inventory_quantity"=> 'available quantity',
                        )
                    )
                )
            );

            $shop = Shopify::shop();

            $products=$shop->api()->rest('POST','admin/api/2023-01/products.json',$products_array);

in the rest api package is unable to locate my shop.


问:
Isabelle verbose evaluation steps
Is there some way to see what the value command does under the hood?
Maybe there exists something like using [[simp_trace]] but for value

```<code>value  using [[simp_trace]] "2+4::nat"
</code>```

Title: Isabelle verbose evaluation steps

Body:
Is there some way to see what the value command does under the hood?
Maybe there exists something like using [[simp_trace]] but for value

value  using [[simp_trace]] "2+4::nat"


问:
Is it possible to select multiple lines of codes in Jupyter notebook and convert them all to Markdown?
Is it possible to select multiple lines in Jupyter notebook and convert them all to Markdown? I know how to convert one cell individually, but converting them in a batch would save time.</p>


问:
Jest with react component gives Element type is invalid: expected a string
Source:
`
import React, { Component } from 'react';
import { Row, Col } from 'reactstrap';
import { connect } from 'react-redux';

```<code>class Test extends Component {

    constructor(props) {
        super(props);
    }

    componentWillReceiveProps(np) {
    }

    componentDidMount() {
    }

    render() {
        return (
        <>
            <Row md="12">
            </Row>
        </>
        )
    }

}

function mapStateToProps(store) {
    return {
        currentUser: store.auth.currentUser,
    }
}

export default connect(mapStateToProps)(Test);`
</code>```

Test:

```<code>`
import React from "react";
import { Provider } from "react-redux";
import { Row, Col } from 'reactstrap';
import renderer from 'react-test-renderer';
import configureMockStore from "redux-mock-store";
import { shallow, mount, render } from 'enzyme';
//import Adapter from 'enzyme-adapter-react-16';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import { configure } from 'enzyme';

configure({ adapter: new Adapter() });

const mockStore = configureMockStore();
const store = mockStore({
    auth: { currentUser: {} }
});
import Test from './Test';

it("Test",() => {
    render(
        <Test store={store}/>
    )
});`
</code>```

I get the following output:
FAIL  src/sportsbiz/assetroi/tv_value/Test.test.js
✕ Test (40ms)

● Test

```<code>Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

  18 |
  19 | it("Test",() => {
> 20 |     render(
     |           ^
  21 |         <Test store={store}/>
  22 |     )
  23 | });
</code>```

What am I doing wrong?

If I comment out  it works of course. I cant change the import because its not exported that way in reactstrap

Body:
Source:
`
import React, { Component } from 'react';
import { Row, Col } from 'reactstrap';
import { connect } from 'react-redux';

class Test extends Component {

    constructor(props) {
        super(props);
    }

    componentWillReceiveProps(np) {
    }

    componentDidMount() {
    }

    render() {
        return (
        <>
            <Row md="12">
            </Row>
        </>
        )
    }

}

function mapStateToProps(store) {
    return {
        currentUser: store.auth.currentUser,
    }
}

export default connect(mapStateToProps)(Test);`

Test:

`
import React from "react";
import { Provider } from "react-redux";
import { Row, Col } from 'reactstrap';
import renderer from 'react-test-renderer';
import configureMockStore from "redux-mock-store";
import { shallow, mount, render } from 'enzyme';
//import Adapter from 'enzyme-adapter-react-16';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import { configure } from 'enzyme';

configure({ adapter: new Adapter() });

const mockStore = configureMockStore();
const store = mockStore({
    auth: { currentUser: {} }
});
import Test from './Test';

it("Test",() => {
    render(
        <Test store={store}/>
    )
});`

I get the following output:
FAIL  src/sportsbiz/assetroi/tv_value/Test.test.js
✕ Test (40ms)

● Test

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

  18 |
  19 | it("Test",() => {
> 20 |     render(
     |           ^
  21 |         <Test store={store}/>
  22 |     )
  23 | });

What am I doing wrong?

If I comment out  it works of course. I cant change the import because its not exported that way in reactstrap


问:
I cant add the billing and shipping addresses in my account in woocommerce
I cant add or edit the billing and shipping addresses in my account in woocommerce.

I've deleted the wp rocket cache but it didnt work. And I removed the country from address. Non of these solutions seems working. What should I do?

This is my woocomerce form-edit-address php

```<code> defined( 'ABSPATH' ) || exit;

$page_title = ( 'billing' === $load_address ) ? esc_html__( 'Billing address', 'woocommerce' ) : esc_html__( 'Shipping address', 'woocommerce' );

do_action( 'woocommerce_before_edit_account_address_form' ); ?>

<?php if ( ! $load_address ) : ?>
    <?php wc_get_template( 'myaccount/my-address.php' ); ?>
<?php else : ?>

    <form method="post">

        <h3><?php echo apply_filters( 'woocommerce_my_account_edit_address_title', $page_title, $load_address ); ?></h3><?php // @codingStandardsIgnoreLine ?>

        <div class="woocommerce-address-fields">
            <?php do_action( "woocommerce_before_edit_address_form_{$load_address}" ); ?>

            <div class="woocommerce-address-fields__field-wrapper">
                <?php
                foreach ( $address as $key => $field ) {
                    woocommerce_form_field( $key, $field, wc_get_post_data_by_key( $key, $field['value'] ) );
                }
                ?>
            </div>

            <?php do_action( "woocommerce_after_edit_address_form_{$load_address}" ); ?>

            <p>
                <button type="submit" class="button" name="save_address" value="<?php esc_attr_e( 'Save address', 'woocommerce' ); ?>"><?php esc_html_e( 'Save address', 'woocommerce' ); ?></button>
                <?php wp_nonce_field( 'woocommerce-edit_address', 'woocommerce-edit-address-nonce' ); ?>
                <input type="hidden" name="action" value="edit_address" />
            </p>
        </div>

    </form>

<?php endif; ?>

<?php do_action( 'woocommerce_after_edit_account_address_form' ); ?>
</code>```

I've deleted the wp rocket cache but it didnt work. And I removed the country from address. Non of these solutions seems working. What should I do?

Body:
I cant add or edit the billing and shipping addresses in my account in woocommerce.

I've deleted the wp rocket cache but it didnt work. And I removed the country from address. Non of these solutions seems working. What should I do?

This is my woocomerce form-edit-address php

 defined( 'ABSPATH' ) || exit;

$page_title = ( 'billing' === $load_address ) ? esc_html__( 'Billing address', 'woocommerce' ) : esc_html__( 'Shipping address', 'woocommerce' );

do_action( 'woocommerce_before_edit_account_address_form' ); ?>

<?php if ( ! $load_address ) : ?>
    <?php wc_get_template( 'myaccount/my-address.php' ); ?>
<?php else : ?>

    <form method="post">

<?php echo apply_filters( 'woocommerce_my_account_edit_address_title', $page_title, $load_address ); ?>
<?php // @codingStandardsIgnoreLine ?>

            <?php do_action( "woocommerce_before_edit_address_form_{$load_address}" ); ?>

                <?php
                foreach ( $address as $key => $field ) {
                    woocommerce_form_field( $key, $field, wc_get_post_data_by_key( $key, $field['value'] ) );
                }
                ?>

            <?php do_action( "woocommerce_after_edit_address_form_{$load_address}" ); ?>

                <button type="submit" class="button" name="save_address" value="<?php esc_attr_e( 'Save address', 'woocommerce' ); ?>"><?php esc_html_e( 'Save address', 'woocommerce' ); ?></button>
                <?php wp_nonce_field( 'woocommerce-edit_address', 'woocommerce-edit-address-nonce' ); ?>
                <input type="hidden" name="action" value="edit_address" />

    </form>

<?php endif; ?>

<?php do_action( 'woocommerce_after_edit_account_address_form' ); ?>

I've deleted the wp rocket cache but it didnt work. And I removed the country from address. Non of these solutions seems working. What should I do?


问:
Fix Duplicate class in Android Studio Gradle dependency
I upgraded Android studio and gradle to the latest version and also updated all project dependencies to the latest verison. Today, I discovered an error that 2 dupclicate classes exist in gradle dependencies.

I got this error:

```<code>Duplicate class androidx.lifecycle.ViewModelLazy found in modules jetified-lifecycle-viewmodel-ktx-2.3.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1) and lifecycle-viewmodel-2.5.1-runtime (androidx.lifecycle:lifecycle-viewmodel:2.5.1)

Duplicate class androidx.lifecycle.ViewTreeViewModelKt found in modules jetified-lifecycle-viewmodel-ktx-2.3.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1) and lifecycle-viewmodel-2.5.1-runtime (androidx.lifecycle:lifecycle-viewmodel:2.5.1)
</code>```

I tried to fix the error as suggested on the Android developer's official webiste, but can't seem to fix the error. The fix at here didn't work

I also tried some stackoverflow answers but it didn't fix it for me, some didn't suite my case.

This is my grade file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 33
    buildToolsVersion "31.0.0"
    defaultConfig {
        applicationId "com.astrro.timely"
        minSdkVersion 16
        targetSdkVersion 33
        multiDexEnabled true
        versionCode 5
        versionName "1.3.0"
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
        vectorDrawables.useSupportLibrary = true

    }

    buildTypes {
        release {
            minifyEnabled false
            shrinkResources false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }

    }

    // changing the default apk build name from app-debug to proper name
    applicationVariants.all {
        variant ->
            variant.outputs.each {
                output ->
                    output.outputFileName = "TimeLY_v${variant.versionName}.apk"
            }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

     dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
        implementation 'org.jetbrains:annotations:15.0'
        implementation 'androidx.appcompat:appcompat:1.5.1'
        implementation 'androidx.appcompat:appcompat-resources:1.5.1'
        implementation 'com.google.android.material:material:1.7.0'
        implementation 'com.squareup.picasso:picasso:2.71828'
        implementation 'androidx.fragment:fragment:1.5.5'
        implementation 'androidx.recyclerview:recyclerview:1.2.1'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
        implementation 'androidx.preference:preference:1.2.0'
        implementation "androidx.multidex:multidex:2.0.1"
        implementation 'androidx.viewpager2:viewpager2:1.0.0'
        implementation 'com.google.code.gson:gson:2.8.8'

        implementation 'com.kevalpatel2106:ringtonepicker:1.2'
        implementation 'net.cachapa.expandablelayout:expandablelayout:2.9.2'
        implementation 'org.greenrobot:eventbus:3.2.0'
        implementation 'com.github.chrisbanes:PhotoView:2.0.0'
        implementation 'com.airbnb.android:lottie:3.7.0'
        implementation 'com.github.javiersantos:AppUpdater:2.7'
        implementation 'me.zhanghai.android.materialprogressbar:library:1.1.6'

        implementation ('com.wdullaer:materialdatetimepicker:4.2.3') {
            exclude group: 'androidx.appcompat'
            exclude group: 'androidx.recyclerview'
        }

        // debugImplementation because all these dependencies should only run in debug builds.
        debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'
    }

}
</code>```

Body:
I upgraded Android studio and gradle to the latest version and also updated all project dependencies to the latest verison. Today, I discovered an error that 2 dupclicate classes exist in gradle dependencies.

I got this error:

Duplicate class androidx.lifecycle.ViewModelLazy found in modules jetified-lifecycle-viewmodel-ktx-2.3.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1) and lifecycle-viewmodel-2.5.1-runtime (androidx.lifecycle:lifecycle-viewmodel:2.5.1)

Duplicate class androidx.lifecycle.ViewTreeViewModelKt found in modules jetified-lifecycle-viewmodel-ktx-2.3.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1) and lifecycle-viewmodel-2.5.1-runtime (androidx.lifecycle:lifecycle-viewmodel:2.5.1)

I tried to fix the error as suggested on the Android developer's official webiste, but can't seem to fix the error. The fix at here didn't work

I also tried some stackoverflow answers but it didn't fix it for me, some didn't suite my case.

This is my grade file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 33
    buildToolsVersion "31.0.0"
    defaultConfig {
        applicationId "com.astrro.timely"
        minSdkVersion 16
        targetSdkVersion 33
        multiDexEnabled true
        versionCode 5
        versionName "1.3.0"
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
        vectorDrawables.useSupportLibrary = true

    }

    buildTypes {
        release {
            minifyEnabled false
            shrinkResources false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }

    }

    // changing the default apk build name from app-debug to proper name
    applicationVariants.all {
        variant ->
            variant.outputs.each {
                output ->
                    output.outputFileName = "TimeLY_v${variant.versionName}.apk"
            }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

     dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
        implementation 'org.jetbrains:annotations:15.0'
        implementation 'androidx.appcompat:appcompat:1.5.1'
        implementation 'androidx.appcompat:appcompat-resources:1.5.1'
        implementation 'com.google.android.material:material:1.7.0'
        implementation 'com.squareup.picasso:picasso:2.71828'
        implementation 'androidx.fragment:fragment:1.5.5'
        implementation 'androidx.recyclerview:recyclerview:1.2.1'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
        implementation 'androidx.preference:preference:1.2.0'
        implementation "androidx.multidex:multidex:2.0.1"
        implementation 'androidx.viewpager2:viewpager2:1.0.0'
        implementation 'com.google.code.gson:gson:2.8.8'

        implementation 'com.kevalpatel2106:ringtonepicker:1.2'
        implementation 'net.cachapa.expandablelayout:expandablelayout:2.9.2'
        implementation 'org.greenrobot:eventbus:3.2.0'
        implementation 'com.github.chrisbanes:PhotoView:2.0.0'
        implementation 'com.airbnb.android:lottie:3.7.0'
        implementation 'com.github.javiersantos:AppUpdater:2.7'
        implementation 'me.zhanghai.android.materialprogressbar:library:1.1.6'

        implementation ('com.wdullaer:materialdatetimepicker:4.2.3') {
            exclude group: 'androidx.appcompat'
            exclude group: 'androidx.recyclerview'
        }

        // debugImplementation because all these dependencies should only run in debug builds.
        debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'
    }

}


问:
Why do Android 13 NFC readers no long recognize credit cards?
My NFC reader app (as well as several downloaded from Play) no longer detects credit cards on devices running Android 13 (Pixel 4a & Pixel 6a).  No problems on devices running Android 12 (eg, Pixel 3a).  My app recognizes ndef, isodep, mifare,nfc[abv].

On Android 13, only NDEF tags trigger discovery.

Is anyone else experiencing this?


问:
Maven error stating that PKIX path building failed: unable to find the valid certificate
While i am building the code in my local, I am getting this error.

I have tried downloading the certificate from https://repo.maven.apache.org/maven2, and through cmd , i have given the command to trust the certificate but this has not solved the problem.

Non-resolvable import POM: Could not transfer artifact org.junit:junit-bom:pom:5.6.2 from/to central (https://repo.maven.apache.org/maven2): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Please help me how I can fix this issue

I have tried downloading the certificate from https://repo.maven.apache.org/maven2, and through cmd , i have given the command to trust the certificate but this has not solved the problem.


问:
PostgresSql error could not find table after trying to replace it
So i have a cleaned dataframe which i would like to upload to my sales database, the first time i did it, it worked but then i noticed that the primary key defaulted to a ranged index, whereas i have a column in my dataframe which i would like to use as the primary key

So knowing the pd.to_sql has a attribute called if_exists, i set it to replace however when i ran it and looked at my table i get the following error on postgres

The following code that i have uploading to my Database is

```<code>def upload_to_db(dataframe: pd.DataFrame, table_name: str):
    """
    Creates a SQLalchmey engine to a postgres database then uploads the dataframe

    Input: Data to be uploaded (DataFrame) (table name is currently dim_users)
    Input: Table_Name to be saved (String)
    """
    engine = create_engine('postgresql://Username:Password@localhost:5432/Sales_Data')
    dataframe.to_sql(table_name, engine, if_exists= 'replace')
    with engine.connect() as con:
        con.execute('ALTER TABLE dim_users ADD PRIMARY KEY ("user_uuid");')

pass
</code>```

One fix would be to delete the table and upload it again but in real life that would not be a option so just thinking what has gone on so i can understand it  better

Body:
So i have a cleaned dataframe which i would like to upload to my sales database, the first time i did it, it worked but then i noticed that the primary key defaulted to a ranged index, whereas i have a column in my dataframe which i would like to use as the primary key

So knowing the pd.to_sql has a attribute called if_exists, i set it to replace however when i ran it and looked at my table i get the following error on postgres

The following code that i have uploading to my Database is

def upload_to_db(dataframe: pd.DataFrame, table_name: str):
    """
    Creates a SQLalchmey engine to a postgres database then uploads the dataframe

    Input: Data to be uploaded (DataFrame) (table name is currently dim_users)
    Input: Table_Name to be saved (String)
    """
    engine = create_engine('postgresql://Username:Password@localhost:5432/Sales_Data')
    dataframe.to_sql(table_name, engine, if_exists= 'replace')
    with engine.connect() as con:
        con.execute('ALTER TABLE dim_users ADD PRIMARY KEY ("user_uuid");')

pass

One fix would be to delete the table and upload it again but in real life that would not be a option so just thinking what has gone on so i can understand it  better


问:
python lxml in docker: "Document is empty" while parsing
Why this code is working without issues on my mac with any version of python, requests and lxml, but doesn't work in any docker container? i tried everything(

it just fails on 34533 line (discovered by printing el.sourceline)

```<code>from requests import get
from lxml import etree

r = get('https://printbar.ru/synsfiles/yandex/market/idrr_full.xml')
with open('test.xml', 'wb') as f:
    f.write(r.content)

tree = etree.iterparse(source='test.xml', events=('end',))
for (ev, el) in tree:
    continue

print('ok')
</code>```

https://printbar.ru/synsfiles/yandex/market/idrr_full.xml seems completely valid and works locally on any of my macs...

i tried ubuntu, alpine, several python containers even with prebuilt lxml, nothing helped. I expected that parsing this file won't throw this error in the middle of parsing:

```<code>Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "src/lxml/iterparse.pxi", line 210, in lxml.etree.iterparse.__next__
  File "src/lxml/iterparse.pxi", line 195, in lxml.etree.iterparse.__next__
  File "src/lxml/iterparse.pxi", line 230, in lxml.etree.iterparse._read_more_events
  File "src/lxml/parser.pxi", line 1376, in lxml.etree._FeedParser.feed
  File "src/lxml/parser.pxi", line 606, in lxml.etree._ParserContext._handleParseResult
  File "src/lxml/parser.pxi", line 615, in lxml.etree._ParserContext._handleParseResultDoc
  File "src/lxml/parser.pxi", line 725, in lxml.etree._handleParseResult
  File "src/lxml/parser.pxi", line 654, in lxml.etree._raiseParseError
  File "test.xml", line 1
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1
</code>```

xmllint says that there is encoding error, but it works locally on mac...) HOW?) i want it dockerized!)

Body:
Why this code is working without issues on my mac with any version of python, requests and lxml, but doesn't work in any docker container? i tried everything(

it just fails on 34533 line (discovered by printing el.sourceline)

from requests import get
from lxml import etree

r = get('https://printbar.ru/synsfiles/yandex/market/idrr_full.xml')
with open('test.xml', 'wb') as f:
    f.write(r.content)

tree = etree.iterparse(source='test.xml', events=('end',))
for (ev, el) in tree:
    continue

print('ok')

https://printbar.ru/synsfiles/yandex/market/idrr_full.xml seems completely valid and works locally on any of my macs...

i tried ubuntu, alpine, several python containers even with prebuilt lxml, nothing helped. I expected that parsing this file won't throw this error in the middle of parsing:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "src/lxml/iterparse.pxi", line 210, in lxml.etree.iterparse.__next__
  File "src/lxml/iterparse.pxi", line 195, in lxml.etree.iterparse.__next__
  File "src/lxml/iterparse.pxi", line 230, in lxml.etree.iterparse._read_more_events
  File "src/lxml/parser.pxi", line 1376, in lxml.etree._FeedParser.feed
  File "src/lxml/parser.pxi", line 606, in lxml.etree._ParserContext._handleParseResult
  File "src/lxml/parser.pxi", line 615, in lxml.etree._ParserContext._handleParseResultDoc
  File "src/lxml/parser.pxi", line 725, in lxml.etree._handleParseResult
  File "src/lxml/parser.pxi", line 654, in lxml.etree._raiseParseError
  File "test.xml", line 1
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1

xmllint says that there is encoding error, but it works locally on mac...) HOW?) i want it dockerized!)


问:
Needs clarification about Nmap and OpenSSL results
I have configured the below cipher list in Apache's ssl.conf file. And my application is running on RHEL 8.5 OS with OpenSSL version 1.1.1k.

```<code>SSLCipherSuite ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES256-CCM:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305
</code>```

I'm running the below Nmap command to test the strength of the cipher suites which I used in my application,

nmap -sV --script ssl-enum-ciphers -p 8443 <IP_ADDRESS>

Please find the below output snippet.

```<code> TLSv1.2:
|     ciphers:
|       TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
|     compressors:
|       NULL
|     cipher preference: client
|_  least strength: A
</code>```

And I knew that the certificates which I used in the application are signed with RSA. so it displays the ciphers which are having RSA authentication.

Also, When I try to execute the below command, I got "error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:ssl/record/rec_layer_s3.c:1544:SSL alert number 40" error.

openssl s_client -connect XX.XX.XX.XX:8443 -cipher ECDHE-RSA-CHACHA20-POLY1305

My queries,

Why "ECDHE-RSA-CHACHA20-POLY1305 and DHE-RSA-AES256-CCM" are not displayed by Nmap command even though they have RSA authentication?

Why the handshake failure happened with that cipher?

Thanks.

Body:
I have configured the below cipher list in Apache's ssl.conf file. And my application is running on RHEL 8.5 OS with OpenSSL version 1.1.1k.

SSLCipherSuite ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES256-CCM:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305

I'm running the below Nmap command to test the strength of the cipher suites which I used in my application,

nmap -sV --script ssl-enum-ciphers -p 8443 <IP_ADDRESS>

Please find the below output snippet.

 TLSv1.2:
|     ciphers:
|       TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
|     compressors:
|       NULL
|     cipher preference: client
|_  least strength: A

And I knew that the certificates which I used in the application are signed with RSA. so it displays the ciphers which are having RSA authentication.

Also, When I try to execute the below command, I got "error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:ssl/record/rec_layer_s3.c:1544:SSL alert number 40" error.

openssl s_client -connect XX.XX.XX.XX:8443 -cipher ECDHE-RSA-CHACHA20-POLY1305

My queries,

Why "ECDHE-RSA-CHACHA20-POLY1305 and DHE-RSA-AES256-CCM" are not displayed by Nmap command even though they have RSA authentication?

Why the handshake failure happened with that cipher?

Thanks.


问:
Error When trying to get a Sharepoint folder - DataSource.Error: SharePoint: Request failed
This is the error message:

DataSource.Error: SharePoint: Request failed: The remote server returned an error: (500) Internal Server Error.  (An error occurred while processing this request.)

I'm trying to get a sharepoint folder through this function called Sharepoint - >

```<code>(inputPath as text) =>
let
    myFolderPath=if Text.EndsWith(Text.Replace(inputPath,"\","/"),"/") then Text.Range(Text.Replace(inputPath,"\","/"),0,Text.Length(Text.Replace(inputPath,"\","/"))-1) else Text.Replace(inputPath,"\","/"),
    definePaths = [root=Text.BeforeDelimiter(myFolderPath,"/sites/")& "/sites/" & Text.BetweenDelimiters(myFolderPath,"/sites/","/") & "/", path=Text.AfterDelimiter(myFolderPath,root), pathList=Text.Split(path,"/")],
    sharepointRoot  = SharePoint.Contents("https://***.sharepoint.com/sites/***", [ApiVersion = 15]),
    goToFolder = (inputTable, pathList)=> if List.Count(pathList)=0 then inputTable else @goToFolder(inputTable{[Name=pathList{0}]}[Content],List.RemoveFirstN(pathList,1)),
    folder = goToFolder(sharepointRoot,definePaths[pathList])
in
    folder
</code>```

This function was working fine, but today it stopped.

I've changed sensitive diretory to "***".

The input is the link to the sharepoint folder.

Someone knows what's wrong?

Best Regards!

Body:
This is the error message:

DataSource.Error: SharePoint: Request failed: The remote server returned an error: (500) Internal Server Error.  (An error occurred while processing this request.)

I'm trying to get a sharepoint folder through this function called Sharepoint - >

(inputPath as text) =>
let
    myFolderPath=if Text.EndsWith(Text.Replace(inputPath,"\","/"),"/") then Text.Range(Text.Replace(inputPath,"\","/"),0,Text.Length(Text.Replace(inputPath,"\","/"))-1) else Text.Replace(inputPath,"\","/"),
    definePaths = [root=Text.BeforeDelimiter(myFolderPath,"/sites/")& "/sites/" & Text.BetweenDelimiters(myFolderPath,"/sites/","/") & "/", path=Text.AfterDelimiter(myFolderPath,root), pathList=Text.Split(path,"/")],
    sharepointRoot  = SharePoint.Contents("https://***.sharepoint.com/sites/***", [ApiVersion = 15]),
    goToFolder = (inputTable, pathList)=> if List.Count(pathList)=0 then inputTable else @goToFolder(inputTable{[Name=pathList{0}]}[Content],List.RemoveFirstN(pathList,1)),
    folder = goToFolder(sharepointRoot,definePaths[pathList])
in
    folder

This function was working fine, but today it stopped.

I've changed sensitive diretory to "***".

The input is the link to the sharepoint folder.

Someone knows what's wrong?

Best Regards!


问:
Speech Recognizer and/or Recognition Listener doesn't seem to work even though permission have been allowed and app is running with no errors
Speech Recognition Listner and Recognition Intent doesn't seem to be called or initiated at all even though method startListening() and stopListening() are called and RECORD_AUDIO permission was allowed. The code below is where I am utilizing them in the showDialog() method which is been called in a on click listener in the onCreate() part of the class.

```<code>    private void speakWithVoiceDialog(String shoppingListUserItemName) {
        System.out.println("ACCESSED");
        androidx.appcompat.app.AlertDialog.Builder builder =
                new androidx.appcompat.app.AlertDialog.Builder
                        (ShoppingListUserItemsActivity.this, R.style.AlertDialogCustom);
        View view = LayoutInflater.from(ShoppingListUserItemsActivity.this).inflate(
                R.layout.voice_input_dialog,
                (ConstraintLayout) findViewById(R.id.layoutDialogContainerVID)
        );
        builder.setView(view);
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
            System.out.println("ACCESS DENIED");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);

        }
            Button cancel_button = view.findViewById(R.id.cancel_button);
            Button enter_button = view.findViewById(R.id.enterButton);
            EditText quantityEditText = view.findViewById(R.id.quantity_edit_text);
            EditText unitPriceEditText = view.findViewById(R.id.unit_price_edit_text);
            ImageView quantityMicrophone = view.findViewById(R.id.quantity_microphone);
            ImageView unitPriceMicrophone = view.findViewById(R.id.unit_price_microphone);
            final androidx.appcompat.app.AlertDialog alertDialog = builder.create();
            cancel_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                }
            });
            enter_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    QueryUtils.saveDetailsOfShoppingListUserItem(shoppingListUserItemName, EnglishWordsToNumbers.replaceNumbers(String.valueOf(quantityEditText.getText())), unitPriceEditText.getText());

                }
            });
            SpeechRecognizer quantitySpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
            SpeechRecognizer unitPriceSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
            final Intent quantitySpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            quantitySpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            quantitySpeechRecognizerIntent .putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
            final Intent unitPriceRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            // when the users click on the textviews next to the edit texts for hold details, listening starts
            RecognitionListener quantityRecognitionListener = new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle bundle) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float v) {

            }

            @Override
            public void onBufferReceived(byte[] bytes) {

            }

            @Override
            public void onEndOfSpeech() {
                System.out.println("@onEndOfSpeech - quantity");

            }

            @Override
            public void onError(int i) {

            }

            @Override
            public void onResults(Bundle bundle) {
                System.out.println("@onResults - quantity");
                ArrayList<String> data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                quantityEditText.setText(EnglishWordsToNumbers.replaceNumbers(data.get(0)));
            }

            @Override
            public void onPartialResults(Bundle bundle) {
                System.out.println("@onPartialResults - quantity");
                ArrayList<String> data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                quantityEditText.setText(EnglishWordsToNumbers.replaceNumbers(data.get(0)));

            }

            @Override
            public void onEvent(int i, Bundle bundle) {

            }
        };
            quantitySpeechRecognizer.setRecognitionListener(quantityRecognitionListener);
            quantityMicrophone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                        if(quantityMicrophoneState == 0){
                            quantityMicrophone.setColorFilter(ContextCompat.getColor(ShoppingListUserItemsActivity.this, R.color.green), android.graphics.PorterDuff.Mode.SRC_IN);
                            quantitySpeechRecognizer.startListening(quantitySpeechRecognizerIntent);
                            quantityMicrophoneState = 1;
                        }
                        else if(quantityMicrophoneState == 1){
                            quantityMicrophone.setColorFilter(ContextCompat.getColor(ShoppingListUserItemsActivity.this, R.color.grey), android.graphics.PorterDuff.Mode.SRC_IN);
                            quantitySpeechRecognizer.stopListening();
                            quantityMicrophoneState = 0;

                        }
                }
            });

            RecognitionListener unitPriceRecognitionListener = new RecognitionListener() {
                @Override
                public void onReadyForSpeech(Bundle bundle) {

                }

                @Override
                public void onBeginningOfSpeech() {

                }

                @Override
                public void onRmsChanged(float v) {

                }

                @Override
                public void onBufferReceived(byte[] bytes) {

                }

                @Override
                public void onEndOfSpeech() {

                }

                @Override
                public void onError(int i) {

                }

                @Override
                public void onResults(Bundle bundle) {
                    ArrayList<String> data = bundle.getStringArrayList(unitPriceSpeechRecognizer.RESULTS_RECOGNITION);
                    unitPriceEditText.setText(EnglishWordsToNumbers.replaceNumbers(data.get(0)));

                }

                @Override
                public void onPartialResults(Bundle bundle) {
                    ArrayList<String> data = bundle.getStringArrayList(unitPriceSpeechRecognizer.RESULTS_RECOGNITION);
                    unitPriceEditText.setText(EnglishWordsToNumbers.replaceNumbers(data.get(0)));

                }

                @Override
                public void onEvent(int i, Bundle bundle) {

                }
            };
            unitPriceSpeechRecognizer.setRecognitionListener(unitPriceRecognitionListener);

            unitPriceMicrophone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(unitPriceMicrophoneState == 0){
                        unitPriceMicrophone.setColorFilter(ContextCompat.getColor(ShoppingListUserItemsActivity.this, R.color.green), android.graphics.PorterDuff.Mode.SRC_IN);
                        unitPriceSpeechRecognizer.startListening(unitPriceRecognizerIntent);
                        unitPriceMicrophoneState = 1;
                    }
                    else if(unitPriceMicrophoneState == 1){
                        unitPriceMicrophone.setColorFilter(ContextCompat.getColor(ShoppingListUserItemsActivity.this, R.color.grey), android.graphics.PorterDuff.Mode.SRC_IN);
                        unitPriceSpeechRecognizer.stopListening();
                        unitPriceMicrophoneState = 0;

                    }

                }
            });

        if (alertDialog.getWindow() != null) {
            alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        }
        alertDialog.show();
    }

</code>```

where I'm calling it

```<code>                microphoneButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            showDialog(getString(R.string.delete_shopping_list_item), shoppingListUserItemName, shoppingListName, JSONEditCodes.DELETE_SHOPPING_LIST_ITEM);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                });
</code>```

and this onClickListener is under a onItemClickListener of a ListView.

I've tried initiating a new Recognition Listener instead of the variables holding the Recognition Listener's for the quantityRecognitionListener and unitPriceRecognitionListener that are set on the respective speech recognizers and both ways it hasn't worked. The android permission is being initiated when denied and granted through the pop-up on my android device, yet I don't even see any methods under the recognition listener occuring(e.g. onPartialResults()).
If needed I can put the code of the whole class. Any ideas/reasons on why its not working?

Body:
Speech Recognition Listner and Recognition Intent doesn't seem to be called or initiated at all even though method startListening() and stopListening() are called and RECORD_AUDIO permission was allowed. The code below is where I am utilizing them in the showDialog() method which is been called in a on click listener in the onCreate() part of the class.

    private void speakWithVoiceDialog(String shoppingListUserItemName) {
        System.out.println("ACCESSED");
        androidx.appcompat.app.AlertDialog.Builder builder =
                new androidx.appcompat.app.AlertDialog.Builder
                        (ShoppingListUserItemsActivity.this, R.style.AlertDialogCustom);
        View view = LayoutInflater.from(ShoppingListUserItemsActivity.this).inflate(
                R.layout.voice_input_dialog,
                (ConstraintLayout) findViewById(R.id.layoutDialogContainerVID)
        );
        builder.setView(view);
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
            System.out.println("ACCESS DENIED");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);

        }
            Button cancel_button = view.findViewById(R.id.cancel_button);
            Button enter_button = view.findViewById(R.id.enterButton);
            EditText quantityEditText = view.findViewById(R.id.quantity_edit_text);
            EditText unitPriceEditText = view.findViewById(R.id.unit_price_edit_text);
            ImageView quantityMicrophone = view.findViewById(R.id.quantity_microphone);
            ImageView unitPriceMicrophone = view.findViewById(R.id.unit_price_microphone);
            final androidx.appcompat.app.AlertDialog alertDialog = builder.create();
            cancel_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                }
            });
            enter_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    QueryUtils.saveDetailsOfShoppingListUserItem(shoppingListUserItemName, EnglishWordsToNumbers.replaceNumbers(String.valueOf(quantityEditText.getText())), unitPriceEditText.getText());

                }
            });
            SpeechRecognizer quantitySpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
            SpeechRecognizer unitPriceSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
            final Intent quantitySpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            quantitySpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            quantitySpeechRecognizerIntent .putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
            final Intent unitPriceRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            // when the users click on the textviews next to the edit texts for hold details, listening starts
            RecognitionListener quantityRecognitionListener = new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle bundle) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float v) {

            }

            @Override
            public void onBufferReceived(byte[] bytes) {

            }

            @Override
            public void onEndOfSpeech() {
                System.out.println("@onEndOfSpeech - quantity");

            }

            @Override
            public void onError(int i) {

            }

            @Override
            public void onResults(Bundle bundle) {
                System.out.println("@onResults - quantity");
                ArrayList<String> data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                quantityEditText.setText(EnglishWordsToNumbers.replaceNumbers(data.get(0)));
            }

            @Override
            public void onPartialResults(Bundle bundle) {
                System.out.println("@onPartialResults - quantity");
                ArrayList<String> data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                quantityEditText.setText(EnglishWordsToNumbers.replaceNumbers(data.get(0)));

            }

            @Override
            public void onEvent(int i, Bundle bundle) {

            }
        };
            quantitySpeechRecognizer.setRecognitionListener(quantityRecognitionListener);
            quantityMicrophone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                        if(quantityMicrophoneState == 0){
                            quantityMicrophone.setColorFilter(ContextCompat.getColor(ShoppingListUserItemsActivity.this, R.color.green), android.graphics.PorterDuff.Mode.SRC_IN);
                            quantitySpeechRecognizer.startListening(quantitySpeechRecognizerIntent);
                            quantityMicrophoneState = 1;
                        }
                        else if(quantityMicrophoneState == 1){
                            quantityMicrophone.setColorFilter(ContextCompat.getColor(ShoppingListUserItemsActivity.this, R.color.grey), android.graphics.PorterDuff.Mode.SRC_IN);
                            quantitySpeechRecognizer.stopListening();
                            quantityMicrophoneState = 0;

                        }
                }
            });

            RecognitionListener unitPriceRecognitionListener = new RecognitionListener() {
                @Override
                public void onReadyForSpeech(Bundle bundle) {

                }

                @Override
                public void onBeginningOfSpeech() {

                }

                @Override
                public void onRmsChanged(float v) {

                }

                @Override
                public void onBufferReceived(byte[] bytes) {

                }

                @Override
                public void onEndOfSpeech() {

                }

                @Override
                public void onError(int i) {

                }

                @Override
                public void onResults(Bundle bundle) {
                    ArrayList<String> data = bundle.getStringArrayList(unitPriceSpeechRecognizer.RESULTS_RECOGNITION);
                    unitPriceEditText.setText(EnglishWordsToNumbers.replaceNumbers(data.get(0)));

                }

                @Override
                public void onPartialResults(Bundle bundle) {
                    ArrayList<String> data = bundle.getStringArrayList(unitPriceSpeechRecognizer.RESULTS_RECOGNITION);
                    unitPriceEditText.setText(EnglishWordsToNumbers.replaceNumbers(data.get(0)));

                }

                @Override
                public void onEvent(int i, Bundle bundle) {

                }
            };
            unitPriceSpeechRecognizer.setRecognitionListener(unitPriceRecognitionListener);

            unitPriceMicrophone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(unitPriceMicrophoneState == 0){
                        unitPriceMicrophone.setColorFilter(ContextCompat.getColor(ShoppingListUserItemsActivity.this, R.color.green), android.graphics.PorterDuff.Mode.SRC_IN);
                        unitPriceSpeechRecognizer.startListening(unitPriceRecognizerIntent);
                        unitPriceMicrophoneState = 1;
                    }
                    else if(unitPriceMicrophoneState == 1){
                        unitPriceMicrophone.setColorFilter(ContextCompat.getColor(ShoppingListUserItemsActivity.this, R.color.grey), android.graphics.PorterDuff.Mode.SRC_IN);
                        unitPriceSpeechRecognizer.stopListening();
                        unitPriceMicrophoneState = 0;

                    }

                }
            });

        if (alertDialog.getWindow() != null) {
            alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        }
        alertDialog.show();
    }

where I'm calling it

                microphoneButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            showDialog(getString(R.string.delete_shopping_list_item), shoppingListUserItemName, shoppingListName, JSONEditCodes.DELETE_SHOPPING_LIST_ITEM);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                });

and this onClickListener is under a onItemClickListener of a ListView.

I've tried initiating a new Recognition Listener instead of the variables holding the Recognition Listener's for the quantityRecognitionListener and unitPriceRecognitionListener that are set on the respective speech recognizers and both ways it hasn't worked. The android permission is being initiated when denied and granted through the pop-up on my android device, yet I don't even see any methods under the recognition listener occuring(e.g. onPartialResults()).
If needed I can put the code of the whole class. Any ideas/reasons on why its not working?


问:
AWS lambda in Java using container image failing with unable to find handlerRequest method
I have a simple lambda in Java to fetch some details from s3 bucket and the jar file works.
I have run following command to generate the Main.class file in org.example folder.
mvn compile dependency:copy-dependencies -DincludeScope=runtime
I tried to pass the jar file in the package too but that does not work either.

When I build the image and use in aws lambda it gives me error:

Printing org.example.Main::handleRequest
/entrypoint.sh: line 26: exec: org.example.Main::handleRequest: not found

There is a entrypoint.sh file which is responsible for Kerberos authentication and then just runs the CMD.

entrypoint.sh:

```<code>#!/bin/bash
set -e
    echo "### Kerberizing with the Java binary ###"
    "/apps/initialize_krb"

echo "Printing $@"
if [ -z "${AWS_LAMBDA_RUNTIME_API}" ]; then
    exec /usr/bin/aws-lambda-rie python -m awslambdaric $1
else
    exec "$@"
fi
</code>```

Dockerfile:

```<code>ARG BRANCH_VERSION=latest
FROM allimages*******-java11:${BRANCH_VERSION}

COPY ./target/classes /var/task
COPY ./target/dependency/* /var/task/lib/
COPY entrypoint.sh /var/task
RUN chmod +x /var/task/entrypoint.sh

WORKDIR /var/task
ENTRYPOINT ["/var/task/entrypoint.sh"]
CMD ["org.example.Main::handleRequest"]
</code>```

I am unable to understand what I am missing. Please help.

Body:
I have a simple lambda in Java to fetch some details from s3 bucket and the jar file works.
I have run following command to generate the Main.class file in org.example folder.
mvn compile dependency:copy-dependencies -DincludeScope=runtime
I tried to pass the jar file in the package too but that does not work either.

When I build the image and use in aws lambda it gives me error:

Printing org.example.Main::handleRequest
/entrypoint.sh: line 26: exec: org.example.Main::handleRequest: not found

There is a entrypoint.sh file which is responsible for Kerberos authentication and then just runs the CMD.

entrypoint.sh:

#!/bin/bash
set -e
    echo "### Kerberizing with the Java binary ###"
    "/apps/initialize_krb"

echo "Printing $@"
if [ -z "${AWS_LAMBDA_RUNTIME_API}" ]; then
    exec /usr/bin/aws-lambda-rie python -m awslambdaric $1
else
    exec "$@"
fi

Dockerfile:

ARG BRANCH_VERSION=latest
FROM allimages*******-java11:${BRANCH_VERSION}

COPY ./target/classes /var/task
COPY ./target/dependency/* /var/task/lib/
COPY entrypoint.sh /var/task
RUN chmod +x /var/task/entrypoint.sh

WORKDIR /var/task
ENTRYPOINT ["/var/task/entrypoint.sh"]
CMD ["org.example.Main::handleRequest"]

I am unable to understand what I am missing. Please help.


问:
Trying to calculate the total distance of a ball after falling and bouncing
The Formula that i am trying to use to calculate the total distance  of a ball after free fall from a distance D and bouncing X times is:

for example after the ball hits the ground eight times this would be the answer:

```<code>distance = 1 + 2 * (h + h^2 + ... + h^7)
</code>```

Note that in the above formula, the term h^n represents the height of the ball after the nth hit and the factor of 2 in all but the first term reflects that the ball travels both up and back down to the floor for each hit. The sum in the brackets represents the geometric series for the height of the ball.

```<code>distance = 1 + 2 * (2/3 + (2/3)^2 + (2/3)^3 + (2/3)^4 + (2/3)^5 + (2/3)^6 + (2/3)^7)

distance = 1 + 2 * (2/3 * (10423/2187)) = 1 + 2 * (6882/2187) = 10423/2187 = 4.77 m approximately
</code>```

I somehow tried to do the javascript part but somehow my script doesnt work

function totalDistance(fall, bouncing, numBounces) {
  let distance = fall;
  let h = bouncing;
  for (let i = 1; i <= numBounces - 1; i++) {
    distance += 2 * Math.pow(h, i);
  }
  return distance;
}

function calculate() {
  let fall = document.getElementById("fall").value;
  let bouncing = document.getElementById("bouncing").value;
  let numBounces = document.getElementById("numBounces").value;
  document.getElementById("result").innerHTML = "The total distance traveled after " + numBounces + " bounces is: " + totalDistance(fall, bouncing, numBounces) + " meters";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<body>

  <p>Enter the height of the fall (in meters): <input type="text" id="fall"></p>
  <p>Enter the bouncing ratio (e.g. 0.66 for 2/3): <input type="text" id="bouncing"></p>
  <p>Enter the number of bounces: <input type="text" id="numBounces"></p>
  <button onclick="calculate()">Calculate</button>
  <p id="result"></p>

</body>

</html></code>```

Body:
The Formula that i am trying to use to calculate the total distance  of a ball after free fall from a distance D and bouncing X times is:

for example after the ball hits the ground eight times this would be the answer:

distance = 1 + 2 * (h + h^2 + ... + h^7)

Note that in the above formula, the term h^n represents the height of the ball after the nth hit and the factor of 2 in all but the first term reflects that the ball travels both up and back down to the floor for each hit. The sum in the brackets represents the geometric series for the height of the ball.

distance = 1 + 2 * (2/3 + (2/3)^2 + (2/3)^3 + (2/3)^4 + (2/3)^5 + (2/3)^6 + (2/3)^7)

distance = 1 + 2 * (2/3 * (10423/2187)) = 1 + 2 * (6882/2187) = 10423/2187 = 4.77 m approximately

I somehow tried to do the javascript part but somehow my script doesnt work

function totalDistance(fall, bouncing, numBounces) {
  let distance = fall;
  let h = bouncing;
  for (let i = 1; i <= numBounces - 1; i++) {
    distance += 2 * Math.pow(h, i);
  }
  return distance;
}

function calculate() {
  let fall = document.getElementById("fall").value;
  let bouncing = document.getElementById("bouncing").value;
  let numBounces = document.getElementById("numBounces").value;
  document.getElementById("result").innerHTML = "The total distance traveled after " + numBounces + " bounces is: " + totalDistance(fall, bouncing, numBounces) + " meters";
}

<!DOCTYPE html>

Enter the height of the fall (in meters): <input type="text" id="fall">

Enter the bouncing ratio (e.g. 0.66 for 2/3): <input type="text" id="bouncing">

Enter the number of bounces: <input type="text" id="numBounces">

  <button onclick="calculate()">Calculate</button>


问:
How to send post requests to open chatbox?
So, I'm trying to open a chat box by sending POST request to the URL, but the return url is the same, what's the problem?

Here's the HTML:

```<code><button type="button" data-dismiss="modal" data-toggle="open-chatbox" data-groupid="" data-type="Question" data-targetid="53808" class="btn btn-primary px-4 font-w400">
                    <i class="far fa-comments fa-fw mr-1"></i> Quick Response
                </button>
</code>```

Here is my code

```<code>payload = {
    "groupID":"",
    "targetType":"Question",
    "targetID":"53808",
}

url2 = "Some URL"
p2 = s.post(url2, data=payload)
soup = bs4.BeautifulSoup(p2.content, 'html.parser')
</code>```

Body:
So, I'm trying to open a chat box by sending POST request to the URL, but the return url is the same, what's the problem?

Here's the HTML:

<button type="button" data-dismiss="modal" data-toggle="open-chatbox" data-groupid="" data-type="Question" data-targetid="53808" class="btn btn-primary px-4 font-w400">
                     Quick Response
                </button>

Here is my code

payload = {
    "groupID":"",
    "targetType":"Question",
    "targetID":"53808",
}

url2 = "Some URL"
p2 = s.post(url2, data=payload)
soup = bs4.BeautifulSoup(p2.content, 'html.parser')


问:
Why my docker-compose.yml file not finding the package.json file?
I am trying to dockerize my react/typecsript application, but when I try to docker-compose run frontend it does not find the package.json file. I do not have a DockerFile, only a docker-compose.yml

docker-compose.yml:

```<code>`version: '3.5'

services:
  frontend:
    image: node:latest
    volumes:
      - ./frontend:/app
    ports:
      - 3000:3000
    working_dir: /app
    command: bash -c "npm i && npm start"`
</code>```

My root folder is called FULL-STACK-CHALLENGE and structure of my folder as follow:

Project structure(https://i.stack.imgur.com/RkCbY.png)

When I try to run the docker-compose.yml file give this error:

```<code>Creating full-stack-challenge_frontend_run ... done
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /app/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/app/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2023-01-12T17_30_41_901Z-debug-0.log
ERROR: 254
</code>```

And I also want to open this application at localhost:3000

Where is the mistake I am making?

I already try to change the name of working_dir or the name of volumes and even try to create a DockerFile and nothing works

Body:
I am trying to dockerize my react/typecsript application, but when I try to docker-compose run frontend it does not find the package.json file. I do not have a DockerFile, only a docker-compose.yml

docker-compose.yml:

`version: '3.5'

services:
  frontend:
    image: node:latest
    volumes:
      - ./frontend:/app
    ports:
      - 3000:3000
    working_dir: /app
    command: bash -c "npm i && npm start"`

My root folder is called FULL-STACK-CHALLENGE and structure of my folder as follow:

Project structure(https://i.stack.imgur.com/RkCbY.png)

When I try to run the docker-compose.yml file give this error:

Creating full-stack-challenge_frontend_run ... done
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /app/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/app/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2023-01-12T17_30_41_901Z-debug-0.log
ERROR: 254

And I also want to open this application at localhost:3000

Where is the mistake I am making?

I already try to change the name of working_dir or the name of volumes and even try to create a DockerFile and nothing works


问:
Postgres SQL to execute multiple Insert/update queries at one once and clean up based on Key if required
We have 3 tables as below:

```<code>Name
Address
Telephone
</code>```

Each table has a individual Key and currently we are running multiple Insert and Update queries for each table separately based on the keys. And the columns might differ in each query.

Want to check if there is any way where we can execute all the scripts at once through any Stored Procedure or thorough any script.

Also if there is any way to clean up the records whatever we have Inserted if required.

Appreciate any help, Thanks!

Body:
We have 3 tables as below:

Name
Address
Telephone

Each table has a individual Key and currently we are running multiple Insert and Update queries for each table separately based on the keys. And the columns might differ in each query.

Want to check if there is any way where we can execute all the scripts at once through any Stored Procedure or thorough any script.

Also if there is any way to clean up the records whatever we have Inserted if required.

Appreciate any help, Thanks!


问:
NextAuth prisma 401 error on deploy but works on localhost
Im having this problem on my deployed app

```<code>error:
"\nInvalid `prisma.user.findFirst()` invocation:\n\n\nCan't reach database server at `localhost`:`5432`\n\nPlease make sure your database server is running at `localhost`:`5432`."
ok:
false
status:
401
url:
null
</code>```

but in my localhost it works perfectly

this is my code:

/pages/api/auth/[...nextauth].js

```<code>import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaClient } from "@prisma/client";
import bcryptjs from "bcryptjs";

const prisma = new PrismaClient();
export default NextAuth({
  session: {
    strategy: "jwt",
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user?.userId) {
        token.userId = user.userId;
      }
      return token;
    },
    async session({ session, token }) {
      if (token?.userId) {
        session.user.userId = token.userId;
      }
      return session;
    },
  },
  providers: [
    CredentialsProvider({
      id: "credentials",
      name: "Credentials",
      authorize: async (credentials) => {
        const user = await prisma.user.findFirst({
          where: {
            email: credentials.email,
          },
        });
        try {
          if (
            user &&
            bcryptjs.compareSync(credentials.password, user.password)
          ) {
            const userInfo = {
              userId: user.userId,
              name: user.username,
              image: user.image,
            };
            return userInfo;
          }
          throw new Error("Invalid email or password");
        } catch (err) {
          const errorMessage = err.response.data.message;
          // Redirecting to the login page with error messsage in the URL
          throw new Error(errorMessage + "&email=" + credentials.email);
        }
      },
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
});
</code>```

/login

```<code>onSubmit={async (values) => {
            await signIn("credentials", {
              redirect: false,
              email: values.email,
              password: values.password,
            })
              .then((error) => console.log(error))
              .catch((error) => console.log(error));
}

</code>```

DATABASE_URL='postgres://postgres:postgres@localhost:5432/nextauth?connect_timeout=300'
NEXTAUTH_URL=my vercel deploy url
NEXTAUTH_SECRET=secret

how can i solve this problem? i tried many things to solve this but it still not working

Body:
Im having this problem on my deployed app

error:
"\nInvalid `prisma.user.findFirst()` invocation:\n\n\nCan't reach database server at `localhost`:`5432`\n\nPlease make sure your database server is running at `localhost`:`5432`."
ok:
false
status:
401
url:
null

but in my localhost it works perfectly

this is my code:

/pages/api/auth/[...nextauth].js

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaClient } from "@prisma/client";
import bcryptjs from "bcryptjs";

const prisma = new PrismaClient();
export default NextAuth({
  session: {
    strategy: "jwt",
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user?.userId) {
        token.userId = user.userId;
      }
      return token;
    },
    async session({ session, token }) {
      if (token?.userId) {
        session.user.userId = token.userId;
      }
      return session;
    },
  },
  providers: [
    CredentialsProvider({
      id: "credentials",
      name: "Credentials",
      authorize: async (credentials) => {
        const user = await prisma.user.findFirst({
          where: {
            email: credentials.email,
          },
        });
        try {
          if (
            user &&
            bcryptjs.compareSync(credentials.password, user.password)
          ) {
            const userInfo = {
              userId: user.userId,
              name: user.username,
              image: user.image,
            };
            return userInfo;
          }
          throw new Error("Invalid email or password");
        } catch (err) {
          const errorMessage = err.response.data.message;
          // Redirecting to the login page with error messsage in the URL
          throw new Error(errorMessage + "&email=" + credentials.email);
        }
      },
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
});

/login

onSubmit={async (values) => {
            await signIn("credentials", {
              redirect: false,
              email: values.email,
              password: values.password,
            })
              .then((error) => console.log(error))
              .catch((error) => console.log(error));
}

DATABASE_URL='postgres://postgres:postgres@localhost:5432/nextauth?connect_timeout=300'
NEXTAUTH_URL=my vercel deploy url
NEXTAUTH_SECRET=secret

how can i solve this problem? i tried many things to solve this but it still not working


问:
The PowerShell script uploads all my values as 0 from an excel spreadsheet, i'm unsure why?
sorry if this is a rookie question, bit new to this... I'm trying to upload data from a .csv file to an online table using JSON.

The script below is recognised, especially the string values, but the rest of the columns appear but every value is 0. Even the 'Computer Name' section, when it should be 'Computer-01'.

I'm not entirely sure what i've done wrong, but imagine it's something syntax related. I've tried swapping out the intergers with string, but that usually causes the '0' to disappear and it's just blank.

Any direction would be appreciated!

Thank you.

```<code>#SU tile
$data = Import-Csv -Path "C:\Temp\file.csv" -Delimiter ','
$data | Select-Object @{
    Name = "Domain";
    Expression ={[string]$_.Domain}
},
@{
    Name = "Name";
    Expression ={[string]$_.Name}
},
@{
    Name = "Computer Name";
    Expression ={[int]$_.ComputerName}
},
@{
    Name = "IP Address";
    Expression ={[int]$_.IPAddress}
},
@{
    Name = "Approved Updates Installed";
    Expression ={[int]$_.ApprovedUpdatesInstalled}
},
@{
    Name = "Last Reported Status Date";
    Expression = {[LastReportedStatusDate]::ParseExact($($_.LastReportedStatusDate), 'dd/MM/yyyy',[Globalization.CultureInfo]::CreateSpecificCulture('en-GB'))}
    },
@{
    Name = "Make";
    Expression = {[String]$_.Make}
}
</code>```

I've tried swapping out the integers with string, but that usually causes the '0' to disappear and it's just blank.

I'm expecting the numbers on the spreadsheet, so 2,25,54 etc and ip addresses e.g. 123.11.23

Body:
sorry if this is a rookie question, bit new to this... I'm trying to upload data from a .csv file to an online table using JSON.

The script below is recognised, especially the string values, but the rest of the columns appear but every value is 0. Even the 'Computer Name' section, when it should be 'Computer-01'.

I'm not entirely sure what i've done wrong, but imagine it's something syntax related. I've tried swapping out the intergers with string, but that usually causes the '0' to disappear and it's just blank.

Any direction would be appreciated!

Thank you.

#SU tile
$data = Import-Csv -Path "C:\Temp\file.csv" -Delimiter ','
$data | Select-Object @{
    Name = "Domain";
    Expression ={[string]$_.Domain}
},
@{
    Name = "Name";
    Expression ={[string]$_.Name}
},
@{
    Name = "Computer Name";
    Expression ={[int]$_.ComputerName}
},
@{
    Name = "IP Address";
    Expression ={[int]$_.IPAddress}
},
@{
    Name = "Approved Updates Installed";
    Expression ={[int]$_.ApprovedUpdatesInstalled}
},
@{
    Name = "Last Reported Status Date";
    Expression = {[LastReportedStatusDate]::ParseExact($($_.LastReportedStatusDate), 'dd/MM/yyyy',[Globalization.CultureInfo]::CreateSpecificCulture('en-GB'))}
    },
@{
    Name = "Make";
    Expression = {[String]$_.Make}
}

I've tried swapping out the integers with string, but that usually causes the '0' to disappear and it's just blank.

I'm expecting the numbers on the spreadsheet, so 2,25,54 etc and ip addresses e.g. 123.11.23


问:
WordPress Media endpoint POST request by $.ajax() method saying "Sorry, you are not allowed to upload this file type."
I am trying to publish CPT (custom post type) posts from front end with ajax and Rest API. I can create post titles and content without any issues but I need help uploading featured images. I am using $.ajax() method.
Not sure in what format I should send attachment URL as 'data' value. Here I have prepared an object where I put the attachment path with a key of 'source_url'. Is this okay?

And after submit the request, I am getting this error:
"Sorry, you are not allowed to upload this file type." [Note: I have uploaded an image with .jpeg extension]

Please kindly review my code and let me know what I am missing.
Thanks a lot.

```<code>var featuredImage = {
      source_url: $(".post-thumb").val(),
    };

    // Lets make an Ajax call to add image on the media
    $.ajax({
      beforeSend: function (xhr) {
        xhr.setRequestHeader("X-WP-Nonce", sovObj.restNonce);
      },
      headers: {
        "Content-Type": "image/jpeg",
        "Content-Disposition": 'attachment; filename="image.jpg"',
      },
      processData: false,
      contentType: false,
      url: sovObj.restURL + "wp/v2/media",
      type: "POST",
      data: featuredImage,
      success: function (response) {
        console.log(response);
      },
      error: function (response) {
        console.log(response);
      },
    });```
```

Body:
I am trying to publish CPT (custom post type) posts from front end with ajax and Rest API. I can create post titles and content without any issues but I need help uploading featured images. I am using $.ajax() method.
Not sure in what format I should send attachment URL as 'data' value. Here I have prepared an object where I put the attachment path with a key of 'source_url'. Is this okay?

And after submit the request, I am getting this error:
"Sorry, you are not allowed to upload this file type." [Note: I have uploaded an image with .jpeg extension]

Please kindly review my code and let me know what I am missing.
Thanks a lot.

var featuredImage = {
      source_url: $(".post-thumb").val(),
    };

    // Lets make an Ajax call to add image on the media
    $.ajax({
      beforeSend: function (xhr) {
        xhr.setRequestHeader("X-WP-Nonce", sovObj.restNonce);
      },
      headers: {
        "Content-Type": "image/jpeg",
        "Content-Disposition": 'attachment; filename="image.jpg"',
      },
      processData: false,
      contentType: false,
      url: sovObj.restURL + "wp/v2/media",
      type: "POST",
      data: featuredImage,
      success: function (response) {
        console.log(response);
      },
      error: function (response) {
        console.log(response);
      },
    });```