问:
Adding smooth scroll on my scrollable div
I have a div block containing the steps of one of my benefits that I made scrollable vertically by holding with the mouse ( Draggable Div )

I would like to add a smooth effect and not just a scroll that stops instantly when we stop the scroll.

What should I add to my code below?

Thank you and happy holidays!

```<code>const container = document.querySelector('.process-steps');

let startY;
let startX;
let scrollLeft;
let scrollTop;
let isDown;

container.addEventListener('mousedown',e => mouseIsDown(e));
container.addEventListener('mouseup',e => mouseUp(e))
container.addEventListener('mouseleave',e=>mouseLeave(e));
container.addEventListener('mousemove',e=>mouseMove(e));

function mouseIsDown(e){
  isDown = true;
  startY = e.pageY - container.offsetTop;
  startX = e.pageX - container.offsetLeft;
  scrollLeft = container.scrollLeft;
  scrollTop = container.scrollTop;
}
function mouseUp(e){
  isDown = false;
}
function mouseLeave(e){
  isDown = false;
}
function mouseMove(e){
  if(isDown){
    e.preventDefault();
    //Move vertcally
    const y = e.pageY - container.offsetTop;
    const walkY = y - startY;
    container.scrollTop = scrollTop - walkY;

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

Body:
I have a div block containing the steps of one of my benefits that I made scrollable vertically by holding with the mouse ( Draggable Div )

I would like to add a smooth effect and not just a scroll that stops instantly when we stop the scroll.

What should I add to my code below?

Thank you and happy holidays!

const container = document.querySelector('.process-steps');

let startY;
let startX;
let scrollLeft;
let scrollTop;
let isDown;

container.addEventListener('mousedown',e => mouseIsDown(e));
container.addEventListener('mouseup',e => mouseUp(e))
container.addEventListener('mouseleave',e=>mouseLeave(e));
container.addEventListener('mousemove',e=>mouseMove(e));

function mouseIsDown(e){
  isDown = true;
  startY = e.pageY - container.offsetTop;
  startX = e.pageX - container.offsetLeft;
  scrollLeft = container.scrollLeft;
  scrollTop = container.scrollTop;
}
function mouseUp(e){
  isDown = false;
}
function mouseLeave(e){
  isDown = false;
}
function mouseMove(e){
  if(isDown){
    e.preventDefault();
    //Move vertcally
    const y = e.pageY - container.offsetTop;
    const walkY = y - startY;
    container.scrollTop = scrollTop - walkY;

  }
}
</script>


来源: stackexchange

问:
How to do shadow DOM in react js
I need to implement shadow DOM to particular component. This component has one child component and the child component has several component. I required to add shadowDOM style to these all components.</p>
```<code>import React from 'react';
import { render } from 'react-dom';
import App from './App';

const host = document.querySelector('#parent-div');
const shadow = host.attachShadow({ mode: 'open' });
const rendered= document.createElement('div');
shadow.appendChild(rendered);
ReactDOM.render(<App />, rendered);

//The above code is rendered and the child components also rendered, But I couldn't see the app component and its child components in visually.
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to do shadow DOM in react js

Body:
I need to implement shadow DOM to particular component. This component has one child component and the child component has several component. I required to add shadowDOM style to these all components.

import React from 'react';
import { render } from 'react-dom';
import App from './App';

const host = document.querySelector('#parent-div');
const shadow = host.attachShadow({ mode: 'open' });
const rendered= document.createElement('div');
shadow.appendChild(rendered);
ReactDOM.render(<App />, rendered);

//The above code is rendered and the child components also rendered, But I couldn't see the app component and its child components in visually.


问:
Upload Images to Notion Page Content-Block (Notion API, Python)
I'm working on a way to upload local images(JPEG) to a page in Notion via Notion-API with Python.
I already converted the picture in base64 and now I want to add it in a block, inside a existing page. I know theres a way to upload images from a URL but first I want to try if this is possible.

I tried different URLs of the api to which i send my call, because I'm not completely sure how to set up this up properly. It's my first try to directly interact with an API, so this is a bit of a struggle for me.

This is the part of my Code in which I have problems with. I think it might be just a problem with the json formatting, the url, or I completely missed how to to do it properly.

```<code>        # Image as base64
        image_base64 = base64.b64encode(image_bytes).decode("utf-8")

        url1 = "https://api.notion.com/v1/blocks/input_page_id/children"
        url2 = "https://api.notion.com/v1/pages"

        headers = {
            "Authorization": f"Bearer {notion_api_key}",
            "Content-Type": "application/json",
            "Notion-Version": "2022-06-28",
            "accept": "application/json"
        }

        data = {
            "parent": {
                "type": "page_id",
                "page_id": "input_page_id" },
            "children": {
                "type": "image",
                    "image": {
                        "type": "file",
                        "file_ids": [
                            {
                                "url": "data:image/jpeg;base64," + image_base64
                            }
                        ]
                    }
            }
}

        response = requests.post(url, headers=headers, json=data)
        print(response.json())
</code>```

The first URL "url1" is invalid and I tried a few variations of it, but as I understand it should be the right endpoint to update(in my case create) a block and a page in notion is also a block, so I just put in the page id here.
The error message i get for "url2" is as follows:

```<code>{'object': 'error', 'status': 400, 'code': 'validation_error', 'message': 'body failed validation: body.parent.database_id should be defined, instead was `undefined`.'}
</code>```

If uploading the images as base64 isn't possible anyway, i would try to use an Cloud Storage like AWS S3 or something which is designed for private use like Dropbox.

Body:
I'm working on a way to upload local images(JPEG) to a page in Notion via Notion-API with Python.
I already converted the picture in base64 and now I want to add it in a block, inside a existing page. I know theres a way to upload images from a URL but first I want to try if this is possible.

I tried different URLs of the api to which i send my call, because I'm not completely sure how to set up this up properly. It's my first try to directly interact with an API, so this is a bit of a struggle for me.

This is the part of my Code in which I have problems with. I think it might be just a problem with the json formatting, the url, or I completely missed how to to do it properly.

        # Image as base64
        image_base64 = base64.b64encode(image_bytes).decode("utf-8")

        url1 = "https://api.notion.com/v1/blocks/input_page_id/children"
        url2 = "https://api.notion.com/v1/pages"

        headers = {
            "Authorization": f"Bearer {notion_api_key}",
            "Content-Type": "application/json",
            "Notion-Version": "2022-06-28",
            "accept": "application/json"
        }

        data = {
            "parent": {
                "type": "page_id",
                "page_id": "input_page_id" },
            "children": {
                "type": "image",
                    "image": {
                        "type": "file",
                        "file_ids": [
                            {
                                "url": "data:image/jpeg;base64," + image_base64
                            }
                        ]
                    }
            }
}

        response = requests.post(url, headers=headers, json=data)
        print(response.json())

The first URL "url1" is invalid and I tried a few variations of it, but as I understand it should be the right endpoint to update(in my case create) a block and a page in notion is also a block, so I just put in the page id here.
The error message i get for "url2" is as follows:

{'object': 'error', 'status': 400, 'code': 'validation_error', 'message': 'body failed validation: body.parent.database_id should be defined, instead was `undefined`.'}

If uploading the images as base64 isn't possible anyway, i would try to use an Cloud Storage like AWS S3 or something which is designed for private use like Dropbox.


问:
WP theme mega menu woo taxonomies
I am working on a custom wordpress theme and using woocommerce. In the woocommerce i am having some custom taxonomies for my products ex. Brands, Designers.

I need to build a mega menu and display the Brands/Designers as submenu. Should i use navwalker to build that kind on menu? Any suggestions?

Title: WP theme mega menu woo taxonomies


问:
What alternatives can be used to represent .NET's 'from-end' indexer expression inside a lambda/expression tree?
I wrote a mock for a test which tries to mimic a method involving any file uploaded with a ".jpg" extension and decided to use .NET's 'from-end' indexer expression for convenience in checking if a file is indeed a JPEG file through the provided filename. However, the compiler complains with CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access. What alternatives I could use which achieves the same result/ease of use as the expression itself?

This code doesn't work:

```<code>_mock.Setup(f => f.DownloadFileAsync(
    It.IsNotNull<Guid>(),
    It.Is<string>(s => s.Split('.', StringSplitOptions.None)[^1] == "jpg"), // CS8790 Error
    It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new BinaryData(Array.Empty<byte>())));
</code>```

The code below works because it uses normal indexing:

```<code>_mock.Setup(f => f.DownloadFileAsync(
    It.IsNotNull<Guid>(),
    It.Is<string>(s => s.Split('.', StringSplitOptions.None)[1] == "jpg"), // compiles fine.
    It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new BinaryData(Array.Empty<byte>())));
</code>```

Body:
I wrote a mock for a test which tries to mimic a method involving any file uploaded with a ".jpg" extension and decided to use .NET's 'from-end' indexer expression for convenience in checking if a file is indeed a JPEG file through the provided filename. However, the compiler complains with CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access. What alternatives I could use which achieves the same result/ease of use as the expression itself?

This code doesn't work:

_mock.Setup(f => f.DownloadFileAsync(
    It.IsNotNull<Guid>(),
    It.Is<string>(s => s.Split('.', StringSplitOptions.None)[^1] == "jpg"), // CS8790 Error
    It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new BinaryData(Array.Empty<byte>())));

The code below works because it uses normal indexing:

_mock.Setup(f => f.DownloadFileAsync(
    It.IsNotNull<Guid>(),
    It.Is<string>(s => s.Split('.', StringSplitOptions.None)[1] == "jpg"), // compiles fine.
    It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new BinaryData(Array.Empty<byte>())));


问:
How to setup to use background callbacks in dash app
I have a dash application. I have use docker-compose, services as below:

web: # my custom dash app image. I have used gunicorn to start it in docker file

proxy: # built-in nginx image

db: # built-in postgres image

pgadmin: # built-in pgadmin image

This above setup is running fine.

Now, I have added functionality where user can upload csv files. For this I am trying to use background callback.
I have read the documentation on dash website for the same but confuse how to setup this.

What I understand is as below:
I will need following

redis: # built-in redis image

install (under web), pip install dash[celery]

write a code from dash website as demo/test code

Issuses are as follow:

do I need to install (under web) pip install -U "celery[redis]"

how to start/initialize celery_app i.e. celery -A app:celery_app worker --loglevel=INFO --concurrency=2

as in web service, I am starting gunicorn, how start celery also from same docker file

or do I need new service as say

eg worker: # my custom dash app image (same as web) and start/initiate celery_app in docker file

by doing so am I duplicating the same web code twice, one service(web) to start gunicorn and other service (worker) to start celery_app

Please suggest.

Updated

project structure:

main.py

proj

manage.py

visuals

app.py  # This is dash application

Installed:

dash[celery]

app.py:

```<code>REDIS_URL='redis://localhost:6379/0'

celery_app = Celery(__name__, broker=REDIS_URL, backend=REDIS_URL)
background_callback_manager = CeleryManager(celery_app=celery_app)

app = Dash(
    __name__,
    background_callback_manager=background_callback_manager,
    external_stylesheets=[dbc.themes.BOOTSTRAP],
    suppress_callback_exceptions=True,
)

server = app.server
</code>```

docker-compose:

```<code>  web:
    container_name: web_application
    build: .
    command: ["gunicorn", "--workers", "2", "--bind", "0.0.0.0:8000", "--preload", "main:create_app()"]
    restart: always
    ports:
      - "8000:8000"
    networks:
    env_file:
    depends_on:
      - db
      - pgadmin
      - celery
    volumes:

  celery:
    container_name: celery_application
    build: .
    # command: "celery -A main:create_celery_app() worker --loglevel=INFO"
    command: "celery -A main:celery_app worker --loglevel=INFO"
    restart: always
    networks:
    env_file:
    depends_on:
      - db
    volumes:
</code>```

Errors:

```<code> Error: Invalid value for '-A' / '--app':
celery_application | Unable to load celery application.
celery_application | While trying to load the module main the following error occurred:
celery_application | Traceback (most recent call last):
celery_application |   File ".venv/lib/python3.11/site-packages/celery/app/base.py", line 1250, in backend
celery_application |     return self._local.backend
celery_application |            ^^^^^^^^^^^^^^^^^^^
celery_application | AttributeError: '_thread._local' object has no attribute 'backend'

celery_application | ModuleNotFoundError: No module named "'redis"
</code>```

Body:
I have a dash application. I have use docker-compose, services as below:

web: # my custom dash app image. I have used gunicorn to start it in docker file

proxy: # built-in nginx image

db: # built-in postgres image

pgadmin: # built-in pgadmin image

This above setup is running fine.

Now, I have added functionality where user can upload csv files. For this I am trying to use background callback.
I have read the documentation on dash website for the same but confuse how to setup this.

What I understand is as below:
I will need following

redis: # built-in redis image

install (under web), pip install dash[celery]

write a code from dash website as demo/test code

Issuses are as follow:

do I need to install (under web) pip install -U "celery[redis]"

how to start/initialize celery_app i.e. celery -A app:celery_app worker --loglevel=INFO --concurrency=2

as in web service, I am starting gunicorn, how start celery also from same docker file

or do I need new service as say

eg worker: # my custom dash app image (same as web) and start/initiate celery_app in docker file

by doing so am I duplicating the same web code twice, one service(web) to start gunicorn and other service (worker) to start celery_app

Please suggest.

Updated

project structure:

main.py

proj

manage.py

visuals

app.py  # This is dash application

Installed:

dash[celery]

app.py:

REDIS_URL='redis://localhost:6379/0'

celery_app = Celery(__name__, broker=REDIS_URL, backend=REDIS_URL)
background_callback_manager = CeleryManager(celery_app=celery_app)

app = Dash(
    __name__,
    background_callback_manager=background_callback_manager,
    external_stylesheets=[dbc.themes.BOOTSTRAP],
    suppress_callback_exceptions=True,
)

server = app.server

docker-compose:

  web:
    container_name: web_application
    build: .
    command: ["gunicorn", "--workers", "2", "--bind", "0.0.0.0:8000", "--preload", "main:create_app()"]
    restart: always
    ports:
      - "8000:8000"
    networks:
    env_file:
    depends_on:
      - db
      - pgadmin
      - celery
    volumes:

  celery:
    container_name: celery_application
    build: .
    # command: "celery -A main:create_celery_app() worker --loglevel=INFO"
    command: "celery -A main:celery_app worker --loglevel=INFO"
    restart: always
    networks:
    env_file:
    depends_on:
      - db
    volumes:

Errors:

 Error: Invalid value for '-A' / '--app':
celery_application | Unable to load celery application.
celery_application | While trying to load the module main the following error occurred:
celery_application | Traceback (most recent call last):
celery_application |   File ".venv/lib/python3.11/site-packages/celery/app/base.py", line 1250, in backend
celery_application |     return self._local.backend
celery_application |            ^^^^^^^^^^^^^^^^^^^
celery_application | AttributeError: '_thread._local' object has no attribute 'backend'

celery_application | ModuleNotFoundError: No module named "'redis"


问:
Jupyter notebook is not showing files in Document Folder
I open Anaconda Prompt and type jupyter notebook which will open jupyter notebook in Microsoft Edge.

When I click on Documents it didn't show anything inside Documents Folder. I have to use upload button to upload files in jupyter notebook.

But when I click on Downloads folder, everything is visible over there.

Don't know why this is happening.

I also tried to open jupyter notebook from Anaconda Navigator but still issue persist.

Please find below image for Version of jupyter notebook.

Installed path:- C:\Users\user_name\anaconda3

I am expecting, jupyter notebook should show me files which are exist in Documents folder same as it shows me files in Downloads folder.


问:
Nextjs getServerSideProps does not pass session to component
Good morning. I am using NextJS and get the session in the getServerSideProps block.
I am passing multiple parameters to the return object, however, the session does not pass. All of the other key value pairs works, but when I try to log the session, It comes undefined... I don't understand...

```<code>const DashboardPage = ({ session, secret }) => {

  const [loading, setloading] = useState(false);

  //This does not work
  console.log('Session: ', session);

  return (
    <section className="border-4 border-orange-800 max-w-5xl mx-auto">

      <CreateListModal userId={session?.userId} loading={loading} setloading={setloading} />
    </section>
  )
}

export const getServerSideProps = async context => {

  // get sessions with added user Id in the session object
  const session = await requireAuthentication(context);

// This works
  console.log(session);

  if (!session) {
    return {
      redirect: {
        destination: '/signup',
        permanent: false
      }
    }
  }

  else {
    return {
      props: {

        session: session,
        secret: 'Pasarika este dulce'
      }
    }
  }
}

export default DashboardPage;

</code>```

The purpose of the requireAuthentication function is to create a new session object where I will insert another key value pair that will contain the user id and the session that will be used in the entire app.

In that function I get the user by email that is returned by the session and get the Id from the db. I than return the new session object that looks like this:

```<code>{
  user: {
    name: 'daniel sas',
    email: 'email@gmail.com',
    image: 'https://lh3.googldeusercontent.com/a/A6r44ZwMyONqcfJORNnuYtbVv_LYbab-wv5Uyxk=s96-c',
    userId: 'clbcpc0hi0002sb1wsiea3q5d'//This is the required thing in my app
  },
  expires: '2022-12-23T08:04:08.263Z'
}
</code>```

The following function is used to get the data from the database

```<code>import { getSession } from "next-auth/react";
import prisma from './prisma'

// This function get the email and returns a new session object that includes
//  the userId

export const requireAuthentication = async context => {
    const session = await getSession(context);

    // If there is no user or there is an error ret to signup page
    if (!session) return null

    // If the user is not found return same redirect to signup
    else {
        try {
            const user = await prisma.user.findUnique({where: { email: session.user.email }});

            if (!user) return null;

            // Must return a new session here that contains the userId...
            else {
              const newSession = {
                user: {
                  ...session.user,
                  userId: user.id
                },

                expires: session.expires
              };

              return newSession;
            }
        }
        catch (error) {
            if (error) {
              console.log(error);
            }
        }
    }
}
</code>```

Body:
Good morning. I am using NextJS and get the session in the getServerSideProps block.
I am passing multiple parameters to the return object, however, the session does not pass. All of the other key value pairs works, but when I try to log the session, It comes undefined... I don't understand...

const DashboardPage = ({ session, secret }) => {

  const [loading, setloading] = useState(false);

  //This does not work
  console.log('Session: ', session);

  return (

      <CreateListModal userId={session?.userId} loading={loading} setloading={setloading} />

  )
}

export const getServerSideProps = async context => {

  // get sessions with added user Id in the session object
  const session = await requireAuthentication(context);

// This works
  console.log(session);

  if (!session) {
    return {
      redirect: {
        destination: '/signup',
        permanent: false
      }
    }
  }

  else {
    return {
      props: {

        session: session,
        secret: 'Pasarika este dulce'
      }
    }
  }
}

export default DashboardPage;

The purpose of the requireAuthentication function is to create a new session object where I will insert another key value pair that will contain the user id and the session that will be used in the entire app.

In that function I get the user by email that is returned by the session and get the Id from the db. I than return the new session object that looks like this:

{
  user: {
    name: 'daniel sas',
    email: 'email@gmail.com',
    image: 'https://lh3.googldeusercontent.com/a/A6r44ZwMyONqcfJORNnuYtbVv_LYbab-wv5Uyxk=s96-c',
    userId: 'clbcpc0hi0002sb1wsiea3q5d'//This is the required thing in my app
  },
  expires: '2022-12-23T08:04:08.263Z'
}

The following function is used to get the data from the database

import { getSession } from "next-auth/react";
import prisma from './prisma'

// This function get the email and returns a new session object that includes
//  the userId

export const requireAuthentication = async context => {
    const session = await getSession(context);

    // If there is no user or there is an error ret to signup page
    if (!session) return null

    // If the user is not found return same redirect to signup
    else {
        try {
            const user = await prisma.user.findUnique({where: { email: session.user.email }});

            if (!user) return null;

            // Must return a new session here that contains the userId...
            else {
              const newSession = {
                user: {
                  ...session.user,
                  userId: user.id
                },

                expires: session.expires
              };

              return newSession;
            }
        }
        catch (error) {
            if (error) {
              console.log(error);
            }
        }
    }
}


问:
Making API request Asynchronously, but got Error: OSError: [WinError 10038] An operation was attempted on something that is not a socket
This is my code and I am simply making calls for sort of stocks data for different tickers.

```<code>import asyncio
import aiohttp
from decouple import config
import time

TOKEN = config('token')
url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={}&interval=5min&apikey={}"
symbols = ['AAPL', 'GOOG', 'TSLA', 'MSFT', 'XOM', 'WMT', 'PFE', 'HBC', 'JNJ', 'BAC']
results = []

print('Started Requesting!')
start = time.time()

def get_tasks(session):
    tasks = []
    for symbol in symbols:
        tasks.append(session.get(url=url.format(symbol, AlphaVanAPI), ssl=False))
    return tasks

async def reqAPI():
    async with aiohttp.ClientSession() as session:
        tasks = get_tasks(session)
        responses = await asyncio.gather(*tasks)
        for response in responses:
            results.append(await response.json())

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(reqAPI())
end = time.time() - start
print('Done Requesting! Took {} seconds'.format(end))
</code>```

When I ran the code, it gave me below error:

```<code>Error: OSError: [WinError 10038] An operation was attempted on something that is not a socket
Exception ignored in: <coroutine object reqAPI at 0x000002CF3B72E7C0>
RuntimeError: coroutine ignored GeneratorExit
</code>```

I've ran the code multiple times but it shown the same error every time.

IMPORTANT: But then when I ran it after 30 minutes, it ran just fine. I have not change anything in the code.

Output when I ran after 30 minutes.

```<code>Started Requesting!
Done Requesting! Took 3.059232473373413 seconds
</code>```

Now it is Unexpected behaviour for me and it freaks me out.
Can someone tells me what sorcery is this? I am new to this.
Thanks in advance!

Body:
This is my code and I am simply making calls for sort of stocks data for different tickers.

import asyncio
import aiohttp
from decouple import config
import time

TOKEN = config('token')
url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={}&interval=5min&apikey={}"
symbols = ['AAPL', 'GOOG', 'TSLA', 'MSFT', 'XOM', 'WMT', 'PFE', 'HBC', 'JNJ', 'BAC']
results = []

print('Started Requesting!')
start = time.time()

def get_tasks(session):
    tasks = []
    for symbol in symbols:
        tasks.append(session.get(url=url.format(symbol, AlphaVanAPI), ssl=False))
    return tasks

async def reqAPI():
    async with aiohttp.ClientSession() as session:
        tasks = get_tasks(session)
        responses = await asyncio.gather(*tasks)
        for response in responses:
            results.append(await response.json())

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(reqAPI())
end = time.time() - start
print('Done Requesting! Took {} seconds'.format(end))

When I ran the code, it gave me below error:

Error: OSError: [WinError 10038] An operation was attempted on something that is not a socket
Exception ignored in: <coroutine object reqAPI at 0x000002CF3B72E7C0>
RuntimeError: coroutine ignored GeneratorExit

I've ran the code multiple times but it shown the same error every time.

IMPORTANT: But then when I ran it after 30 minutes, it ran just fine. I have not change anything in the code.

Output when I ran after 30 minutes.

Started Requesting!
Done Requesting! Took 3.059232473373413 seconds

Now it is Unexpected behaviour for me and it freaks me out.
Can someone tells me what sorcery is this? I am new to this.
Thanks in advance!


问:
Chrome Extension install numbers are VERY different on Google Analytics vs. Chrome Web Store statistics -- why, and how to resolve?
If I look inside of the Chrome Web Store "Analytics" section, it shows a certain number of installs over a specified time period. Google Analytics shows a totally different number. Why?

I've integrated my Chrome Web Store page with my Google Analytics page, for better tracking information. Installs are apparently reported in Analytics as page visits to a URL that contains "track_install". (I assume that's the case; there's shockingly no documentation I can find on, how to track any sort of conversions, install rates, etc, of Chrome Extensions, via either Google Analytics or Google Ads.)

My question is, why am I seeing such wildly different numbers between the two sources? Google Analytics is under-reporting installs by a factor of around 4, versus what I see in the Chrome Web Store page.

Any idea what is causing this, and how to resolve it?

Thanks


问:
ue5 Object overlapping error when each object's y value is different
ue5 When each object y value is different
Even if the orthographic and ortho width are modified in the camera options
Objects overlap due to different y values.[[[enter image description here](https://i.stack.imgur.com/yF18S.jpg)](https://i.stack.imgur.com/ikGy9.png)](https://i.stack.imgur.com/V2u7e.png)

I modified the orthographic and ortho width in the camera options.[enter image description here]


问:
Unable to create table in database getting warning
Getting Wrnings but unable to create tables in data base.

while executing spring boot program I am getting this.
HHH90000021: Encountered deprecated setting [javax.persistence.sharedCache.mode], use [jakarta.persistence.sharedCache.mode] instead

HHH90000026: MySQL57Dialect has been deprecated; use org.hibernate.dialect.MySQLDialect instead
[2m


问:
I have a situation where I am using onBlur and useRef for a textArea because of lagging issue in textArea
I am using onBlur instead of onChange event with useRef for a textArea. I am using this because whenever I type in textArea it is taking much longer time then expected. textArea is lagging in my component so for that I am using onBlur with ref. but the problem is whenever I am submiting my form and edit that form it is clearing the state and ref but does not update the textarea field.

const textRef = useRef(TextArea)

<TextArea
  ref={textRef}
  className="form-control form-control-sm"
  maxLength={500}
  cols={30}
  placeholder="Enter Reason here"
  rows={1}
  onBlur={() => {
    setIstimeSequenceReasonDropdown(
      textRef?.current?.resizableTextArea?.textArea?.value
    )
  }}
/>

```


问:
Cassandra daemon automatically stops
I'm starting the Cassandra daemon and it stays up for 10 seconds and then it stops working automatically. What would be the problem here?

Cassandra daemon automatically stops

Title: Cassandra daemon automatically stops


问:
Pass verfication code phone authentication
i try to do automatic fill of sms code ,I am using firebase, in function oncodesent is send the code, and after that i want to pass the verficiation code to another functions, and the oncreate to use him , the problem is this method is void by default (i cant do return),
And when i try to save it to another variable is always null except from the oncodesent method,
Can anyone know how to fix it?

this is the function

```<code> @Override
    public void onCodeSent(@NonNull String verificationId,
                           @NonNull PhoneAuthProvider.ForceResendingToken token)
    {
        super.onCodeSent(verificationId, token);
        Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity.class);

        intent.putExtra("verificationId", verificationId);

        Toast.makeText(RegistrationActivity.this, "Code sent", Toast.LENGTH_SHORT).show();
        btnJoinNl.setEnabled(true);
        flagVerification=true;
</code>```

how I pass the verificationId to other functions in this activity?

Body:
i try to do automatic fill of sms code ,I am using firebase, in function oncodesent is send the code, and after that i want to pass the verficiation code to another functions, and the oncreate to use him , the problem is this method is void by default (i cant do return),
And when i try to save it to another variable is always null except from the oncodesent method,
Can anyone know how to fix it?

this is the function

 @Override
    public void onCodeSent(@NonNull String verificationId,
                           @NonNull PhoneAuthProvider.ForceResendingToken token)
    {
        super.onCodeSent(verificationId, token);
        Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity.class);

        intent.putExtra("verificationId", verificationId);

        Toast.makeText(RegistrationActivity.this, "Code sent", Toast.LENGTH_SHORT).show();
        btnJoinNl.setEnabled(true);
        flagVerification=true;

how I pass the verificationId to other functions in this activity?


问:
How to create a UISplitViewController with a VIPER pattern and how to handle the communication between viewControllers?
I've created a UISplitView Module using VIPER architecture, my intention is to use it many times during the project.

I want to handle communication between the two child viewcontrollers.
I am not being able to think a suitable way for this.

This is my GenericSplitView Router Class:

```<code>class GenericSplitRouter {

    static func createModule(viewControllerLeft: UIViewController, viewControllerRight: UIViewController) -> GenericSplitViewController {
        let view = GenericSplitViewController()
        let presenter: GenericSplitPresenterProtocol & GenericSplitInteractorOutputProtocol = GenericSplitPresenter()
        let interactor: GenericSplitInteractorInputProtocol & GenericSplitRemoteDataManagerOutputProtocol = GenericSplitInteractor()
        let localDataManager: GenericSplitLocalDataManagerInputProtocol = GenericSplitLocalDataManager()
        let remoteDataManager: GenericSplitRemoteDataManagerInputProtocol = GenericSplitRemoteDataManager()
        let router: GenericSplitRouterProtocol = GenericSplitRouter()

        view.presenter = presenter
        presenter.view = view
        presenter.router = router
        presenter.interactor = interactor
        presenter.viewControllerRight = viewControllerRight
        presenter.viewControllerLeft = viewControllerLeft
        interactor.presenter = presenter
        interactor.localDatamanager = localDataManager
        interactor.remoteDatamanager = remoteDataManager
        remoteDataManager.remoteRequestHandler = interactor
        presenter.viewControllerLeft = viewControllerLeft
        presenter.viewControllerRight = viewControllerRight

        return view
    }
}
</code>```

When I Instantiate the viper module I do it like this so I end up having a Parent VIPER module with two child VIPER modules

```<code>let vc = GenericSplitRouter.createModule(viewControllerLeft: NotificationsRouter().createModule(), viewControllerRight: NotificationDetailRouter().createModule())

</code>```

ViewController from the left is a tableView
ViewController from the right is a detailView from the cells that users select.

I've tried using the delegate pattern but having a hard time to implement it in this situation

Body:
I've created a UISplitView Module using VIPER architecture, my intention is to use it many times during the project.

I want to handle communication between the two child viewcontrollers.
I am not being able to think a suitable way for this.

This is my GenericSplitView Router Class:

class GenericSplitRouter {

    static func createModule(viewControllerLeft: UIViewController, viewControllerRight: UIViewController) -> GenericSplitViewController {
        let view = GenericSplitViewController()
        let presenter: GenericSplitPresenterProtocol & GenericSplitInteractorOutputProtocol = GenericSplitPresenter()
        let interactor: GenericSplitInteractorInputProtocol & GenericSplitRemoteDataManagerOutputProtocol = GenericSplitInteractor()
        let localDataManager: GenericSplitLocalDataManagerInputProtocol = GenericSplitLocalDataManager()
        let remoteDataManager: GenericSplitRemoteDataManagerInputProtocol = GenericSplitRemoteDataManager()
        let router: GenericSplitRouterProtocol = GenericSplitRouter()

        view.presenter = presenter
        presenter.view = view
        presenter.router = router
        presenter.interactor = interactor
        presenter.viewControllerRight = viewControllerRight
        presenter.viewControllerLeft = viewControllerLeft
        interactor.presenter = presenter
        interactor.localDatamanager = localDataManager
        interactor.remoteDatamanager = remoteDataManager
        remoteDataManager.remoteRequestHandler = interactor
        presenter.viewControllerLeft = viewControllerLeft
        presenter.viewControllerRight = viewControllerRight

        return view
    }
}

When I Instantiate the viper module I do it like this so I end up having a Parent VIPER module with two child VIPER modules

let vc = GenericSplitRouter.createModule(viewControllerLeft: NotificationsRouter().createModule(), viewControllerRight: NotificationDetailRouter().createModule())

ViewController from the left is a tableView
ViewController from the right is a detailView from the cells that users select.

I've tried using the delegate pattern but having a hard time to implement it in this situation


问:
Flutter: How to make a rotatable coordinate system by gesture like maps in Ubuntu?
I want to create a page with a rotatable coordinate GestureDetector system run on Ubuntu and Android like this Video

This is my code use InteractiveViewer, CustomPainter and GestureDetector:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(title: const Text('My App')),
            body: InteractiveViewer(
              child: Container(
                color: Colors.amberAccent,
                width: double.maxFinite,
                height: double.maxFinite,
                child: GestureDetector(
                  child: CustomPaint(
                      painter: MapPainter(
                    context: context,
                  )),
                ),
              ),
            )));
  }
}

class MapPainter extends CustomPainter {
  final BuildContext context;
  final double resolution = 0.05;

  MapPainter({required this.context});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.save();
    {
      drawGrid(canvas);
    }
    canvas.restore();
  }

  void drawGrid(Canvas canvas) {
    int numOfGrid = 50;
    if (resolution == 0) return;
    for (var i = -20; i <= numOfGrid; i++) {
      canvas.drawLine(
        Offset(i / resolution, -numOfGrid / resolution),
        Offset(i / resolution, numOfGrid / resolution),
        Paint()..color = Colors.grey.withOpacity(0.3),
      );
      canvas.drawLine(
        Offset(-numOfGrid / resolution, i / resolution),
        Offset(numOfGrid / resolution, i / resolution),
        Paint()..color = Colors.grey.withOpacity(0.3),
      );
    }
  }

  @override
  bool shouldRepaint(MapPainter oldDelegate) {
    return true;
  }
}

</code>```

I tried matrix_gexture_detector like this Answer but the rotation function only works for Android, I don't know how to rotate in Ubuntu.
matrix_gesture_detector

Body:
I want to create a page with a rotatable coordinate GestureDetector system run on Ubuntu and Android like this Video

This is my code use InteractiveViewer, CustomPainter and GestureDetector:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(title: const Text('My App')),
            body: InteractiveViewer(
              child: Container(
                color: Colors.amberAccent,
                width: double.maxFinite,
                height: double.maxFinite,
                child: GestureDetector(
                  child: CustomPaint(
                      painter: MapPainter(
                    context: context,
                  )),
                ),
              ),
            )));
  }
}

class MapPainter extends CustomPainter {
  final BuildContext context;
  final double resolution = 0.05;

  MapPainter({required this.context});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.save();
    {
      drawGrid(canvas);
    }
    canvas.restore();
  }

  void drawGrid(Canvas canvas) {
    int numOfGrid = 50;
    if (resolution == 0) return;
    for (var i = -20; i <= numOfGrid; i++) {
      canvas.drawLine(
        Offset(i / resolution, -numOfGrid / resolution),
        Offset(i / resolution, numOfGrid / resolution),
        Paint()..color = Colors.grey.withOpacity(0.3),
      );
      canvas.drawLine(
        Offset(-numOfGrid / resolution, i / resolution),
        Offset(numOfGrid / resolution, i / resolution),
        Paint()..color = Colors.grey.withOpacity(0.3),
      );
    }
  }

  @override
  bool shouldRepaint(MapPainter oldDelegate) {
    return true;
  }
}

I tried matrix_gexture_detector like this Answer but the rotation function only works for Android, I don't know how to rotate in Ubuntu.
matrix_gesture_detector


问:
How to resolve Pandas Read csv not working for Mock S3?
I created a mock s3 bucket with moto. I put an object into it. I am trying to read with pandas read_csv.

```<code>S3_BUCKET_NAME = 'mock_bucket'
def s3_bucket():
    mocks3 = mock_s3()
    mocks3.start()
    os.environ["AWS_DEFAULT_REGION"] = "us-east-1"
    s3 = boto3.resource('s3')
    s3.create_bucket(Bucket=S3_BUCKET_NAME)
    return s3
s3 = s3_bucket()
bucket = s3.Bucket(S3_BUCKET_NAME)

bucket.put_object(Key='/2022/12/14/6/25/t_ext_gop/t.csv', Body='test')
a = pd.read_csv('s3://amx-mock-bigdata-stemtime/2022/12/14/6/25/t_ext_gop/t.csv')
</code>```

I get the following error:

```<code>AttributeError: 'MockRawResponse' object has no attribute 'raw_headers'
</code>```

How do I resolve this?

Body:
I created a mock s3 bucket with moto. I put an object into it. I am trying to read with pandas read_csv.

S3_BUCKET_NAME = 'mock_bucket'
def s3_bucket():
    mocks3 = mock_s3()
    mocks3.start()
    os.environ["AWS_DEFAULT_REGION"] = "us-east-1"
    s3 = boto3.resource('s3')
    s3.create_bucket(Bucket=S3_BUCKET_NAME)
    return s3
s3 = s3_bucket()
bucket = s3.Bucket(S3_BUCKET_NAME)

bucket.put_object(Key='/2022/12/14/6/25/t_ext_gop/t.csv', Body='test')
a = pd.read_csv('s3://amx-mock-bigdata-stemtime/2022/12/14/6/25/t_ext_gop/t.csv')

I get the following error:

AttributeError: 'MockRawResponse' object has no attribute 'raw_headers'

How do I resolve this?


问:
How can I see the tether coming to the address?
what I want to do is a bot that sends a signal to myself when there is a token coming to my wallet address. But in the fiction I want to do, I want to pull the latest transactions of the address with trongrid and send a notification to myself if the money has come from there, but I have no idea how to do it. How do I access the inside of raw_data_hex and find out what's going on there?

import requests
import binascii
from struct import Struct

walletAddress = "walletAddress"

url = f"https://api.trongrid.io/v1/accounts/{walletAddress}/transactions?only_confirmed=true&only_to=true&limit=25"

headers = {"accept": "application/json"}

response = requests.get(url=url, headers=headers)

for transaction in response.json()["data"]:
    raw_data = binascii.unhexlify(transaction.get("raw_data_hex"))
    print(raw_data[:255].decode("iso-8859-1"))
```
</code>```


问:
Picocli: is it possible to calculate Option default value with help of some other Autowired field?
I want to implement the following logic of Option default value calculation

```<code>@Command(name = "test-command")
public class TestCommand implements Callable {

    @Autowired
    DefaultValueUtils utils;

    @ArgGroup
    EntityGroup functions = new EntityGroup();

    class EntityGroup {
        @Option(names = "--function1", defaultValue = "true")
        boolean function1 = utils.isFunction1();

        @Option(names = "--function2", defaultValue = "true")
        boolean function2 = utils.isFunction2();
    }

    ...
}

</code>```

I have 2 boolean options - function1 and function2; if they are not provided their default values are specified in some other place. But if options provided, I need to override values with provided ones.
One more problem is in following logic:

if none of them provided - default values should be calculated;
If one of them provided - only provided one is true, not provided false;
If both provided - both are true

How can I implement this?

This current block of the code is failing because utils is null during EntityGroup instantiation.

Body:
I want to implement the following logic of Option default value calculation

@Command(name = "test-command")
public class TestCommand implements Callable {

    @Autowired
    DefaultValueUtils utils;

    @ArgGroup
    EntityGroup functions = new EntityGroup();

    class EntityGroup {
        @Option(names = "--function1", defaultValue = "true")
        boolean function1 = utils.isFunction1();

        @Option(names = "--function2", defaultValue = "true")
        boolean function2 = utils.isFunction2();
    }

    ...
}

I have 2 boolean options - function1 and function2; if they are not provided their default values are specified in some other place. But if options provided, I need to override values with provided ones.
One more problem is in following logic:

if none of them provided - default values should be calculated;
If one of them provided - only provided one is true, not provided false;
If both provided - both are true

How can I implement this?

This current block of the code is failing because utils is null during EntityGroup instantiation.


问:
Progress Bar S3 Bucket - PHP Ajax, Javascript
I'm trying to add a Progress Bar to track the file Upload status of my Form. To upload files I use this Form code:

```<code><form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
         <input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="this.form.submit();changeStyle()" class="file-up" id="fileFTP">
      </form>
</code>```

And this PHP code to manage the File Upload request.

```<code><?php
require './aws/aws-autoloader.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

// AWS Info
$bucketName = '***';
$IAM_KEY    = '***';
$IAM_SECRET = '***';

// Connect to AWS
try {
    // You may need to change the region. It will say in the URL when the bucket is open
    // and on creation. us-east-2 is Ohio, us-east-1 is North Virgina
    $s3 = S3Client::factory(array(
        'credentials' => array(
            'key' => $IAM_KEY,
            'secret' => $IAM_SECRET
        ),
        'version' => 'latest',
        'region' => 'eu-west-1'
    ));

}
catch (Exception $e) {

    die("Error: " . $e->getMessage());
}
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
//$target_file = 'f/' . basename($_FILES["ftp"]['tmp_name']);   //ftp is file name at index.php

if (isset($_FILES["ftp"]) && $_FILES["ftp"]["error"] == 0) {

    $mimeType = mime_content_type($_FILES["ftp"]["tmp_name"]);
    $fileSize = $_FILES["ftp"]["size"];

    if (strpos($mimeType, "image") === 0) {
        if ($fileSize <= 1000 * 1024 * 1024) { //max image size

            $target_dir  = "i/";
           // $strng       = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
            $target_file = $target_dir . time() . rand(100, 999);
            //$pathInS3    = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;

            // Add it to S3
            try {
                if (!file_exists('/tmp/tmpfile')) {
                    echo 3;
                    mkdir('/tmp/tmpfile');
                }

                $tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
                $tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");

                $fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
                $tempFile     = file_put_contents($tempFilePath, $fileContents);

                $s3->putObject(array(
                    'Bucket' => $bucketName,
                    'Key' => $target_file,
                    'SourceFile' => $tempFilePath,
                    'StorageClass' => 'REDUCED_REDUNDANCY',
                    'ACL' => 'public-read'
                ));

                $valPOutput = htmlspecialchars($target_file);
                header('HTTP/1.1 303 See Other');
                header('Location: http://example.com/result.php' . "?p=" . $valPOutput);

            }
            catch (S3Exception $e) {
                die('Error:' . $e->getMessage());
            }
            catch (Exception $e) {
                die('Error:' . $e->getMessage());
            }
        } else {
            echo "image too big";
        }
    } elseif ($mimeType == "application/zip" || $mimeType == "application/x-rar-compressed" || $mimeType == "application/x-7z-compressed" || $mimeType == "application/x-bzip2") {
        if ($fileSize <= 5000 * 1024 * 1024) { //max arch size

            $target_dir  = "f/";
            //$strng       = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
            $target_file = $target_dir . time() . rand(100, 999);
           // $pathInS3    = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;

            // Add it to S3
            try {
                if (!file_exists('/tmp/tmpfile')) {
                    echo 3;
                    mkdir('/tmp/tmpfile');
                }

                $tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
                $tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");

                $fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
                $tempFile     = file_put_contents($tempFilePath, $fileContents);

                $s3->putObject(array(
                    'Bucket' => $bucketName,
                    'Key' => $target_file,
                    'SourceFile' => $tempFilePath,
                    'StorageClass' => 'REDUCED_REDUNDANCY',
                    'ACL' => 'public-read'
                ));

                $valPOutput = htmlspecialchars($target_file);
                header('HTTP/1.1 303 See Other');
                header('Location: http://example.com/result.php' . "?p=" . $valPOutput);

            }
            catch (S3Exception $e) {
                die('Error:' . $e->getMessage());
            }
            catch (Exception $e) {
                die('Error:' . $e->getMessage());
            }
        }else {
          echo "arch too big";
        }
    }
}

?>
</code>```

I've tried to do so adding event listeners to prevent submitting request, but when I upload a file, the website URL changes from https://example.com to https://example.com/awsUpload.php and the Progress Bar does not move and the Upload keeps going.

I'd like to receive some suggestions on how I can move or think to achieve that (the code I posted right now does not include any Progress bar test since I deleted the progress bar code cause it did not work).

EDIT DOWN HERE
Modified the form and added this new Script.
Right now the Load bar does work and the file gets uploaded, unfortunately I do not know why after the form gets submitted I do not get redirected to https://example.com/?p=****

```<code>  <form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
     <input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="uploadFile(this.form)" class="file-up" id="fileFTP">

   <progress id="upload-progress" value="0" max="100"></progress>

  </form>

<script>
function uploadFile(form) {
  var fileInput = form.querySelector('input[type="file"]');
  var file = fileInput.files[0];
  var formData = new FormData(form);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', this.form, true);

  xhr.upload.onprogress = function(e) {
    if (e.lengthComputable) {
      var percentComplete = (e.loaded / e.total) * 100;
      var progressBar = form.querySelector('progress');
      progressBar.value = percentComplete;
    }
  };

  xhr.onload = function() {
    if (xhr.status == 200) {
      // File uploaded successfully
      alert('success')
    } else {
      // An error occurred during the upload
    }
  };

  xhr.send(formData);
}
</script>
</code>```

Extra: I tried to ad in the action of  if (xhr.status == 200) to redirect to a certain webpage with window.location but I'm missing the  $valPOutput from the awsUpload.php and do not know how to get it.

Body:
I'm trying to add a Progress Bar to track the file Upload status of my Form. To upload files I use this Form code:

<form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
         <input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="this.form.submit();changeStyle()" class="file-up" id="fileFTP">
      </form>

And this PHP code to manage the File Upload request.

<?php
require './aws/aws-autoloader.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

// AWS Info
$bucketName = '***';
$IAM_KEY    = '***';
$IAM_SECRET = '***';

// Connect to AWS
try {
    // You may need to change the region. It will say in the URL when the bucket is open
    // and on creation. us-east-2 is Ohio, us-east-1 is North Virgina
    $s3 = S3Client::factory(array(
        'credentials' => array(
            'key' => $IAM_KEY,
            'secret' => $IAM_SECRET
        ),
        'version' => 'latest',
        'region' => 'eu-west-1'
    ));

}
catch (Exception $e) {

    die("Error: " . $e->getMessage());
}
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
//$target_file = 'f/' . basename($_FILES["ftp"]['tmp_name']);   //ftp is file name at index.php

if (isset($_FILES["ftp"]) && $_FILES["ftp"]["error"] == 0) {

    $mimeType = mime_content_type($_FILES["ftp"]["tmp_name"]);
    $fileSize = $_FILES["ftp"]["size"];

    if (strpos($mimeType, "image") === 0) {
        if ($fileSize <= 1000 * 1024 * 1024) { //max image size

            $target_dir  = "i/";
           // $strng       = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
            $target_file = $target_dir . time() . rand(100, 999);
            //$pathInS3    = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;

            // Add it to S3
            try {
                if (!file_exists('/tmp/tmpfile')) {
                    echo 3;
                    mkdir('/tmp/tmpfile');
                }

                $tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
                $tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");

                $fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
                $tempFile     = file_put_contents($tempFilePath, $fileContents);

                $s3->putObject(array(
                    'Bucket' => $bucketName,
                    'Key' => $target_file,
                    'SourceFile' => $tempFilePath,
                    'StorageClass' => 'REDUCED_REDUNDANCY',
                    'ACL' => 'public-read'
                ));

                $valPOutput = htmlspecialchars($target_file);
                header('HTTP/1.1 303 See Other');
                header('Location: http://example.com/result.php' . "?p=" . $valPOutput);

            }
            catch (S3Exception $e) {
                die('Error:' . $e->getMessage());
            }
            catch (Exception $e) {
                die('Error:' . $e->getMessage());
            }
        } else {
            echo "image too big";
        }
    } elseif ($mimeType == "application/zip" || $mimeType == "application/x-rar-compressed" || $mimeType == "application/x-7z-compressed" || $mimeType == "application/x-bzip2") {
        if ($fileSize <= 5000 * 1024 * 1024) { //max arch size

            $target_dir  = "f/";
            //$strng       = preg_replace("/[\s-]|\#/", "_", basename($_FILES["ftp"]["name"])); //Prima era solo "/[\s-]/"
            $target_file = $target_dir . time() . rand(100, 999);
           // $pathInS3    = 'https://s3.ap-south-1.amazonaws.com/' . $bucketName . '/' . $target_file;

            // Add it to S3
            try {
                if (!file_exists('/tmp/tmpfile')) {
                    echo 3;
                    mkdir('/tmp/tmpfile');
                }

                $tempFilePath = '/tmp/tmpfile/' . basename($_FILES["ftp"]['name']);
                $tempFile = fopen($tempFilePath, "w") or die("Error: Unable to open file.");

                $fileContents = file_get_contents($_FILES["ftp"]['tmp_name']);
                $tempFile     = file_put_contents($tempFilePath, $fileContents);

                $s3->putObject(array(
                    'Bucket' => $bucketName,
                    'Key' => $target_file,
                    'SourceFile' => $tempFilePath,
                    'StorageClass' => 'REDUCED_REDUNDANCY',
                    'ACL' => 'public-read'
                ));

                $valPOutput = htmlspecialchars($target_file);
                header('HTTP/1.1 303 See Other');
                header('Location: http://example.com/result.php' . "?p=" . $valPOutput);

            }
            catch (S3Exception $e) {
                die('Error:' . $e->getMessage());
            }
            catch (Exception $e) {
                die('Error:' . $e->getMessage());
            }
        }else {
          echo "arch too big";
        }
    }
}

?>

I've tried to do so adding event listeners to prevent submitting request, but when I upload a file, the website URL changes from https://example.com to https://example.com/awsUpload.php and the Progress Bar does not move and the Upload keeps going.

I'd like to receive some suggestions on how I can move or think to achieve that (the code I posted right now does not include any Progress bar test since I deleted the progress bar code cause it did not work).

EDIT DOWN HERE
Modified the form and added this new Script.
Right now the Load bar does work and the file gets uploaded, unfortunately I do not know why after the form gets submitted I do not get redirected to https://example.com/?p=****

  <form id="contact-form" action="awsUpload.php" method="post" name="frmImage" enctype="multipart/form-data">
     <input class="file-input" type="file" style="width:100%;"autocomplete="off" name="ftp" accept="image/*, .zip, .rar, .bzip" onchange="uploadFile(this.form)" class="file-up" id="fileFTP">

   <progress id="upload-progress" value="0" max="100"></progress>

  </form>

Extra: I tried to ad in the action of  if (xhr.status == 200) to redirect to a certain webpage with window.location but I'm missing the  $valPOutput from the awsUpload.php and do not know how to get it.


问:
Exception is thrown with Mockito but it is not caught in JUnit
I have a problem with a test case and cannot pass through it, tried to change some things but in any case the result is the same. I am pretty new to Mockito and to this kind of tests - so cannot understand what may be wrong.

Tried to do this way with a try catch block

```<code>@Test
public void shouldFailToRead_URLFileNotFound() throws IOException {

  URLConnection urlConnection = mock(URLConnection.class);
  fakedUrlStreamHandler.addConnection(URL_FILE_NOT_FOUND, urlConnection);

  FileNotFoundException fileNotFoundException = new FileNotFoundException("There is no such a file " + URL_FILE_NOT_FOUND);
  when(urlConnection.getInputStream()).thenThrow(fileNotFoundException);

  try {
    fileUpdater.downloadFile(fileUpdateListener, URL_FILE_NOT_FOUND);
    fail("Was expecting a RuntimeException with FileNotFoundException");
  } catch (RuntimeException e) {
    assertThat(e.getCause(), equalTo(fileNotFoundException));
  }
}
</code>```

The method that checks if an URL is alive

```<code>private boolean isUrlFileExists(final URL urlToDownload) {
  try {
    URLConnection connection = urlToDownload.openConnection();
    connection.getInputStream();
    return true;
  } catch (IOException e) {
    error("There is no file at " + urlToDownload + ". No Connection: " + e.getMessage(), e);
    throw new RuntimeException(e);
  }
}
</code>```

The line with fileUpdater.downloadFile have a nested call of methods until it get to isUrlFileExists.

Tried to do using expected keyword

```<code>(expected = FileNotFoundException.class)
</code>```

Also tried it with @Rule annotation

```<code>@Rule
public ExpectedException exceptionRule = ExpectedException.none();

exceptionRule.expect(FileNotFoundException.class);
</code>```

In any case I get the same error message

```<code>Exception in thread "FileDownloadThread" java.lang.RuntimeException: java.io.FileNotFoundException: There is no such a file http://somehost.com/download/file-not-found.zip
    at com.files.impl.FileUpdater$DownloadWorker.isUrlFileExists(FileUpdater.java:263)
    at com.files.impl.FileUpdater$DownloadWorker.makeDownloadAttempt(FileUpdater.java:285)
    at com.files.impl.FileUpdater$DownloadWorker.run(FileUpdater.java:324)
Caused by: java.io.FileNotFoundException: There is no such a file http://somehost.com/download/file-not-found.zip
    at java.net.URL.openStream(URL.java:1045)
    at com.files.impl.FileUpdater$DownloadWorker.isUrlFileExists(FileUpdater.java:258)
    ... 2 more

java.lang.AssertionError: Was expecting a RuntimeException with FileNotFoundException
</code>```

So in the end exception is thrown but it cannot be caught in my Test case, what I do wrong in here?

Originally tried to write the test this way, and register a URLStreamHandlerFactory for that using this post as an example, I am using Mockito 1.6 and locked in to this version.

Body:
I have a problem with a test case and cannot pass through it, tried to change some things but in any case the result is the same. I am pretty new to Mockito and to this kind of tests - so cannot understand what may be wrong.

Tried to do this way with a try catch block

@Test
public void shouldFailToRead_URLFileNotFound() throws IOException {

  URLConnection urlConnection = mock(URLConnection.class);
  fakedUrlStreamHandler.addConnection(URL_FILE_NOT_FOUND, urlConnection);

  FileNotFoundException fileNotFoundException = new FileNotFoundException("There is no such a file " + URL_FILE_NOT_FOUND);
  when(urlConnection.getInputStream()).thenThrow(fileNotFoundException);

  try {
    fileUpdater.downloadFile(fileUpdateListener, URL_FILE_NOT_FOUND);
    fail("Was expecting a RuntimeException with FileNotFoundException");
  } catch (RuntimeException e) {
    assertThat(e.getCause(), equalTo(fileNotFoundException));
  }
}

The method that checks if an URL is alive

private boolean isUrlFileExists(final URL urlToDownload) {
  try {
    URLConnection connection = urlToDownload.openConnection();
    connection.getInputStream();
    return true;
  } catch (IOException e) {
    error("There is no file at " + urlToDownload + ". No Connection: " + e.getMessage(), e);
    throw new RuntimeException(e);
  }
}

The line with fileUpdater.downloadFile have a nested call of methods until it get to isUrlFileExists.

Tried to do using expected keyword

(expected = FileNotFoundException.class)

Also tried it with @Rule annotation

@Rule
public ExpectedException exceptionRule = ExpectedException.none();

exceptionRule.expect(FileNotFoundException.class);

In any case I get the same error message

Exception in thread "FileDownloadThread" java.lang.RuntimeException: java.io.FileNotFoundException: There is no such a file http://somehost.com/download/file-not-found.zip
    at com.files.impl.FileUpdater$DownloadWorker.isUrlFileExists(FileUpdater.java:263)
    at com.files.impl.FileUpdater$DownloadWorker.makeDownloadAttempt(FileUpdater.java:285)
    at com.files.impl.FileUpdater$DownloadWorker.run(FileUpdater.java:324)
Caused by: java.io.FileNotFoundException: There is no such a file http://somehost.com/download/file-not-found.zip
    at java.net.URL.openStream(URL.java:1045)
    at com.files.impl.FileUpdater$DownloadWorker.isUrlFileExists(FileUpdater.java:258)
    ... 2 more

java.lang.AssertionError: Was expecting a RuntimeException with FileNotFoundException

So in the end exception is thrown but it cannot be caught in my Test case, what I do wrong in here?

Originally tried to write the test this way, and register a URLStreamHandlerFactory for that using this post as an example, I am using Mockito 1.6 and locked in to this version.


问:
I/flutter (25473): Failed host lookup: 'shamo-backend.buildwithangga.id' I/flutter (25473): Failed host lookup: 'shamo-backend.buildwithangga.id'
I/flutter (25473): Failed host lookup: 'shamo-backend.buildwithangga.id'

`

```<code>import 'package:altamazee/models/user_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class AuthService {
  String baseUrl = 'https://shamo-backend.buildwithangga.id/api';

  Future<UserModel> register({
    required String name,
    required String username,
    required String email,
    required String password,
  }) async {
    var url = '$baseUrl/register';
    var headers = {'Content-Type': 'application/json'};
    var body = jsonEncode({
      'name': name,
      'username': username,
      'email': email,
      'password': password,
    });

    var response = await http.post(
      Uri.parse('https://shamo-backend.buildwithangga.id/api'),
      headers: headers,
      body: body,
    );

    print(response.body);

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'];
      UserModel user = UserModel.fromJson(data['user']);
      user.token = 'Bearer ' + data['access_token'];

      return user;
    } else {
      throw Exception('Email sudah terdaftar');
    }
  }
}

</code>```

`

please helpme to solve this
please helpme to solve this
please helpme to solve this
please helpme to solve this

Body:
I/flutter (25473): Failed host lookup: 'shamo-backend.buildwithangga.id'

`

import 'package:altamazee/models/user_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class AuthService {
  String baseUrl = 'https://shamo-backend.buildwithangga.id/api';

  Future<UserModel> register({
    required String name,
    required String username,
    required String email,
    required String password,
  }) async {
    var url = '$baseUrl/register';
    var headers = {'Content-Type': 'application/json'};
    var body = jsonEncode({
      'name': name,
      'username': username,
      'email': email,
      'password': password,
    });

    var response = await http.post(
      Uri.parse('https://shamo-backend.buildwithangga.id/api'),
      headers: headers,
      body: body,
    );

    print(response.body);

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'];
      UserModel user = UserModel.fromJson(data['user']);
      user.token = 'Bearer ' + data['access_token'];

      return user;
    } else {
      throw Exception('Email sudah terdaftar');
    }
  }
}

`

please helpme to solve this
please helpme to solve this
please helpme to solve this
please helpme to solve this


问:
The bean 'jerseyTagsProvider' could not be registered A bean with that name has already been defined in class path resource and overriding is disabled
the issue is after updgrading from Java 11 to Java 17.
Spring-Boot upgraded to v2.7.4.
spock.version upgraded to 2.3-groovy-4.0
Thank you in advance.</p>


问:
How to trigger droppable from outside droppable area?
I have a To do app (created using react-forked/dnd) with multiple columns to move tasks when status is updated. I wish to allow dropping task card even when it is dropped over the header area of the column (which is outside the droppable area of the column). Need ideas about how to do this. Thanks!

Image explaining droppable & header areas:


问:
Event listener is not triggered when using with drop-down?
I am trying to trigger the event listener whenever the user selects anything from the dropdown but it is not working, I am using the select2 plugin for the dropdown.

I am trying to send some values through ajax whenever the user selects from the dropdown, but unfortunately, it is not triggering.

$(document).ready(function() {
  $(".select2").select2();

});

const select = document.querySelector('#Country');
const resultsContainer = document.querySelector('#results');
let currentIndex = 0;

select.addEventListener('change', function(event) {
  const countryId = event.target.value;
  console.log(countryId);
  console.log("hi");
   //ajax call here!
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<form>
  <select class="select2 form-control" name="Country" id="Country" data-live-search="true">
    <option value="Country" selected>---Select Country---</option>
    <option value="Ägypten">Ägypten (Egypt)</option>
    <option value="Argentinien">Argentinien (Argentinia)</option>
    <option value="Äthiopien">Äthiopien (Ethiopia)</option>
  </select>
</form></code>```

Body:
I am trying to trigger the event listener whenever the user selects anything from the dropdown but it is not working, I am using the select2 plugin for the dropdown.

I am trying to send some values through ajax whenever the user selects from the dropdown, but unfortunately, it is not triggering.

$(document).ready(function() {
  $(".select2").select2();

});

const select = document.querySelector('#Country');
const resultsContainer = document.querySelector('#results');
let currentIndex = 0;

select.addEventListener('change', function(event) {
  const countryId = event.target.value;
  console.log(countryId);
  console.log("hi");
   //ajax call here!
});

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>

<form>
  <select class="select2 form-control" name="Country" id="Country" data-live-search="true">
    <option value="Country" selected>---Select Country---</option>
    <option value="Ägypten">Ägypten (Egypt)</option>
    <option value="Argentinien">Argentinien (Argentinia)</option>
    <option value="Äthiopien">Äthiopien (Ethiopia)</option>
  </select>
</form>


问:
How can I spy static method's class in JUnit5?
I want to stub static method.

But if I use mockStatic(), whole methods are mocked.

How can I spy static method's class?

```<code>class StaticFoo {

  // Want to stub this method
  public static void wantToStub() { ... }

  // And don't want to stub this method
  public static void noStub() { ... }
}
</code>```

Body:
I want to stub static method.

But if I use mockStatic(), whole methods are mocked.

How can I spy static method's class?

class StaticFoo {

  // Want to stub this method
  public static void wantToStub() { ... }

  // And don't want to stub this method
  public static void noStub() { ... }
}


问:
I'm not able call the Listener Class,Whenever I tried to call Listener class it's Showing Errors
I'm not able call the Listener Class,Whenever I tried to call Listener class it's Showing Errors

I'm getting this error

Source Code

```<code>import tweepy
from tweepy import StreamListener
import json
import twitter_credentials
import sys
import csv

auth =tweepy.OAuthHandler(twitter_credentials.consumer_key,twitter_credentials.consumer_secret)
auth.set_access_token(twitter_credentials.access_token,twitter_credentials.access_token_secret)

api =tweepy.API(auth,wait_on_rate_limit=True)

try:
    api.verify_credentials()
    print("Authentication OK")
except:
    print("Error during authentication")

tweets =api.search_tweets(q="Python",lang="en")
#api.search_tweets(q="Python",lang="en",rpp=100)
for tweet in tweets:
    USER =tweet.user.name
    RETWEETS =tweet.retweet_count
    CREATED =tweet.created_at
    TEXT =tweet.text
    SOURCE =tweet.source
    print(USER +" | "+TEXT+" | "+str(RETWEETS)+ " | "+SOURCE)

class listener(tweepy.StreamListener):
    def __int__(self,passed_api):
        self.api =passed_api
        self.me= api.me()

    def on_status(self,tweet):
        USER = tweet.user.name
        RETWEETS = tweet.retweet_count
        CREATED = tweet.created_at
        TEXT = tweet.text
        SOURCE = tweet.source
        print(USER + " | " + TEXT + " | " + str(RETWEETS) + " | " + SOURCE)
        file =open("C:\\Users\\kishan chand\\PycharmProjects\\pythonProject2\\results\\tweets_extract.csv","a")
        output1 =USER+" | "+TEXT+" | "+str(RETWEETS)+" | "+SOURCE+ '\n'
        file.write(output1)
        file.close()

if __name__ =='__main__':
    tweets_listene =listener()
    auth = tweepy.OAuthHandler(twitter_credentials.consumer_key,
    twitter_credentials.consumer_secret)
    auth.set_access_token(twitter_credentials.access_token,
    twitter_credentials.access_token_secret)
    stream =tweepy.Stream(auth,twitter_credentials.access_token,
    twitter_credentials.access_token_secret,tweets_listene)
    stream.filter(track =["India","Python"])
</code>```

Basically,I'm trying to access the Stream Tweets with the help of Inherited StreamListener Class But I'm not able to call the Listener Class

Body:
I'm not able call the Listener Class,Whenever I tried to call Listener class it's Showing Errors

I'm getting this error

Source Code

import tweepy
from tweepy import StreamListener
import json
import twitter_credentials
import sys
import csv

auth =tweepy.OAuthHandler(twitter_credentials.consumer_key,twitter_credentials.consumer_secret)
auth.set_access_token(twitter_credentials.access_token,twitter_credentials.access_token_secret)

api =tweepy.API(auth,wait_on_rate_limit=True)

try:
    api.verify_credentials()
    print("Authentication OK")
except:
    print("Error during authentication")

tweets =api.search_tweets(q="Python",lang="en")
#api.search_tweets(q="Python",lang="en",rpp=100)
for tweet in tweets:
    USER =tweet.user.name
    RETWEETS =tweet.retweet_count
    CREATED =tweet.created_at
    TEXT =tweet.text
    SOURCE =tweet.source
    print(USER +" | "+TEXT+" | "+str(RETWEETS)+ " | "+SOURCE)

class listener(tweepy.StreamListener):
    def __int__(self,passed_api):
        self.api =passed_api
        self.me= api.me()

    def on_status(self,tweet):
        USER = tweet.user.name
        RETWEETS = tweet.retweet_count
        CREATED = tweet.created_at
        TEXT = tweet.text
        SOURCE = tweet.source
        print(USER + " | " + TEXT + " | " + str(RETWEETS) + " | " + SOURCE)
        file =open("C:\\Users\\kishan chand\\PycharmProjects\\pythonProject2\\results\\tweets_extract.csv","a")
        output1 =USER+" | "+TEXT+" | "+str(RETWEETS)+" | "+SOURCE+ '\n'
        file.write(output1)
        file.close()

if __name__ =='__main__':
    tweets_listene =listener()
    auth = tweepy.OAuthHandler(twitter_credentials.consumer_key,
    twitter_credentials.consumer_secret)
    auth.set_access_token(twitter_credentials.access_token,
    twitter_credentials.access_token_secret)
    stream =tweepy.Stream(auth,twitter_credentials.access_token,
    twitter_credentials.access_token_secret,tweets_listene)
    stream.filter(track =["India","Python"])

Basically,I'm trying to access the Stream Tweets with the help of Inherited StreamListener Class But I'm not able to call the Listener Class


问:
Improve CustomScrollView behavior
Behavior i want to achieve

Closest behavior i get

I tried using SliverPersistentHeader and SliverList inside CustomScrollView and achieved almost same behavior except one thing. SliverList is using background and not rounding it's coners. I need CustomScrollView to make one scrollable area to scroll SliverList from any part of screen.

Here is my code:

```<code>const double _kFlexibleFromHeight = 0.2;
const _kMainVerticalPadding = 20.0;
const _kMainHorizontalPadding = 15.0;

class SliverBottomSheet extends StatefulWidget {
  const SliverBottomSheet({Key? key}) : super(key: key);

  @override
  State<SliverBottomSheet> createState() => _SliverBottomSheetState();
}

class _SliverBottomSheetState extends State<SliverBottomSheet> {
  late final ScrollController _controller;
  @override
  void initState() {
    _controller = ScrollController()
      ..addListener(() {
        setState(() {});
      });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          colors: [
            AppColors.mainBluePurple,
            AppColors.bgLightOrange,
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          stops: [0.2, 0.43],
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: CustomScrollView(
          controller: _controller,
          slivers: [
            SliverPersistentHeader(
              delegate: _HeaderDelegate(
                  controller: _controller,
                  height: MediaQuery.of(context).size.height *
                      _kFlexibleFromHeight),
            ),
            //just wrapper to add Decoration to SliverList
            SliverGroupBuilder(
              decoration: const BoxDecoration(
                  color: Colors.blue,
                  borderRadius:
                      BorderRadius.vertical(top: Radius.circular(50))),
              child: SliverList(
                  delegate: SliverChildBuilderDelegate(
                      (ctx, index) => ListTile(
                            title: Text('tile $index'),
                          ),
                      childCount: 40)),
            ),
          ],
        ),
      ),
    );
  }
}

class _HeaderDelegate extends SliverPersistentHeaderDelegate {
  final ScrollController controller;
  final double height;

  _HeaderDelegate({
    required this.controller,
    required this.height,
  });

  double get topPadding => min(
        _kMainVerticalPadding * 2,
        max(
          0,
          _kMainVerticalPadding -
              (controller.hasClients ? controller.offset / 10 : 0),
        ),
      );

  double get bottomPadding => min(
        _kMainVerticalPadding * 2,
        max(
          0,
          _kMainVerticalPadding +
              (controller.hasClients ? controller.offset / 10 : 0),
        ),
      );

  double _getOpacity(BuildContext context) {
    double result = 1;
    if (!controller.hasClients) return result;
    result = 1 -
        (controller.offset /
            ((MediaQuery.of(context).size.height * 0.2) / 100) /
            100);
    if (result < 0) {
      result = 0;
    } else if (result > 1) {
      result = 1;
    }
    return result;
  }

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Stack(
      children: [
        Positioned(
          top: shrinkOffset,
          bottom: controller.offset > 0 ? 0 - shrinkOffset : null,
          left: 0,
          right: 0,
          child: Opacity(
            opacity: _getOpacity(context),
            child: SizedBox(
              height: height,
              child: ListView(
                padding: EdgeInsets.only(
                  top: topPadding,
                  bottom: bottomPadding,
                ),
                scrollDirection: Axis.horizontal,
                children: List.generate(
                    5,
                    (index) => Container(
                          margin: const EdgeInsets.all(4),
                          alignment: Alignment.center,
                          width: 100,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            color: Colors.white,
                          ),
                          child: Text('Child $index'),
                        )),
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
      true;
}
</code>```

Title: Improve CustomScrollView behavior

Body:
Behavior i want to achieve

Closest behavior i get

I tried using SliverPersistentHeader and SliverList inside CustomScrollView and achieved almost same behavior except one thing. SliverList is using background and not rounding it's coners. I need CustomScrollView to make one scrollable area to scroll SliverList from any part of screen.

Here is my code:

const double _kFlexibleFromHeight = 0.2;
const _kMainVerticalPadding = 20.0;
const _kMainHorizontalPadding = 15.0;

class SliverBottomSheet extends StatefulWidget {
  const SliverBottomSheet({Key? key}) : super(key: key);

  @override
  State<SliverBottomSheet> createState() => _SliverBottomSheetState();
}

class _SliverBottomSheetState extends State<SliverBottomSheet> {
  late final ScrollController _controller;
  @override
  void initState() {
    _controller = ScrollController()
      ..addListener(() {
        setState(() {});
      });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          colors: [
            AppColors.mainBluePurple,
            AppColors.bgLightOrange,
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          stops: [0.2, 0.43],
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: CustomScrollView(
          controller: _controller,
          slivers: [
            SliverPersistentHeader(
              delegate: _HeaderDelegate(
                  controller: _controller,
                  height: MediaQuery.of(context).size.height *
                      _kFlexibleFromHeight),
            ),
            //just wrapper to add Decoration to SliverList
            SliverGroupBuilder(
              decoration: const BoxDecoration(
                  color: Colors.blue,
                  borderRadius:
                      BorderRadius.vertical(top: Radius.circular(50))),
              child: SliverList(
                  delegate: SliverChildBuilderDelegate(
                      (ctx, index) => ListTile(
                            title: Text('tile $index'),
                          ),
                      childCount: 40)),
            ),
          ],
        ),
      ),
    );
  }
}

class _HeaderDelegate extends SliverPersistentHeaderDelegate {
  final ScrollController controller;
  final double height;

  _HeaderDelegate({
    required this.controller,
    required this.height,
  });

  double get topPadding => min(
        _kMainVerticalPadding * 2,
        max(
          0,
          _kMainVerticalPadding -
              (controller.hasClients ? controller.offset / 10 : 0),
        ),
      );

  double get bottomPadding => min(
        _kMainVerticalPadding * 2,
        max(
          0,
          _kMainVerticalPadding +
              (controller.hasClients ? controller.offset / 10 : 0),
        ),
      );

  double _getOpacity(BuildContext context) {
    double result = 1;
    if (!controller.hasClients) return result;
    result = 1 -
        (controller.offset /
            ((MediaQuery.of(context).size.height * 0.2) / 100) /
            100);
    if (result < 0) {
      result = 0;
    } else if (result > 1) {
      result = 1;
    }
    return result;
  }

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Stack(
      children: [
        Positioned(
          top: shrinkOffset,
          bottom: controller.offset > 0 ? 0 - shrinkOffset : null,
          left: 0,
          right: 0,
          child: Opacity(
            opacity: _getOpacity(context),
            child: SizedBox(
              height: height,
              child: ListView(
                padding: EdgeInsets.only(
                  top: topPadding,
                  bottom: bottomPadding,
                ),
                scrollDirection: Axis.horizontal,
                children: List.generate(
                    5,
                    (index) => Container(
                          margin: const EdgeInsets.all(4),
                          alignment: Alignment.center,
                          width: 100,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            color: Colors.white,
                          ),
                          child: Text('Child $index'),
                        )),
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
      true;
}


问:
What is the best way to allow end users to dynamically create mongo collections and manage their fields using mongoose?
I am trying to design a web application that will allow (empower) users to create their own mongo collections, manage the collection models (fields, types, references, and indexes), and perform basic CRUD operations on them. From a simple easy to use interface, the users can easily access and manipulate their data and customize various collections to their preferences (I'm surprised this wouldn't be more common - in Microsoft Sharepoint and Power Platform, for instance, users can create and customize Lists / Data tables and use them in a UI).
My initial strategy programmatically is for users to have a collections (array type) field in their user document that specifies each of their collections and its corresponding fields. For instance:

```<code>{
  _id: 'uid1',
  name: 'user1',
  collections: [
   {
     name: 'uid1_collection_tasks', // non-mutable
     fields: [
      {
        key: 'name',
        type: 'String'
      },
      {
        key: 'complete',
        type: 'Boolean'
      }
     ]
   }
  ]
}
</code>```

On app startup, or whenever the collections field is updated, the collections in each users document would be dynamically generated or updated. Similarly, users would send CRUD requests to the server indicating the collection name and query which would be validated against that users document.

```<code>function createModelFromUserCollection(collection) {
   var newSchema = new Schema({ }); // build schema object from collection.fields
   mongoose.model(collection.name, Any);
}
</code>```

My general question is whether or not this is a viable approach to accomplish it (or the concept even viable to begin with), and if not - what would an alternative be?
I also appreciate any general feedback on the concept and potential risks :)

Body:
I am trying to design a web application that will allow (empower) users to create their own mongo collections, manage the collection models (fields, types, references, and indexes), and perform basic CRUD operations on them. From a simple easy to use interface, the users can easily access and manipulate their data and customize various collections to their preferences (I'm surprised this wouldn't be more common - in Microsoft Sharepoint and Power Platform, for instance, users can create and customize Lists / Data tables and use them in a UI).
My initial strategy programmatically is for users to have a collections (array type) field in their user document that specifies each of their collections and its corresponding fields. For instance:

{
  _id: 'uid1',
  name: 'user1',
  collections: [
   {
     name: 'uid1_collection_tasks', // non-mutable
     fields: [
      {
        key: 'name',
        type: 'String'
      },
      {
        key: 'complete',
        type: 'Boolean'
      }
     ]
   }
  ]
}

On app startup, or whenever the collections field is updated, the collections in each users document would be dynamically generated or updated. Similarly, users would send CRUD requests to the server indicating the collection name and query which would be validated against that users document.

function createModelFromUserCollection(collection) {
   var newSchema = new Schema({ }); // build schema object from collection.fields
   mongoose.model(collection.name, Any);
}

My general question is whether or not this is a viable approach to accomplish it (or the concept even viable to begin with), and if not - what would an alternative be?
I also appreciate any general feedback on the concept and potential risks :)


问:
Field `state` does not exist in Odoo 13
view.xml

```<code><record id="fsm_order_form" model="ir.ui.view">
<field name="name">fsm.order.form</field>
<field name="model">fsm.order</field>
<field name="inherit_id" ref='fieldservice.fsm_order_form'/>
<field name="arch" type="xml">
    <xpath expr="//notebook/page[@name='planning_page']/group" position="after">
        <field name="planning_ids">
            <tree string='Planning'>
                <field name="employee_id"/>
                <field name="role_id"/>
                <field name="start_datetime"/>
                <field name="end_datetime"/>
                <field name="allocated_hours"/>
                <field name="wage"/>
            </tree>
        </field>

        <group>
            <group class="oe_subtotal_footer oe_right" name="planning_hours">
                <field name="planned_hours" widget="float_time"/>
                <field name="currency_id" invisible='1'/>
                <field name="planned_labour_cost" class="oe_subtotal_footer_separator" widget='monetary'
                        options="{'currency_field': 'currency_id'}"/>
            </group>
        </group>
    </xpath>
</field>
</code>```

__manifest__.py

```<code>'depends': ['base','web','mail','dms','project_stock_request','business_requirement','stock_request_customization','bi_job_cost_estimate_customer','planning','repair','project','quality_control','project_task_material','sale_timesheet','hr_timesheet','fieldservice','maintenance','mrp','maintenance_plan','bi_job_cost_estimate_customer'],
</code>```

I'm getting Field state does not exist in Odoo 13 when upgrading the module. This error was never raised before and code is not not even changed now.
The module fieldservice is already in dependency list in __manifest__.py. The model fsm.order is extended in another custom module adding the field state.

Title: Field `state` does not exist in Odoo 13

Body:
view.xml

<record id="fsm_order_form" model="ir.ui.view">
<field name="name">fsm.order.form</field>
<field name="model">fsm.order</field>
<field name="inherit_id" ref='fieldservice.fsm_order_form'/>
<field name="arch" type="xml">
    <xpath expr="//notebook/page[@name='planning_page']/group" position="after">
        <field name="planning_ids">
            <tree string='Planning'>
                <field name="employee_id"/>
                <field name="role_id"/>
                <field name="start_datetime"/>
                <field name="end_datetime"/>
                <field name="allocated_hours"/>
                <field name="wage"/>
            </tree>
        </field>

        <group>
            <group class="oe_subtotal_footer oe_right" name="planning_hours">
                <field name="planned_hours" widget="float_time"/>
                <field name="currency_id" invisible='1'/>
                <field name="planned_labour_cost" class="oe_subtotal_footer_separator" widget='monetary'
                        options="{'currency_field': 'currency_id'}"/>
            </group>
        </group>
    </xpath>
</field>

__manifest__.py

'depends': ['base','web','mail','dms','project_stock_request','business_requirement','stock_request_customization','bi_job_cost_estimate_customer','planning','repair','project','quality_control','project_task_material','sale_timesheet','hr_timesheet','fieldservice','maintenance','mrp','maintenance_plan','bi_job_cost_estimate_customer'],

I'm getting Field state does not exist in Odoo 13 when upgrading the module. This error was never raised before and code is not not even changed now.
The module fieldservice is already in dependency list in __manifest__.py. The model fsm.order is extended in another custom module adding the field state.


问:
Chrome always comes to the fore when the automation bot is running
I am a Python developer which is writing a automated bots for my requirements. I switched my OS to Fedora from Windows a month ago. After I finished my Fedora familiarization process, I tried to get my bots to work, but I ran into a problem.

There is no problem with the working or performance of the bots. However, if a new tab is opened while the bots are running in the background, they always put Google Chrome at the top.

My bots that work without opening a new tab can still work in the background, but when Chrome switch to a new tab or close the tab are constantly coming to the front and bothering me.

While using Windows, Chrome was sending a red notification below during this process and it didn't bother me. Is this a problem with my new operating system? Is there a solution to this?

thanks in advance

I tried the close the notifications of Google Chrome from GNOME Settings but nothing changed. Explore in the Chrome settings to find something but find nothing.


问:
In Loopback4 repository, mongodb as datasource, how to query on a array field
In loopback4 application, which is using mongodb as datasource.
Repository myRepo has a field userIDs of type string array, How to find all all records where a given userID abc is in userIDs array?

Given these records

```<code>name:"A",userIDs:["abc"]
name:"B",userIDs:["abc","xyz"]
name:"C",userIDs:["abc","def"]
name:"D",userIDs:["xyz","def"]
</code>```

Expected result, when search for abc

```<code>name:"A",userIDs:["abc"]
name:"B",userIDs:["abc","xyz"]
name:"C",userIDs:["abc","def"]
</code>```

Tried this,

```<code>this.myRepo.find({where: {userIDs: {inq: [["abc"]]}}});
</code>```

But this returns only

```<code>name:"A",userIDs:["abc"]
</code>```

Couldn't locate any such example here in loopback4 query documentation.

Body:
In loopback4 application, which is using mongodb as datasource.
Repository myRepo has a field userIDs of type string array, How to find all all records where a given userID abc is in userIDs array?

Given these records

name:"A",userIDs:["abc"]
name:"B",userIDs:["abc","xyz"]
name:"C",userIDs:["abc","def"]
name:"D",userIDs:["xyz","def"]

Expected result, when search for abc

name:"A",userIDs:["abc"]
name:"B",userIDs:["abc","xyz"]
name:"C",userIDs:["abc","def"]

Tried this,

this.myRepo.find({where: {userIDs: {inq: [["abc"]]}}});

But this returns only

name:"A",userIDs:["abc"]

Couldn't locate any such example here in loopback4 query documentation.


问:
AWS DMS doesn't migrate the some special characters in data properly
I'm trying to perform a homogenous migration (both source and target DB is AWS Aurora MySQL) using AWS DMS. After running the task, it executes properly and migrates whole data. Since, I've turned validations on, I can see some validation failures. On looking further into validation failures I found that some special characters are not being migrated properly by DMS.

For example,

```<code>Table column: jsondata
Value in source DB: {'key1': 'some data ?'}
after migration looks something like:
Value in target DB: {'key1': 'some data [SUB]'}
</code>```

Happening only for special characters. Can someone help me understand why this is happening and what's the solution? I want a complete duplication of data.

Body:
I'm trying to perform a homogenous migration (both source and target DB is AWS Aurora MySQL) using AWS DMS. After running the task, it executes properly and migrates whole data. Since, I've turned validations on, I can see some validation failures. On looking further into validation failures I found that some special characters are not being migrated properly by DMS.

For example,

Table column: jsondata
Value in source DB: {'key1': 'some data ?'}
after migration looks something like:
Value in target DB: {'key1': 'some data [SUB]'}

Happening only for special characters. Can someone help me understand why this is happening and what's the solution? I want a complete duplication of data.


问:
Is there a way, a variables set by zalando.org/skipper-filter in the Ingress object to be used in Daemonset object in Kubernetes?
I am trying to find a way to use the values set by zalando.org/skipper=filter in the Skipper Ingress object and reference that value in the Daemonset object.

For example, if I used the following filter chain in a Ingress object:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: demo
  annotations:
    zalando.org/skipper-filter: setQuery("abc", "xyz") -> oauthGrant()

</code>```

And i am trying to reference the values set in the setQuery in the args tag in the Daemonset like

"-oauth2-client-secret=$(request.query.abc)"

I want the client secret to be have a value set in the filter section of the ingress object.
I've tried bunch of other filters but nothing has worked till now. Or maybe I haven't understood how filter works. Anyone know anything about this?

Body:
I am trying to find a way to use the values set by zalando.org/skipper=filter in the Skipper Ingress object and reference that value in the Daemonset object.

For example, if I used the following filter chain in a Ingress object:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: demo
  annotations:
    zalando.org/skipper-filter: setQuery("abc", "xyz") -> oauthGrant()

And i am trying to reference the values set in the setQuery in the args tag in the Daemonset like

"-oauth2-client-secret=$(request.query.abc)"

I want the client secret to be have a value set in the filter section of the ingress object.
I've tried bunch of other filters but nothing has worked till now. Or maybe I haven't understood how filter works. Anyone know anything about this?