问:
How do I make request to a dns server?
I am trying to get a data response using a socket. I need any kind of response from the DNS. So I try requesting the IP of "www.youtube.com" from google DNS. I am not getting any response.

```<code>Network network = ...
String DNS = "8.8.8.8";
try (Socket socket = network.getSocketFactory().createSocket(DNS, 53)) {
    socket.connect(new InetSocketAddress("www.youtube.com", 80));
    InputStreamReader input = new InputStreamReader(socket.getInputStream());
    BufferedReader reader = new BufferedReader(input);
    socket.getOutputStream().write("www.youtube.com".getBytes());
    String skip = reader.readLine(), string = reader.readLine();
    Log.e("READ", skip + " " + string);
} catch (IOException exception) {
    String message = context.getText(R.string.nointernet) + ": " +
    exception.getLocalizedMessage();
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    context.getVariables().setNetwork(null);
}
</code>```

In this case, the log is always printing null which means I haven't communicated with the DNS server.
How can a make the socket request?

Title: How do I make request to a dns server?

Body:
I am trying to get a data response using a socket. I need any kind of response from the DNS. So I try requesting the IP of "www.youtube.com" from google DNS. I am not getting any response.

Network network = ...
String DNS = "8.8.8.8";
try (Socket socket = network.getSocketFactory().createSocket(DNS, 53)) {
    socket.connect(new InetSocketAddress("www.youtube.com", 80));
    InputStreamReader input = new InputStreamReader(socket.getInputStream());
    BufferedReader reader = new BufferedReader(input);
    socket.getOutputStream().write("www.youtube.com".getBytes());
    String skip = reader.readLine(), string = reader.readLine();
    Log.e("READ", skip + " " + string);
} catch (IOException exception) {
    String message = context.getText(R.string.nointernet) + ": " +
    exception.getLocalizedMessage();
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    context.getVariables().setNetwork(null);
}

In this case, the log is always printing null which means I haven't communicated with the DNS server.
How can a make the socket request?


来源: stackexchange

问:
python-telegram-bot: The last sent message is not a document
I have problem to download files from my private chat.
I've added a bot as administrator to my private chat.
To upload on telegram with a python script I have no problems, for example I use successfully this code

```<code>import os
import telegram

# Enter your bot's token here
TOKEN = "58819**********************....."

# Enter your private chat ID here
CHAT_ID = -100****...

# Enter the path to the document here
DOCUMENT_PATH = "C:\\temp\\telegram\\snow.epub"

# Create a Bot object using the token
bot = telegram.Bot(token=TOKEN)

# Open the document in binary mode
with open(DOCUMENT_PATH, "rb") as f:
    # Send the document to the specified chat
    bot.send_document(chat_id=CHAT_ID, document=f)

print("Document sent successfully!")
</code>```

Problem is download this file (an epub file) from my private chat
i try with this code but nothing happens, powershell returns me this message

```<code>PS C:\temp\telegram> python scaricare2.py
The last sent message is not a document.
</code>```

I test with this code

```<code>import os
import os.path
import telegram

# Enter your bot's token here
TOKEN = "588199*****************..."

# Enter your private chat ID here
CHAT_ID = -1001******...

# Create a Bot object using the token
bot = telegram.Bot(token=TOKEN)

# Download the latest file sent in the chat
updates = bot.get_updates(offset=-1, limit=1)
if updates:
    # Checks if the Message object contains a document attribute
    if hasattr(updates[0].message, "document"):
        file_id = updates[0].message.document.file_id
    else:
        print("The last sent message is not a document.")
        exit()

    file_info = bot.get_file(file_id)
    file = bot.download_file(file_info.file_path)

    # Create the path to the directory where to save the file
    download_path = "C:/temp/telegram/filexx/"

    # Create the full path to the file using the file name
    file_path = os.path.join(download_path, file_info.file_name)

    # Open the file in binary write mode
    with open(file_path, "wb") as f:
        # Write the contents of the file to the specified path
        f.write(file)
    print("File downloaded successfully!")
else:
    print("The last sent message is not a document.")
</code>```

Any idea to solve ?

Download from bot returns this error

```<code>PS C:\temp\telegram> python scaricare2.py
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 402, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 398, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Program Files\Python310\lib\http\client.py", line 1374, in getresponse
    response.begin()
  File "C:\Program Files\Python310\lib\http\client.py", line 318, in begin
    version, status, reason = self._read_status()
  File "C:\Program Files\Python310\lib\http\client.py", line 279, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Program Files\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
  File "C:\Program Files\Python310\lib\ssl.py", line 1273, in recv_into
    return self.read(nbytes, buffer)
  File "C:\Program Files\Python310\lib\ssl.py", line 1129, in read
    return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 259, in _request_wrapper
    resp = self._con_pool.request(*args, **kwargs)
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 68, in request
    return self.request_encode_body(method, url, fields=fields,
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 148, in request_encode_body
    return self.urlopen(method, url, **extra_kw)
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\poolmanager.py", line 244, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 665, in urlopen
    retries = retries.increment(method, url, error=e, _pool=self,
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\retry.py", line 347, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\packages\six.py", line 686, in reraise
    raise value
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 614, in urlopen
    httplib_response = self._make_request(conn, method, url,
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 404, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout,
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 321, in _raise_timeout
    raise exc_cls(*args)
telegram.vendor.ptb_urllib3.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=5.0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\temp\telegram\scaricare2.py", line 24, in <module>
    file_info = bot.get_file(file_id)
  File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 134, in decorator
    result = func(*args, **kwargs)
  File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 2510, in get_file
    result = self._post('getFile', data, timeout=timeout, api_kwargs=api_kwargs)
  File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 299, in _post
    return self.request.post(
  File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 361, in post
    result = self._request_wrapper(
  File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 261, in _request_wrapper
    raise TimedOut() from error
telegram.error.TimedOut: Timed out
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have problem to download files from my private chat.
I've added a bot as administrator to my private chat.
To upload on telegram with a python script I have no problems, for example I use successfully this code

import os
import telegram

# Enter your bot's token here
TOKEN = "58819**********************....."

# Enter your private chat ID here
CHAT_ID = -100****...

# Enter the path to the document here
DOCUMENT_PATH = "C:\\temp\\telegram\\snow.epub"

# Create a Bot object using the token
bot = telegram.Bot(token=TOKEN)

# Open the document in binary mode
with open(DOCUMENT_PATH, "rb") as f:
    # Send the document to the specified chat
    bot.send_document(chat_id=CHAT_ID, document=f)

print("Document sent successfully!")

Problem is download this file (an epub file) from my private chat
i try with this code but nothing happens, powershell returns me this message

PS C:\temp\telegram> python scaricare2.py
The last sent message is not a document.

I test with this code

import os
import os.path
import telegram

# Enter your bot's token here
TOKEN = "588199*****************..."

# Enter your private chat ID here
CHAT_ID = -1001******...

# Create a Bot object using the token
bot = telegram.Bot(token=TOKEN)

# Download the latest file sent in the chat
updates = bot.get_updates(offset=-1, limit=1)
if updates:
    # Checks if the Message object contains a document attribute
    if hasattr(updates[0].message, "document"):
        file_id = updates[0].message.document.file_id
    else:
        print("The last sent message is not a document.")
        exit()

    file_info = bot.get_file(file_id)
    file = bot.download_file(file_info.file_path)

    # Create the path to the directory where to save the file
    download_path = "C:/temp/telegram/filexx/"

    # Create the full path to the file using the file name
    file_path = os.path.join(download_path, file_info.file_name)

    # Open the file in binary write mode
    with open(file_path, "wb") as f:
        # Write the contents of the file to the specified path
        f.write(file)
    print("File downloaded successfully!")
else:
    print("The last sent message is not a document.")

Any idea to solve ?

Download from bot returns this error

PS C:\temp\telegram> python scaricare2.py
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 402, in _make_request
    six.raise_from(e, None)
  File "<string>", line 2, in raise_from
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 398, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Program Files\Python310\lib\http\client.py", line 1374, in getresponse
    response.begin()
  File "C:\Program Files\Python310\lib\http\client.py", line 318, in begin
    version, status, reason = self._read_status()
  File "C:\Program Files\Python310\lib\http\client.py", line 279, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Program Files\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
  File "C:\Program Files\Python310\lib\ssl.py", line 1273, in recv_into
    return self.read(nbytes, buffer)
  File "C:\Program Files\Python310\lib\ssl.py", line 1129, in read
    return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 259, in _request_wrapper
    resp = self._con_pool.request(*args, **kwargs)
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 68, in request
    return self.request_encode_body(method, url, fields=fields,
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 148, in request_encode_body
    return self.urlopen(method, url, **extra_kw)
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\poolmanager.py", line 244, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 665, in urlopen
    retries = retries.increment(method, url, error=e, _pool=self,
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\retry.py", line 347, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\packages\six.py", line 686, in reraise
    raise value
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 614, in urlopen
    httplib_response = self._make_request(conn, method, url,
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 404, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout,
  File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 321, in _raise_timeout
    raise exc_cls(*args)
telegram.vendor.ptb_urllib3.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=5.0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\temp\telegram\scaricare2.py", line 24, in <module>
    file_info = bot.get_file(file_id)
  File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 134, in decorator
    result = func(*args, **kwargs)
  File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 2510, in get_file
    result = self._post('getFile', data, timeout=timeout, api_kwargs=api_kwargs)
  File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 299, in _post
    return self.request.post(
  File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 361, in post
    result = self._request_wrapper(
  File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 261, in _request_wrapper
    raise TimedOut() from error
telegram.error.TimedOut: Timed out


问:
How to quickly send an int from same app on one device to another device?
I have an idea for an app, but it requires near-instant transmission (much less than 2 second delay) of an int 1-5000 to another device.  The basic premise is that one user long-presses a button for a certain amount of time, I measure that time, then upon finger release display a picture on the other device for n milliseconds.

I also need to be able to scale this from 2 users to upto maybe 500 at the same time ideally? Or if that doesn't work "broadcast" the int to all device simultaneously, that's also acceptable.

I have done this successfully using TCP/UDP sockets and it worked great and smoothly, but only for 2 users at the same time.  It hurts my brain trying to figure out how to scale it up, and the source code for that is long gone anyways, I could make it again in a couple days if sockets is the only solution, but trying to see if anyone has any other ideas.

So basically, what is the easiest and relatively low latency method to give my app running on another device an int?  Even one word hints are highly appreciated.

I'm familiar with Android Development Studio and have basic (uni level) knowledge of java.


问:
Referencing from a list of models to run predictions against a test set with corresponding categories
I have a dataset that consists of a response variable, time variable, and categorical variable(location) and I'm trying to output predictions against a test set containing the categorical variables and time variable.  My solution was to create a list of lm models corresponding to each of the categories with:

```<code>model_list <- list()

 all_models <- for (name in names(groups)) {
       group <- groups[[name]]
       model <- lm(response ~ date, data = group)
       model_list[[name]] <- model
   }
</code>```

Then for each categorical value of test set use the corresponding model to predict the provided time value with:

```<code>> for (i in 1:nrow(test)) {
     category <- test[i, "cfips"]
     model <- model_list[[category]]

     prediction <- predict(model, newdata = test[i,])
     print(paste("Prediction for row", i, ":", prediction))
 }
</code>```
```<code>Error in model_list[[category]] : invalid subscript type 'list'
</code>```

Even when I change it to model <- unlist(model_list[[category]]) it gives me the same error about it being a list.  I don't think unlisting it is the solution either because when I check the output of unlist(model_list) it just turns the model list of 3000 into another list of 900,000 elements because it ungroups the model components.  Any way to work around this or just a better way to predict with a list of models?

Tried using unlist() since 'list' type is invalid but continues to act as a list

Edit: I was able to get passed the "list" error by adding the unlist() to the

category <- test[i, "cfips"]

My new problem is an error in model_list[[category]] : subscript out of bounds

It runs smoothly from lines 1-94 and that's where it hits the error.  The problem is that nrow(test) is 25000 but length(model_list) is only 3000. The categorical value has skips so while the length of the model list is 3000, it is still made up of models named as 1001 up to 25000 just with skipped numbers.  It is correct about it being out of bounds because it is using the length of the list as its bounds but nowhere do I reference the length of the list.

Body:
I have a dataset that consists of a response variable, time variable, and categorical variable(location) and I'm trying to output predictions against a test set containing the categorical variables and time variable.  My solution was to create a list of lm models corresponding to each of the categories with:

model_list <- list()

 all_models <- for (name in names(groups)) {
       group <- groups[[name]]
       model <- lm(response ~ date, data = group)
       model_list[[name]] <- model
   }

Then for each categorical value of test set use the corresponding model to predict the provided time value with:

> for (i in 1:nrow(test)) {
     category <- test[i, "cfips"]
     model <- model_list[[category]]

     prediction <- predict(model, newdata = test[i,])
     print(paste("Prediction for row", i, ":", prediction))
 }

Error in model_list[[category]] : invalid subscript type 'list'

Even when I change it to model <- unlist(model_list[[category]]) it gives me the same error about it being a list.  I don't think unlisting it is the solution either because when I check the output of unlist(model_list) it just turns the model list of 3000 into another list of 900,000 elements because it ungroups the model components.  Any way to work around this or just a better way to predict with a list of models?

Tried using unlist() since 'list' type is invalid but continues to act as a list

Edit: I was able to get passed the "list" error by adding the unlist() to the

category <- test[i, "cfips"]

My new problem is an error in model_list[[category]] : subscript out of bounds

It runs smoothly from lines 1-94 and that's where it hits the error.  The problem is that nrow(test) is 25000 but length(model_list) is only 3000. The categorical value has skips so while the length of the model list is 3000, it is still made up of models named as 1001 up to 25000 just with skipped numbers.  It is correct about it being out of bounds because it is using the length of the list as its bounds but nowhere do I reference the length of the list.


问:
How do you properly redirect using Remix Forms?
TL;DR: When I select an item from the drop down it is not redirecting me to the correct page.

I'm making a photo sharing website and I'm using Remix and the url to render all the data on the pages.
Here is a screenshot to give you a better idea:
Main page draft UI

So when the user selects North America from the Continent drop down menu it will navigate to /north-america and then the Continent menu drop down will have North America selected and the Country drop down menu will display all countries in North America (that exist in my database) as well as the breadcrumbs (breadcrumbs is working) and so on.

Here is the relevant code:

```<code>export async function loader({ request, params }: LoaderArgs) {
  const [{ data: continents }, { data: countries }, { data: regions }] =
    await Promise.all([
      supabase.from("continents").select("*"),
      supabase.from("countries").select("name, slug, continent( name, slug )"),
      supabase
        .from("regions")
        .select("name, slug, country (name, slug, continent (name, slug)))"),
    ]);

  return json({
    user: await getUser(request),
    continents,
    countries,
    regions,
  });
}

export async function action({ request }: ActionArgs) {
  const body = await request.formData();
  const continent = body.get("continent") as string;
  const country = body.get("country") as string;
  const region = body.get("region") as string;

  const location = continent || country || region || "/";
  const result = redirect(location);
  return result;
}

export default function App() {
  const data = useLoaderData();
  const params = useParams();
  const submit = useSubmit();
  const [state, setState] = useState(params);

  function handleChange(event: { currentTarget: FormData }) {
    submit(event.currentTarget, { replace: true });
  }

  return (
    <>
      <html lang="en" className="h-full">
        <head>
          <Combobox photos={photos} />
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <Meta />
          <Links />
        </head>
        <body className="h-full">
          <NavBar />
          <Breadcrumbs location={params} />
          <div className="grid grid-cols-5 gap-1 md:grid-cols-5">
            <Form method="post" onChange={handleChange}>
              {/* Continent Selector */}
              <div className="mx-auto flex max-w-7xl py-10 sm:px-4 lg:px-4">
                <div className="flex-auto pr-10">
                  <label
                    htmlFor="continent"
                    className="block text-sm font-medium text-gray-700"
                  >
                    Continent
                  </label>
                  <select
                    id="continent"
                    title="continent"
                    name="location"
                    className="mt-1 block w-full rounded-md border-gray-300 py-2 pl-3 text-base focus:border-indigo-500 focus:outline-none focus:ring-indigo-500 sm:text-sm"
                    value={state.continent}
                    onChange={(event) =>
                      setState({ Continent: event.target.value })
                    }
                  >
                    <option value="">Select a continent...</option>
                    {data.continents?.map((continent, index) => (
                      <option value={continent.slug} key={index}>
                        {continent.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </Form>
</code>```

I've tried everything I can think of but I'm very new to react so I'm sure I'm missing something basic here.

Body:
TL;DR: When I select an item from the drop down it is not redirecting me to the correct page.

I'm making a photo sharing website and I'm using Remix and the url to render all the data on the pages.
Here is a screenshot to give you a better idea:
Main page draft UI

So when the user selects North America from the Continent drop down menu it will navigate to /north-america and then the Continent menu drop down will have North America selected and the Country drop down menu will display all countries in North America (that exist in my database) as well as the breadcrumbs (breadcrumbs is working) and so on.

Here is the relevant code:

export async function loader({ request, params }: LoaderArgs) {
  const [{ data: continents }, { data: countries }, { data: regions }] =
    await Promise.all([
      supabase.from("continents").select("*"),
      supabase.from("countries").select("name, slug, continent( name, slug )"),
      supabase
        .from("regions")
        .select("name, slug, country (name, slug, continent (name, slug)))"),
    ]);

  return json({
    user: await getUser(request),
    continents,
    countries,
    regions,
  });
}

export async function action({ request }: ActionArgs) {
  const body = await request.formData();
  const continent = body.get("continent") as string;
  const country = body.get("country") as string;
  const region = body.get("region") as string;

  const location = continent || country || region || "/";
  const result = redirect(location);
  return result;
}

export default function App() {
  const data = useLoaderData();
  const params = useParams();
  const submit = useSubmit();
  const [state, setState] = useState(params);

  function handleChange(event: { currentTarget: FormData }) {
    submit(event.currentTarget, { replace: true });
  }

  return (
    <>

          <Combobox photos={photos} />
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <Meta />
          <Links />

          <NavBar />
          <Breadcrumbs location={params} />

            <Form method="post" onChange={handleChange}>
              {/* Continent Selector */}

                    Continent

                  <select
                    id="continent"
                    title="continent"
                    name="location"
                    className="mt-1 block w-full rounded-md border-gray-300 py-2 pl-3 text-base focus:border-indigo-500 focus:outline-none focus:ring-indigo-500 sm:text-sm"
                    value={state.continent}
                    onChange={(event) =>
                      setState({ Continent: event.target.value })
                    }
                  >
                    <option value="">Select a continent...</option>
                    {data.continents?.map((continent, index) => (
                      <option value={continent.slug} key={index}>
                        {continent.name}
                      </option>
                    ))}
                  </select>

            </Form>

I've tried everything I can think of but I'm very new to react so I'm sure I'm missing something basic here.


问:
Getting TimeoutError: Navigation timeout of 30000 ms exceeded
I don't know why my browser is giving me timeout, it's kind of slow because I'm using proxies but I have set on the launch options that the timeout should be 0

```<code>    const browser = await puppeteer.launch({
        headless: false,
        args: ['--proxy-server=http://ip:port'],
        timeout: 0
      });
</code>```

Anyone knows how can i fix this? thanks

I expected the browser not to crash (close) after 30000 ms , but it's giving me timeout

Body:
I don't know why my browser is giving me timeout, it's kind of slow because I'm using proxies but I have set on the launch options that the timeout should be 0

    const browser = await puppeteer.launch({
        headless: false,
        args: ['--proxy-server=http://ip:port'],
        timeout: 0
      });

Anyone knows how can i fix this? thanks

I expected the browser not to crash (close) after 30000 ms , but it's giving me timeout


问:
PeriodicWorkRequest is executing mulitiple times instead of single time withing time span
I have used 15 minutes in second parameter as minimum period length of 15 minutes.But app is calling backgroun service multiple times within 15 minutes of span instead of running once in 15 minutes

val periodicWorkRequest = PeriodicWorkRequest.Builder(DownloadingWorker::class.java,15,TimeUnit.MINUTES)
.build()
WorkManager.getInstance(applicationContext).enqueue(periodicWorkRequest)


问:
Errors updating project NuGet packages
It'a gotten a little scary to update all my NuGet packages as I always seem to have errors after I do.

I just did this now and had two issues.

I'm getting about a dozen of the following error.

Warning CS8032 An instance of analyzer Microsoft.CodeAnalysis.CSharp.Analyzers.FixAnalyzers.CSharpFixerWithFixAllAnalyzer cannot be created from C:\Users\jwood.nuget\packages\microsoft.codeanalysis.analyzers\1.1.0\analyzers\dotnet\cs\Microsoft.CodeAnalysis.CSharp.Analyzers.dll: Could not load type 'Microsoft.CodeAnalysis.Analyzers.FixAnalyzers.FixerWithFixAllAnalyzer`1' from assembly 'Microsoft.CodeAnalysis.Analyzers, Version=3.3.3.10305, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

I had some compatibility errors and several packages that refused to install. On closer inspection, I see the package manager is trying to install version 7 libraries when my project uses .NET 6. Why would Package Manager want to install incompatible libraries?

Title: Errors updating project NuGet packages


问:
Using an Openmote-B ADC
I'm working on signal acquisition and transmission using Openmote-B. I have an analogue signal from a sensor, that is to be transmitted using an openmote. Is it possible to directly feed the analog data to the Openmote? How can I use the inbuild ADC in CC2538 for this purpose?
Thank You.

I'm new to this Communication side. I have gone through the data sheets and other available sources about Openmote-B. I'm expecting to know how I can use the available ADC in the SoC and get resources related with it.

Title: Using an Openmote-B ADC


问:
WebStorm does not see the aliases of SASS files in Nuxt 3
How to make WebStorm read the alias specified in nuxt.config.ts for SASS files?

// nuxt.config.ts
export default defineNuxtConfig({
  srcDir: "src/",
  alias: {
    "@vuetify-variables": fileURLToPath(
      new URL("./src/assets/scss/libs/vuetify/_variables.scss", import.meta.url)
    ),
    scss: fileURLToPath(new URL("./src/assets/scss", import.meta.url)),
  },
  ...
});
```
<p>Usage:</p>
<pre class="lang-js prettyprint-override"><code>@use '@vuetify-variables' as vuetify-variables;
</code>```

WebStorm 2022.2.3

Nuxt 3.2.2

Body:
How to make WebStorm read the alias specified in nuxt.config.ts for SASS files?

// nuxt.config.ts
export default defineNuxtConfig({
  srcDir: "src/",
  alias: {
    "@vuetify-variables": fileURLToPath(
      new URL("./src/assets/scss/libs/vuetify/_variables.scss", import.meta.url)
    ),
    scss: fileURLToPath(new URL("./src/assets/scss", import.meta.url)),
  },
  ...
});

Usage:

@use '@vuetify-variables' as vuetify-variables;

WebStorm 2022.2.3

Nuxt 3.2.2


问:
Input from website link same as API in Cloudflare Worker
I am using Cloudflare worker scripts for generating the MD5 hash for extra security steps for user authorization in my server.

I have viewed the code from other StackOverflow question
(Not able to create MD5 Hash on Cloudflare Worker Script):

```<code>addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const message = "hi"
  const msgUint8 = new TextEncoder().encode(message)
  const hashBuffer = await crypto.subtle.digest('MD5', msgUint8)
  const hashArray = Array.from(new Uint8Array(hashBuffer))
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')

  return new Response(hashHex, {status: 200})
}
</code>```

The input of the hash needs to be changed manually cause it is inside the code, declared in a variable. What I want that the code automatically gets the string from the link same as API, like if I access https://example.example.workers.dev/&string=hi or something related, it will get the string hi, then put it into the code, and after that get an MD5 hash 6152496c47126ba1079afd2a0b63645d.

Can someone help me to solve this problem?

Body:
I am using Cloudflare worker scripts for generating the MD5 hash for extra security steps for user authorization in my server.

I have viewed the code from other StackOverflow question
(Not able to create MD5 Hash on Cloudflare Worker Script):

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const message = "hi"
  const msgUint8 = new TextEncoder().encode(message)
  const hashBuffer = await crypto.subtle.digest('MD5', msgUint8)
  const hashArray = Array.from(new Uint8Array(hashBuffer))
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')

  return new Response(hashHex, {status: 200})
}

The input of the hash needs to be changed manually cause it is inside the code, declared in a variable. What I want that the code automatically gets the string from the link same as API, like if I access https://example.example.workers.dev/&string=hi or something related, it will get the string hi, then put it into the code, and after that get an MD5 hash 6152496c47126ba1079afd2a0b63645d.

Can someone help me to solve this problem?


问:
ClientError: An error occurred (ForbiddenException) when calling the Publish operation: None ( in AWS SAM application (python))
I am developing an AWS SAM application where I am creating all the resources using SAM application's template.yaml file.

The application's flow goes like below:

Subscribe to a AWS IOT Topic --> Kinesis Stream --> AWS Lambda Function
--> Publish data to another AWS IOT Topic

The whole flow is built by now but, the AWS cloudWatch shows the following error when I am trying to publish some data to another topic using Boto3. (I think it may be a permission case like giving permissions to AWS IOT core & AWS Kinesis at the same time)

------ AWS CLoudWatch Log ------

```<code>[ERROR] ClientError: An error occurred (ForbiddenException) when calling the
Publish operation: None

Traceback (most recent call last):
  File "/var/task/app.py", line 8, in lambda_handler
    payload_to_device(deviceId)

  File "/var/task/app.py", line 10, in payload_to_device
    client.publish(

  File "/var/task/botocore/client.py", line 530, in _api_call
    return self._make_api_call(operation_name, kwargs)

  File "/var/task/botocore/client.py", line 960, in _make_api_call
    raise error_class(parsed_response, operation_name)
</code>```

------ Template.yaml file ------

```<code>    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Description: >
      KinesisStream

      Sample SAM Template for KinesisStream

    Globals:
      Function:
        Timeout: 3

    Resources:
      HelloWorldFunction:
        Type: AWS::Serverless::Function
        Properties:
          CodeUri: hello_world/
          Handler: app.lambda_handler
          Runtime: python3.9
          Architectures:
            - x86_64
          Events:
            Stream:
              Type: Kinesis
              Properties:
                Stream: !GetAtt KinesisStream.Arn
                StartingPosition: LATEST
                BatchSize: 5
                MaximumBatchingWindowInSeconds: 5
          Role: !GetAtt LambdaRole.Arn

      LambdaRole:
        Type: AWS::IAM::Role
        Properties:
          AssumeRolePolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Principal:
                  Service:
                    - "lambda.amazonaws.com"
                Action:
                  - 'sts:AssumeRole'
          Path: /
          ManagedPolicyArns:
            - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
          Policies:
            - PolicyName: "LambdaPolicy"
              PolicyDocument:
                Version: "2012-10-17"
                Statement:
                  - Effect: Allow
                    Action:
                      - 'iot:Publish'
                      - 'kinesis:PutRecord'
                    Resource: '*'
      KinesisStream:
        Type: AWS::Kinesis::Stream
        Properties:
          ShardCount: 1

      KinesisStreamRole:
        Type: AWS::IAM::Role
        Properties:
          AssumeRolePolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Principal:
                  Service:
                    - iot.amazonaws.com
                Action:
                  - 'sts:AssumeRole'
          Path: /
          Policies:
            - PolicyName: KinesisStreamPutPolicy
              PolicyDocument:
                Version: "2012-10-17"
                Statement:
                  - Effect: Allow
                    Action: 'kinesis:PutRecord'
                    Resource: !GetAtt KinesisStream.Arn

      IoTDataEventDataTopicRule:
        Type: AWS::IoT::TopicRule
        Properties:
          TopicRulePayload:
            RuleDisabled: 'false'
            Sql: SELECT * FROM 'sample/topic'
            Actions:
            - Kinesis:
                StreamName: !Ref KinesisStream
                RoleArn: !GetAtt KinesisStreamRole.Arn
</code>```

------ app.py file ------

```<code>    import json
    import boto3

    client = boto3.client('iot-data', region_name = 'us-west-2')

    def lambda_handler(event, context):
        deviceId = '123'
        payload_to_device(deviceId)

    def payload_to_device(deviceId):
        client.publish(
            topic='another/iot/topic/'+ deviceId +'/topic',
            qos=1,
            payload=json.dumps({"foo":"bar"})
            )
</code>```

Body:
I am developing an AWS SAM application where I am creating all the resources using SAM application's template.yaml file.

The application's flow goes like below:

Subscribe to a AWS IOT Topic --> Kinesis Stream --> AWS Lambda Function
--> Publish data to another AWS IOT Topic

The whole flow is built by now but, the AWS cloudWatch shows the following error when I am trying to publish some data to another topic using Boto3. (I think it may be a permission case like giving permissions to AWS IOT core & AWS Kinesis at the same time)

------ AWS CLoudWatch Log ------

[ERROR] ClientError: An error occurred (ForbiddenException) when calling the
Publish operation: None

Traceback (most recent call last):
  File "/var/task/app.py", line 8, in lambda_handler
    payload_to_device(deviceId)

  File "/var/task/app.py", line 10, in payload_to_device
    client.publish(

  File "/var/task/botocore/client.py", line 530, in _api_call
    return self._make_api_call(operation_name, kwargs)

  File "/var/task/botocore/client.py", line 960, in _make_api_call
    raise error_class(parsed_response, operation_name)

------ Template.yaml file ------

    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Description: >
      KinesisStream

      Sample SAM Template for KinesisStream

    Globals:
      Function:
        Timeout: 3

    Resources:
      HelloWorldFunction:
        Type: AWS::Serverless::Function
        Properties:
          CodeUri: hello_world/
          Handler: app.lambda_handler
          Runtime: python3.9
          Architectures:
            - x86_64
          Events:
            Stream:
              Type: Kinesis
              Properties:
                Stream: !GetAtt KinesisStream.Arn
                StartingPosition: LATEST
                BatchSize: 5
                MaximumBatchingWindowInSeconds: 5
          Role: !GetAtt LambdaRole.Arn

      LambdaRole:
        Type: AWS::IAM::Role
        Properties:
          AssumeRolePolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Principal:
                  Service:
                    - "lambda.amazonaws.com"
                Action:
                  - 'sts:AssumeRole'
          Path: /
          ManagedPolicyArns:
            - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
          Policies:
            - PolicyName: "LambdaPolicy"
              PolicyDocument:
                Version: "2012-10-17"
                Statement:
                  - Effect: Allow
                    Action:
                      - 'iot:Publish'
                      - 'kinesis:PutRecord'
                    Resource: '*'
      KinesisStream:
        Type: AWS::Kinesis::Stream
        Properties:
          ShardCount: 1

      KinesisStreamRole:
        Type: AWS::IAM::Role
        Properties:
          AssumeRolePolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Principal:
                  Service:
                    - iot.amazonaws.com
                Action:
                  - 'sts:AssumeRole'
          Path: /
          Policies:
            - PolicyName: KinesisStreamPutPolicy
              PolicyDocument:
                Version: "2012-10-17"
                Statement:
                  - Effect: Allow
                    Action: 'kinesis:PutRecord'
                    Resource: !GetAtt KinesisStream.Arn

      IoTDataEventDataTopicRule:
        Type: AWS::IoT::TopicRule
        Properties:
          TopicRulePayload:
            RuleDisabled: 'false'
            Sql: SELECT * FROM 'sample/topic'
            Actions:
            - Kinesis:
                StreamName: !Ref KinesisStream
                RoleArn: !GetAtt KinesisStreamRole.Arn

------ app.py file ------

    import json
    import boto3

    client = boto3.client('iot-data', region_name = 'us-west-2')

    def lambda_handler(event, context):
        deviceId = '123'
        payload_to_device(deviceId)

    def payload_to_device(deviceId):
        client.publish(
            topic='another/iot/topic/'+ deviceId +'/topic',
            qos=1,
            payload=json.dumps({"foo":"bar"})
            )


问:
How can I let specific request pass specific Filter in Spring Security
I am working on making API in Spring Boot using Spring Security.

I made when there is request for /account/** and /notifications/**, it goes to JwtAuthenticationFilter by configuring it in SecurityFilterChain.

And now I want to add /plan/webhook endpoint and it goes to only RevenueCatAuthenticationFilter without passing other Filters so I can make different authentication logic for /plan/webhook.

But I found it goes to RevenueCatAuthenticationFilter -> JwtAuthenticationFilter.
How can I make /plan/webhook pass only RevenueCatAuthenticationFilter?

Thank you in advance.

```<code>package com.xxxx.xxxx.config;

import com.xxxx.xxxx.config.filter.JwtAuthenticationFilter;
import com.xxxx.xxxx.config.filter.RevenueCatAuthenticationFilter;
import com.xxxx.xxxx.service.FirebaseService;
import com.xxxx.xxxx.util.JwtTokenUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    JwtAuthenticationFilter jwtAuthenticationFilter(JwtTokenUtil jwtTokenUtil, FirebaseService firebaseService) {
        return new JwtAuthenticationFilter(jwtTokenUtil, firebaseService);
    }
    RevenueCatAuthenticationFilter revenueCatAuthenticationFilter() {
        return new RevenueCatAuthenticationFilter();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, JwtTokenUtil jwtTokenUtil, FirebaseService firebaseService) throws Exception {
        return http
                .httpBasic().disable()
                .csrf().disable()
                .cors().disable()
                .authorizeRequests()
                .antMatchers(
                        "/swagger-resources/**",
                        "/swagger-ui.html",
                        "/swagger-ui/index.html",
                        "/v3/api-docs",
                        "/webjars/**").permitAll()
                .antMatchers("/health/check").permitAll()
                .antMatchers("/notifications/count").permitAll()
                .antMatchers("/plan/webhook").permitAll()
                .anyRequest().authenticated()
                .and()
                .requestMatchers().antMatchers("/plan/webhook").and()
                .addFilterBefore(revenueCatAuthenticationFilter(), BasicAuthenticationFilter.class)
                .requestMatchers().antMatchers("/account/**", "/notifications/**").and()
                .addFilterBefore(jwtAuthenticationFilter(jwtTokenUtil, firebaseService), BasicAuthenticationFilter.class)
                .build();
    }
}

</code>```

ps)

My JwtAuthenticationFilter extends GenericFilter

My RecevenuCatAuthenticationFilter extends OncePerRequestFilter.

Body:
I am working on making API in Spring Boot using Spring Security.

I made when there is request for /account/** and /notifications/**, it goes to JwtAuthenticationFilter by configuring it in SecurityFilterChain.

And now I want to add /plan/webhook endpoint and it goes to only RevenueCatAuthenticationFilter without passing other Filters so I can make different authentication logic for /plan/webhook.

But I found it goes to RevenueCatAuthenticationFilter -> JwtAuthenticationFilter.
How can I make /plan/webhook pass only RevenueCatAuthenticationFilter?

Thank you in advance.

package com.xxxx.xxxx.config;

import com.xxxx.xxxx.config.filter.JwtAuthenticationFilter;
import com.xxxx.xxxx.config.filter.RevenueCatAuthenticationFilter;
import com.xxxx.xxxx.service.FirebaseService;
import com.xxxx.xxxx.util.JwtTokenUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    JwtAuthenticationFilter jwtAuthenticationFilter(JwtTokenUtil jwtTokenUtil, FirebaseService firebaseService) {
        return new JwtAuthenticationFilter(jwtTokenUtil, firebaseService);
    }
    RevenueCatAuthenticationFilter revenueCatAuthenticationFilter() {
        return new RevenueCatAuthenticationFilter();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, JwtTokenUtil jwtTokenUtil, FirebaseService firebaseService) throws Exception {
        return http
                .httpBasic().disable()
                .csrf().disable()
                .cors().disable()
                .authorizeRequests()
                .antMatchers(
                        "/swagger-resources/**",
                        "/swagger-ui.html",
                        "/swagger-ui/index.html",
                        "/v3/api-docs",
                        "/webjars/**").permitAll()
                .antMatchers("/health/check").permitAll()
                .antMatchers("/notifications/count").permitAll()
                .antMatchers("/plan/webhook").permitAll()
                .anyRequest().authenticated()
                .and()
                .requestMatchers().antMatchers("/plan/webhook").and()
                .addFilterBefore(revenueCatAuthenticationFilter(), BasicAuthenticationFilter.class)
                .requestMatchers().antMatchers("/account/**", "/notifications/**").and()
                .addFilterBefore(jwtAuthenticationFilter(jwtTokenUtil, firebaseService), BasicAuthenticationFilter.class)
                .build();
    }
}

ps)

My JwtAuthenticationFilter extends GenericFilter

My RecevenuCatAuthenticationFilter extends OncePerRequestFilter.


问:
How to display github README.md in slack channel
How to display a github README.md contents in a slack message or channel?

I am trying to get repo README.md's to display the full contents in a post on slack which will automatically update based on the github repo's README.md contents to make devOps more efficient.

I have looked at the slack app "github" and doesn't seem to have this integration or the command was changed.
I have tried the following but all I get is invalid command

```<code>/github repo-name /README.md
</code>```

Body:
How to display a github README.md contents in a slack message or channel?

I am trying to get repo README.md's to display the full contents in a post on slack which will automatically update based on the github repo's README.md contents to make devOps more efficient.

I have looked at the slack app "github" and doesn't seem to have this integration or the command was changed.
I have tried the following but all I get is invalid command

/github repo-name /README.md


问:
@JsonQualifier Can't I turn an Object field into a JSON string?
I tried to convert some fields to string type when requesting http, and I got an error when using Moshi's @JsonQualifier.Or is it feasible to use AOP to handle input parameters at the http interface? Will I get an error after modifying the field type?

Let's look directly at the example：

```<code>@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class ObjectToJson

class ObjectToJsonAdapter {

    @ToJson
    fun toJson(@ObjectToJson data: Any): String {
        return JSON.toJSONString(data)
    }

    @FromJson
    @ObjectToJson
    fun fromJson(data: Any): Any {
        return data
    }

}
</code>```
```<code>@Parcelize
data class OperateGroup(
    var id: String? = null,
    var name: String? = null,
    var illustrate: String? = null,
    var level: String? = null,
    var pack: String? = null,
    @ObjectToJson var payload: GroupPayload = GroupPayload(),

    var ownerLabel: String? = null
) : Parcelable

@Parcelize
data class GroupPayload(
    var lat_lon: String = ""
) : Parcelable
</code>```
```<code>private val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .client(okHttpClient)
        .addConverterFactory(
            MoshiConverterFactory.create(
                Moshi.Builder()
                    .add(KotlinJsonAdapterFactory())
                    .add(ObjectToJsonAdapter())
                    .build()
            )
        ).build()
</code>```

An error message is reported：

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sproutapp, PID: 5121
    java.lang.IllegalArgumentException: Unable to create converter for com.example.sproutapp.entity.Result<com.example.sproutapp.api.members.BaseStatisticData>
        for method OperateGroupAPI.baseStatistic
    Caused by: java.lang.IllegalArgumentException: No JsonAdapter for class com.example.sproutapp.api.members.GroupPayload annotated [@com.example.sproutapp.model.ObjectToJson()]
    for class com.example.sproutapp.api.members.GroupPayload payload
    for class com.example.sproutapp.api.members.OperateGroup
    for java.util.List<com.example.sproutapp.api.members.OperateGroup> groupList
    for class com.example.sproutapp.api.members.BaseStatisticData data
    for com.example.sproutapp.entity.Result<com.example.sproutapp.api.members.BaseStatisticData>
        at com.squareup.moshi.Moshi$LookupChain.exceptionWithLookupStack(Moshi.java:389)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:158)
        at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:106)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:75)
        at com.squareup.moshi.CollectionJsonAdapter.newArrayListAdapter(CollectionJsonAdapter.java:54)
        at com.squareup.moshi.CollectionJsonAdapter$1.create(CollectionJsonAdapter.java:38)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
        at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
        at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:106)
        at retrofit2.converter.moshi.MoshiConverterFactory.responseBodyConverter(MoshiConverterFactory.java:89)
        at retrofit2.Retrofit.nextResponseBodyConverter(Retrofit.java:362)
        at retrofit2.Retrofit.responseBodyConverter(Retrofit.java:345)
        at retrofit2.HttpServiceMethod.createResponseConverter(HttpServiceMethod.java:124)
            ... 21 more
E/AndroidRuntime: Caused by: java.lang.IllegalArgumentException: No JsonAdapter for class com.example.sproutapp.api.members.GroupPayload annotated [@com.example.sproutapp.model.ObjectToJson()]
        at com.squareup.moshi.Moshi.adapter(Moshi.java:156)
            ... 37 more
</code>```

Body:
I tried to convert some fields to string type when requesting http, and I got an error when using Moshi's @JsonQualifier.Or is it feasible to use AOP to handle input parameters at the http interface? Will I get an error after modifying the field type?

Let's look directly at the example：

@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class ObjectToJson

class ObjectToJsonAdapter {

    @ToJson
    fun toJson(@ObjectToJson data: Any): String {
        return JSON.toJSONString(data)
    }

    @FromJson
    @ObjectToJson
    fun fromJson(data: Any): Any {
        return data
    }

}

@Parcelize
data class OperateGroup(
    var id: String? = null,
    var name: String? = null,
    var illustrate: String? = null,
    var level: String? = null,
    var pack: String? = null,
    @ObjectToJson var payload: GroupPayload = GroupPayload(),

    var ownerLabel: String? = null
) : Parcelable

@Parcelize
data class GroupPayload(
    var lat_lon: String = ""
) : Parcelable

private val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .client(okHttpClient)
        .addConverterFactory(
            MoshiConverterFactory.create(
                Moshi.Builder()
                    .add(KotlinJsonAdapterFactory())
                    .add(ObjectToJsonAdapter())
                    .build()
            )
        ).build()

An error message is reported：

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sproutapp, PID: 5121
    java.lang.IllegalArgumentException: Unable to create converter for com.example.sproutapp.entity.Result<com.example.sproutapp.api.members.BaseStatisticData>
        for method OperateGroupAPI.baseStatistic
    Caused by: java.lang.IllegalArgumentException: No JsonAdapter for class com.example.sproutapp.api.members.GroupPayload annotated [@com.example.sproutapp.model.ObjectToJson()]
    for class com.example.sproutapp.api.members.GroupPayload payload
    for class com.example.sproutapp.api.members.OperateGroup
    for java.util.List<com.example.sproutapp.api.members.OperateGroup> groupList
    for class com.example.sproutapp.api.members.BaseStatisticData data
    for com.example.sproutapp.entity.Result<com.example.sproutapp.api.members.BaseStatisticData>
        at com.squareup.moshi.Moshi$LookupChain.exceptionWithLookupStack(Moshi.java:389)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:158)
        at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:106)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:75)
        at com.squareup.moshi.CollectionJsonAdapter.newArrayListAdapter(CollectionJsonAdapter.java:54)
        at com.squareup.moshi.CollectionJsonAdapter$1.create(CollectionJsonAdapter.java:38)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
        at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
        at com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory.create(KotlinJsonAdapter.kt:292)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:146)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:106)
        at retrofit2.converter.moshi.MoshiConverterFactory.responseBodyConverter(MoshiConverterFactory.java:89)
        at retrofit2.Retrofit.nextResponseBodyConverter(Retrofit.java:362)
        at retrofit2.Retrofit.responseBodyConverter(Retrofit.java:345)
        at retrofit2.HttpServiceMethod.createResponseConverter(HttpServiceMethod.java:124)
            ... 21 more
E/AndroidRuntime: Caused by: java.lang.IllegalArgumentException: No JsonAdapter for class com.example.sproutapp.api.members.GroupPayload annotated [@com.example.sproutapp.model.ObjectToJson()]
        at com.squareup.moshi.Moshi.adapter(Moshi.java:156)
            ... 37 more


问:
Python auto bot for messenger-project
I am working with a project to create a auto bot for massenger.

I saw some youtube tutorials and i followed 1 video
for the project, in the vieo the developer use's google's DialogFlow for the automated messegers, and the language is python .

but the peoblem is when the youtuber tryed to launch the python code it worked fine for him. but in my case when I try to run the code it shows error,

for a better understanding i'll give the youtube video link too

youtube video link
which is 2 years old.

can anyone help me with this probelm? here is the python code - to use the code we need 2 library,

fbchat{ -m pip install fbchat}

apiai{-m pip install apiai}

```<code>from fbchat import Client, log
from fbchat.models import *
import apiai
import codecs
import json

class chatS(Client):

    def apiaiCon(self):
        self.CLIENT_ACCESS_TOKEN = "3f9cecdc3442cd22220233ecb850e3c39f633bb1"
        self.ai = apiai.ApiAI(self.CLIENT_ACCESS_TOKEN)
        self.request = self.ai.text_request()
        self.request.lang = 'en'
        self.request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    def onMessage(self, mid=None, author_id=None, message=None, message_object=None, thread_id=None, thread_type=ThreadType.USER, ts=None, metadata=None, msg=None, **kwargs):

        # self.markAsRead(author_id)

        log.info("Message {} from {} in {}".format(
            message_object, thread_id, thread_type))

        self.apiaiCon()

        msgText = message_object.text

        self.request.query = msgText

        response = self.request.getresponse()

        obj = json.load(response)

        reply = obj['result']['fulfillment']['speech']

        if author_id != self.uid:
            self.send(Message(text=reply), thread_id=thread_id,
                      thread_type=thread_type)

        self.markAsDelivered(author_id, thread_id)

Client = chatS("email", "password")
Client.listen()

</code>```

in the code CLIENT ACCESS CODE  is the API key of the DialogFlow, and Client = chatS("email", "password") is the facebook email and password

please help me anyone!

I tried to run the code , but it showed some error which i can't fix , here is the error image

Title: Python auto bot for messenger-project

Body:
I am working with a project to create a auto bot for massenger.

I saw some youtube tutorials and i followed 1 video
for the project, in the vieo the developer use's google's DialogFlow for the automated messegers, and the language is python .

but the peoblem is when the youtuber tryed to launch the python code it worked fine for him. but in my case when I try to run the code it shows error,

for a better understanding i'll give the youtube video link too

youtube video link
which is 2 years old.

can anyone help me with this probelm? here is the python code - to use the code we need 2 library,

fbchat{ -m pip install fbchat}

apiai{-m pip install apiai}

from fbchat import Client, log
from fbchat.models import *
import apiai
import codecs
import json

class chatS(Client):

    def apiaiCon(self):
        self.CLIENT_ACCESS_TOKEN = "3f9cecdc3442cd22220233ecb850e3c39f633bb1"
        self.ai = apiai.ApiAI(self.CLIENT_ACCESS_TOKEN)
        self.request = self.ai.text_request()
        self.request.lang = 'en'
        self.request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    def onMessage(self, mid=None, author_id=None, message=None, message_object=None, thread_id=None, thread_type=ThreadType.USER, ts=None, metadata=None, msg=None, **kwargs):

        # self.markAsRead(author_id)

        log.info("Message {} from {} in {}".format(
            message_object, thread_id, thread_type))

        self.apiaiCon()

        msgText = message_object.text

        self.request.query = msgText

        response = self.request.getresponse()

        obj = json.load(response)

        reply = obj['result']['fulfillment']['speech']

        if author_id != self.uid:
            self.send(Message(text=reply), thread_id=thread_id,
                      thread_type=thread_type)

        self.markAsDelivered(author_id, thread_id)

Client = chatS("email", "password")
Client.listen()

in the code CLIENT ACCESS CODE  is the API key of the DialogFlow, and Client = chatS("email", "password") is the facebook email and password

please help me anyone!

I tried to run the code , but it showed some error which i can't fix , here is the error image


问:
Symfony \ Component \ ErrorHandler \ Error \ FatalError
The actual error:

```<code>During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Database\Eloquent\Model::offsetExists($offset)
should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice
in /home/u117697797/domains/divafashion.in/public_html/core/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1658
</code>```

The stacktrace from laravel.log:

```<code>Stack trace:
#0 /home/u117697797/domains/divafashion.in/public_html/core/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(23): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError()
#1 /home/u117697797/domains/divafashion.in/public_html/core/vendor/composer/ClassLoader.php(571): include('/home/u11769779...')
#2 /home/u117697797/domains/divafashion.in/public_html/core/vendor/composer/ClassLoader.php(428): Composer\Autoload\includeFile() #3 /home/u117697797/domains/divafashion.in/public_html/core/vendor/laravel/framework/src/Illuminate/Database/DatabaseServiceProvider.php(42): Composer\Autoload\ClassLoader->loadClass()
#4 /home/u117697797/domains/divafashion.in/public_html/core/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(627): Illuminate\Database\DatabaseServiceProvider->register()
#5 public_html/core/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
**/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php23**
13. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
14. use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
15. use Illuminate\Database\Eloquent\Relations\HasManyThrough;
16. use Illuminate\Database\Eloquent\Relations\Pivot;
17. use Illuminate\Support\Arr;
18. use Illuminate\Support\Collection as BaseCollection;
19. use Illuminate\Support\Str;
20. use Illuminate\Support\Traits\ForwardsCalls;
21. use JsonSerializable;
22.
23. abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
24. {
25.    use Concerns\HasAttributes,
26.        Concerns\HasEvents,
27.        Concerns\HasGlobalScopes,
28.        Concerns\HasRelationships,
29.        Concerns\HasTimestamps,
30.        Concerns\HidesAttributes,
31.        Concerns\GuardsAttributes,
32.        ForwardsCalls;
</code>```

What I want:

I want to live my website without 500 HTTP error or this error. Can you help me?

Body:
The actual error:

During inheritance of ArrayAccess: Uncaught ErrorException: Return type of Illuminate\Database\Eloquent\Model::offsetExists($offset)
should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice
in /home/u117697797/domains/divafashion.in/public_html/core/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1658

The stacktrace from laravel.log:

Stack trace:
#0 /home/u117697797/domains/divafashion.in/public_html/core/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(23): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError()
#1 /home/u117697797/domains/divafashion.in/public_html/core/vendor/composer/ClassLoader.php(571): include('/home/u11769779...')
#2 /home/u117697797/domains/divafashion.in/public_html/core/vendor/composer/ClassLoader.php(428): Composer\Autoload\includeFile() #3 /home/u117697797/domains/divafashion.in/public_html/core/vendor/laravel/framework/src/Illuminate/Database/DatabaseServiceProvider.php(42): Composer\Autoload\ClassLoader->loadClass()
#4 /home/u117697797/domains/divafashion.in/public_html/core/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(627): Illuminate\Database\DatabaseServiceProvider->register()
#5 public_html/core/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
**/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php23**
13. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
14. use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
15. use Illuminate\Database\Eloquent\Relations\HasManyThrough;
16. use Illuminate\Database\Eloquent\Relations\Pivot;
17. use Illuminate\Support\Arr;
18. use Illuminate\Support\Collection as BaseCollection;
19. use Illuminate\Support\Str;
20. use Illuminate\Support\Traits\ForwardsCalls;
21. use JsonSerializable;
22.
23. abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
24. {
25.    use Concerns\HasAttributes,
26.        Concerns\HasEvents,
27.        Concerns\HasGlobalScopes,
28.        Concerns\HasRelationships,
29.        Concerns\HasTimestamps,
30.        Concerns\HidesAttributes,
31.        Concerns\GuardsAttributes,
32.        ForwardsCalls;

What I want:

I want to live my website without 500 HTTP error or this error. Can you help me?


问:
Database more efficient way storing the referral to 1'st table in every line in the 2'nd table
I have 2 tables on my DB

I want to avoid the "account ref" for every line in dates table, is there a way to keep fast fetching and reduce memory ?

I uses postgresql as DB with Django and Python.


问:
updateAcquireFence: Did not find frame. Flutter
I am using youtube_player_iframe: ^4.0.1 this package for youtube video in my app. I have following error "updateAcquireFence: Did not find frame. Flutter" and also not able to play video. After some minutes it shows thumbnail in screen but when I press play button its loading only and not able to play video. Please help me for this I am stuck in this problem.

Followig are my codes:

This are the response from api

```<code>{
  status: true,
  result: found,
  data: [
    {
      ref_id: 5,
      userid: 106764933065187174744,
      username: TakiRajani,
      link: https: //youtu.be/Sm3pR9FYZcY,
      postDateTime: 30-12-202203: 04PM,
      city: tt,
      channelName: masoomeenchannel
    },
    {
      ref_id: 1,
      userid: taki,
      username: TakiRajani,
      link: https: //youtu.be/wf9oETBOxPY,
      postDateTime: 20-11-2211: 30PM,
      city: Mahuva,
      channelName: adminchannel
    },
    {
      ref_id: 2,
      userid: taki1212,
      username: TakiRajani,
      link: https: //youtu.be/K-MYE2DyS-I,
      postDateTime: 20-11-2212: 52PM,
      city: Bhavnagar,
      channelName: alamdargrpmahuva
    },
    {
      ref_id: 4,
      userid: 1,
      username: Taqi,
      link: testUrl,
      postDateTime: TImeDate,
      city: City,
      channelName: alvichannel
    }
  ],
  totalPosts: 4,
  totalPages: 1,
  perPageLimit: 5,
  currentPage: 1,
  hasNextPage: 0
}
</code>```

Following are my code:

```<code>Future<LinkModel> getAllLinks() async {
    var url = "https://aeliya.000webhostapp.com/MajlisLinks.php";
    var response = await http.get(Uri.parse(url));
    var jsondata = jsonDecode(response.body.toString());
    print("****" + jsondata.toString());

    if (response.statusCode == 200) {
      return LinkModel.fromJson(jsondata);
    } else {
      return LinkModel.fromJson(jsondata);
    }
  }
</code>```

init method

```<code>@override
  void initState() {
    // TODO: implement initState
    super.initState();

    _controller = YoutubePlayerController(
      params: YoutubePlayerParams(
        showControls: true,
        mute: false,
        showFullscreenButton: true,
        loop: false,
      )
    );
  }
</code>```

ui part:

```<code>@override
  Widget build(BuildContext context) {
    return YoutubePlayerScaffold(
      controller: _controller,
      aspectRatio: 16 / 9,
      builder: (context, player) {
        return SafeArea(
            child: Scaffold(
              appBar: AppBar(title: Text("Live Program",
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 25
                ),),
                centerTitle: true,
                backgroundColor: Color(hexColors('006064')),
              ),
              body: FutureBuilder<LinkModel>(
                future: getAllLinks(),
                builder: (context,snapshot){
                  if(snapshot.hasData){
                    return ListView.builder(
                      itemCount: snapshot.data!.data!.length,
                        itemBuilder: (context, index){
                      var allItem = snapshot.data!.data![index];
                      var videoId = allItem.link!.substring(17);
                      print("///////////////////");
                      print(videoId);
                      return Card(
                        color: Color(hexColors("03A9F4")),
                        elevation: 6,
                        shape: RoundedRectangleBorder(
                            borderRadius:
                            BorderRadius.circular(10.0)),
                        child: Column(
                          children: [
                           YoutubePlayer(
                             controller: YoutubePlayerController.fromVideoId(videoId: videoId,
                             autoPlay: false,
                             params: YoutubePlayerParams(showFullscreenButton: true))

                               ),

                          ],
                        ),

                      );
                    }
                    );
                  }else{
                    return Container(child: Center(child: CircularProgressIndicator(),),);
                  }

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

Body:
I am using youtube_player_iframe: ^4.0.1 this package for youtube video in my app. I have following error "updateAcquireFence: Did not find frame. Flutter" and also not able to play video. After some minutes it shows thumbnail in screen but when I press play button its loading only and not able to play video. Please help me for this I am stuck in this problem.

Followig are my codes:

This are the response from api

{
  status: true,
  result: found,
  data: [
    {
      ref_id: 5,
      userid: 106764933065187174744,
      username: TakiRajani,
      link: https: //youtu.be/Sm3pR9FYZcY,
      postDateTime: 30-12-202203: 04PM,
      city: tt,
      channelName: masoomeenchannel
    },
    {
      ref_id: 1,
      userid: taki,
      username: TakiRajani,
      link: https: //youtu.be/wf9oETBOxPY,
      postDateTime: 20-11-2211: 30PM,
      city: Mahuva,
      channelName: adminchannel
    },
    {
      ref_id: 2,
      userid: taki1212,
      username: TakiRajani,
      link: https: //youtu.be/K-MYE2DyS-I,
      postDateTime: 20-11-2212: 52PM,
      city: Bhavnagar,
      channelName: alamdargrpmahuva
    },
    {
      ref_id: 4,
      userid: 1,
      username: Taqi,
      link: testUrl,
      postDateTime: TImeDate,
      city: City,
      channelName: alvichannel
    }
  ],
  totalPosts: 4,
  totalPages: 1,
  perPageLimit: 5,
  currentPage: 1,
  hasNextPage: 0
}

Following are my code:

Future<LinkModel> getAllLinks() async {
    var url = "https://aeliya.000webhostapp.com/MajlisLinks.php";
    var response = await http.get(Uri.parse(url));
    var jsondata = jsonDecode(response.body.toString());
    print("****" + jsondata.toString());

    if (response.statusCode == 200) {
      return LinkModel.fromJson(jsondata);
    } else {
      return LinkModel.fromJson(jsondata);
    }
  }

init method

@override
  void initState() {
    // TODO: implement initState
    super.initState();

    _controller = YoutubePlayerController(
      params: YoutubePlayerParams(
        showControls: true,
        mute: false,
        showFullscreenButton: true,
        loop: false,
      )
    );
  }

ui part:

@override
  Widget build(BuildContext context) {
    return YoutubePlayerScaffold(
      controller: _controller,
      aspectRatio: 16 / 9,
      builder: (context, player) {
        return SafeArea(
            child: Scaffold(
              appBar: AppBar(title: Text("Live Program",
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 25
                ),),
                centerTitle: true,
                backgroundColor: Color(hexColors('006064')),
              ),
              body: FutureBuilder<LinkModel>(
                future: getAllLinks(),
                builder: (context,snapshot){
                  if(snapshot.hasData){
                    return ListView.builder(
                      itemCount: snapshot.data!.data!.length,
                        itemBuilder: (context, index){
                      var allItem = snapshot.data!.data![index];
                      var videoId = allItem.link!.substring(17);
                      print("///////////////////");
                      print(videoId);
                      return Card(
                        color: Color(hexColors("03A9F4")),
                        elevation: 6,
                        shape: RoundedRectangleBorder(
                            borderRadius:
                            BorderRadius.circular(10.0)),
                        child: Column(
                          children: [
                           YoutubePlayer(
                             controller: YoutubePlayerController.fromVideoId(videoId: videoId,
                             autoPlay: false,
                             params: YoutubePlayerParams(showFullscreenButton: true))

                               ),

                          ],
                        ),

                      );
                    }
                    );
                  }else{
                    return Container(child: Center(child: CircularProgressIndicator(),),);
                  }

                },
              ),
            )
        );
      },
    );
}
}


问:
Spring Boot Security filter chain has error
when i user Spring Boot Security filter chain insted of WebscurityconfigurerAdapter has error...

```<code>@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.DELETE)
            .hasRole("ADMIN")
            .antMatchers("/admin/**")
            .hasAnyRole("ADMIN")
            .antMatchers("/user/**")
            .hasAnyRole("USER", "ADMIN")
            .antMatchers("/login/**")
            .anonymous()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    return http.build();
}
</code>```

----  httpSecurity NOT recognize  -------

```<code>@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
}
</code>```

***** antMatchers  has error *****[tag:Spring BootSecurity filterChain]

Body:
when i user Spring Boot Security filter chain insted of WebscurityconfigurerAdapter has error...

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.DELETE)
            .hasRole("ADMIN")
            .antMatchers("/admin/**")
            .hasAnyRole("ADMIN")
            .antMatchers("/user/**")
            .hasAnyRole("USER", "ADMIN")
            .antMatchers("/login/**")
            .anonymous()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    return http.build();
}

----  httpSecurity NOT recognize  -------

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
}

***** antMatchers  has error *****[tag:Spring BootSecurity filterChain]


问:
Custom Rectangle Class Not Drawing

import pygame

pygame.init()

BACKGROUND = ("#00607a")
(WIDTH,HEIGHT) = (800,600)

def main():
    screen = pygame.display.set_mode((WIDTH,HEIGHT))
    screen.fill(BACKGROUND)
    pygame.display.set_caption("Cobalt")

    pygame.display.flip()

    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            drawScreen(screen)

class Rectangle():

    def __init__(self, surface, color, x, y, w, h) -> None:
        self.surface = surface
        self.color = color
        self.x = x
        self.y = y
        self.w = w
        self.h = h

    def draw(self):

        pygame.draw.rect(self.surface, self.color, pygame.Rect(self.x,self.y,self.w,self.h))

def drawScreen(screen):

    rec1 = Rectangle(screen, "#004a55", 30, 30, 60 ,60)

    rec1.draw()

    pygame.display.flip

if __name__ == '__main__':

    main()

# Its not drawing the rectangle ?

```

I have a custom rectangle class with x,y , color, and the screen as paramaters. I then create a Rectangle instance in the rec1 varible and call the Rectagle draw functions which should draw it to the screen. but when I run the code nothing appears but no error is given so im not sure whats happeneing.

Title: Custom Rectangle Class Not Drawing

Body:
import pygame

pygame.init()

BACKGROUND = ("#00607a")
(WIDTH,HEIGHT) = (800,600)

def main():
    screen = pygame.display.set_mode((WIDTH,HEIGHT))
    screen.fill(BACKGROUND)
    pygame.display.set_caption("Cobalt")

    pygame.display.flip()

    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            drawScreen(screen)

class Rectangle():

    def __init__(self, surface, color, x, y, w, h) -> None:
        self.surface = surface
        self.color = color
        self.x = x
        self.y = y
        self.w = w
        self.h = h

    def draw(self):

        pygame.draw.rect(self.surface, self.color, pygame.Rect(self.x,self.y,self.w,self.h))

def drawScreen(screen):

    rec1 = Rectangle(screen, "#004a55", 30, 30, 60 ,60)

    rec1.draw()

    pygame.display.flip

if __name__ == '__main__':

    main()

# Its not drawing the rectangle ?

I have a custom rectangle class with x,y , color, and the screen as paramaters. I then create a Rectangle instance in the rec1 varible and call the Rectagle draw functions which should draw it to the screen. but when I run the code nothing appears but no error is given so im not sure whats happeneing.


问:
PHP regex to fetch the inner function list from JavaScript source code
Below is the JavaScript source code on which the php regex I am trying to apply.

```<code><script>
function outerfunction () {

    function abcd () {
        return ('efgh', 1);
    }

    function efgh () {
        return ('higk', 2);
    }
}
</script>
</code>```

I am trying to fetch all the inner function from the JavaScript code below with function name length having 4 chars, using preg_match_all() with pattern /(function.[a-z]{4}.[(][)].*)}/s. using this online tool phpliveregex.com

below is the output in 2nd array. but i need all the functions list as in individual array elements. currently it is comming inside single array element result.

Current output

```<code>array[1] => function abcd () {
        return ('efgh', 1);
    }

    function efgh () {
        return ('higk', 2);
    }
</code>```

Needed:

```<code>array[1] => function abcd () {
        return ('efgh', 1);
    }

array[2] => function efgh () {
        return ('higk', 2);
    }
</code>```

Body:
Below is the JavaScript source code on which the php regex I am trying to apply.

I am trying to fetch all the inner function from the JavaScript code below with function name length having 4 chars, using preg_match_all() with pattern /(function.[a-z]{4}.[(][)].*)}/s. using this online tool phpliveregex.com

below is the output in 2nd array. but i need all the functions list as in individual array elements. currently it is comming inside single array element result.

Current output

array[1] => function abcd () {
        return ('efgh', 1);
    }

    function efgh () {
        return ('higk', 2);
    }

Needed:

array[1] => function abcd () {
        return ('efgh', 1);
    }

array[2] => function efgh () {
        return ('higk', 2);
    }


问:
Tensorflow alternative/equivalent for torch_geometric.nn.radius_graph()
I am new to graph deep learning and I am trying to generate a graph from a matrix of node features by computing graph edges for all nodes within a given distance. I have found a concise way to do this with torch_geometric.nn.radius_graph() but I would like a similarly concise method of accomplishing the same task with tensorflow tensors.

My code is kind of a mess right now and I would like to change it significantly based on whatever method that is convenient for processing a graph dataset in this form. I am aware that I can write a class of connectivity utility functions but I don't think that is ideal.


问:
Getting "duplicate class" error in IntelliJ Idea Community edition, preventing complete compilation of workspace
I am trying to compile my entire workspace with about 200 modules in it. Using javac compiler with extra arguments -Xmaxerrs 1000 -Xmaxwarns 1000
However, the compilation is getting stopped due to the error of duplicate classes being found.
Duplicate Class error

Duplicate classes do exist in my workspace, however, I am not sure which one of them I can delete without leading to consequent dependency issues. Hence I want duplicate classes to existing as it is, but I want IntelliJ to stop giving me this error. Can somebody please help me out and show me how to either suppress/ignore this error so that the compilation does not stop? Thanks in advance

I tried @SuppressWarnings('Duplicates') on top of the duplicate classes but that did not stop the IntelliJ compiler from giving me the same error.
I also tried checking all possible Editor -> Inspections but there is no option for ignoring duplicate classes.
I also increased the shared heap memory for the compiler to 4096 MB.
Tried rebuilding the entire workspace, did not help.
Increased javac compiler inbuilt error limit from 100 to 1000000

(Edit 1) Note: Just to be clear, duplicate classes are NOT in the same package, but in different packages across different modules

(Edit 2) Duplicate class example Class on left Class on right


问:
How find all mailboxes that have "have server reply using a specific message" inbox rule settings set
I want to find all mailboxes that have "have server reply using a specific message" inbox rule settings set.

As test , I have created a user mailbox like below. I've set "have server reply using a specific message" inbox rule for mailbox. After , I have checked it via Get-Inboxrule command. As summary , I am getting a output like below.

I am assuming , I need to catch  "Description  : If the message:  the message was sent only to me." keyword.

```<code>Get-Mailbox "user" |Get-InboxRule | select name,Identity,ForwardTo,ForwardAsAttachmentTo, RedirectTo, DeleteMessage,Description
</code>```

Output :

```<code>Name                  : sent only to me
Identity              : contoso.local/IT/User\9148223268954570753
ForwardTo             :
ForwardAsAttachmentTo :
RedirectTo            :
DeleteMessage         : False
Description           : If the message:
                            the message was sent only to me.
</code>```

thanks,

Body:
I want to find all mailboxes that have "have server reply using a specific message" inbox rule settings set.

As test , I have created a user mailbox like below. I've set "have server reply using a specific message" inbox rule for mailbox. After , I have checked it via Get-Inboxrule command. As summary , I am getting a output like below.

I am assuming , I need to catch  "Description  : If the message:  the message was sent only to me." keyword.

Get-Mailbox "user" |Get-InboxRule | select name,Identity,ForwardTo,ForwardAsAttachmentTo, RedirectTo, DeleteMessage,Description

Output :

Name                  : sent only to me
Identity              : contoso.local/IT/User\9148223268954570753
ForwardTo             :
ForwardAsAttachmentTo :
RedirectTo            :
DeleteMessage         : False
Description           : If the message:
                            the message was sent only to me.

thanks,


问:
What's the difference between textmate scopes and semantic token type?
the confusing example

I'm creating a theme for vscode. However I'm confused about the two different scope descriptions: textmate scopes and semantic token type.

Why is the foreground in textmate scopes crossed out?

I want the text mate foreground color to be applied, not crossed out.


问:
8086 Assemnly , 65535 and -1
65535 = 0xffff(unsigned)
-1 = 0xffff(signed)
In my bochsgdb
mov ax , 65535 and mov ax , -1 can change the content in AX to 11111111
I don't know why it has the same effect.
If in this way . How does 8086 assembly distinguish between -1 and 65535 ? and How do I know the bits are represented for unsigned or signed ?

I thy to google but I did not get the answer , I wish you can explain why is this ? please

Title: 8086 Assemnly , 65535 and -1


问:
SwiftLint regex match multiple cases in file
Here is my rule:

```<code>custom_rules:
  protocol_single_responsibility_violation:
    name: "Protocol with more than one function and or variable"
    regex: '(protocol.*\{\n.*func.*\n.*func.*\})|(protocol.*\{\n.*var.*\n.*func.*\})|(protocol.*\{\n.*func.*\n.*var.*\})|(protocol.*\{\n.*var.*\n.*var.*\})'
    message: "If you would like to create a protocol with more than one function and or variable, then cretae separate protocols with one function or variable each, then combine them with a typealias. For example, typealias = firstProtocol & secondProtocol"
    severity: error
</code>```

Here is my test

protocol GroupedProtocol { // This is the only one it catches
    func stuff()
    func stuff2()
}

protocol GroupedProtocol2 {
    var stuff: Int { get set }
    func stuff2()
}

protocol GroupedProtocol3 {
    var stuff: Int { get set }
    var stuff2: Int { get set }
}

protocol GroupedProtocol4 {
    func stuff2()
    var stuff: Int { get set }
}

protocol GroupedProtocol5 {
    func stuff()
}

class Decoy { }

```

Its currently matching only one of the cases.  How can I make it match all 4 cases?

Body:
Here is my rule:

custom_rules:
  protocol_single_responsibility_violation:
    name: "Protocol with more than one function and or variable"
    regex: '(protocol.*\{\n.*func.*\n.*func.*\})|(protocol.*\{\n.*var.*\n.*func.*\})|(protocol.*\{\n.*func.*\n.*var.*\})|(protocol.*\{\n.*var.*\n.*var.*\})'
    message: "If you would like to create a protocol with more than one function and or variable, then cretae separate protocols with one function or variable each, then combine them with a typealias. For example, typealias = firstProtocol & secondProtocol"
    severity: error

Here is my test

protocol GroupedProtocol { // This is the only one it catches
    func stuff()
    func stuff2()
}

protocol GroupedProtocol2 {
    var stuff: Int { get set }
    func stuff2()
}

protocol GroupedProtocol3 {
    var stuff: Int { get set }
    var stuff2: Int { get set }
}

protocol GroupedProtocol4 {
    func stuff2()
    var stuff: Int { get set }
}

protocol GroupedProtocol5 {
    func stuff()
}

class Decoy { }

Its currently matching only one of the cases.  How can I make it match all 4 cases?


问:
When navigating to a different web page from a webpage should the URL of the new webpage contain the endpoint of the previous web page?
Suppose I have a web page let's say rooms.html and the URL of that page is "http://localhost:8000/hotel/rooms/". In that HTML page there is a link to add_room.html page, when I click on that link, I get redirected to add_room.html whose URL is "http://localhost:8000/hotel/add_room/". I want to know what should I keep the UPL of this page. Should it be "http://localhost:8000/hotel/add_room/" or "http://localhost:8000/hotel/rooms/add_room/". So bascically my question is that when navigating to a different web page from a webpage should the URL of the new webpage contain the endpoint of the previous web page?</p>


问:
Python Gurobi not able to get optimize solution
I'm working on a Gurobi optimize question but can't not find the solution I want.
This question is trying to find the best path for picking materials in warehouse.

Here is the current solution.

```<code>x(0,5,33) 1.0
q(1,33) 2.0
x(1,2,33) 1.0
q(2,33) 2.0
x(2,3,33) 1.0
q(3,33) 2.0
x(3,4,33) 1.0
q(4,33) 2.0
x(4,1,33) 1.0
q(5,33) 2.0
x(5,0,33) 1.0
</code>```

Here is my code.

```<code>from gurobipy import*

N = [0, 1, 2, 3, 4, 5] #Material location in warehosue, 0 is depot
S = [1] #The configuration need to be pick up

#Material list with location n
I, K = multidict({1:11, 2:12, 3:13, 4:42, 5:41})

#Distance between each location
R1 = {(0,1): 3, (0,2): 6, (0,3): 5, (0,4):4, (0,5): 2,\
      (1,2): 3, (1,3): 4, (1,4): 3, (1,5): 3,\
     (2,3): 3, (2,4): 6, (2,5): 4, (3,4): 3, (3,5): 7, (4,5): 6}
R = {}
for i,j in R1:
    R[j,i]=R1[i,j]
    R[i,j]=R1[i,j] #把0,1 -> 1,0

#Capacity
C = 10
#the batch of picking
L = [l for l in range(1,60)]

#BOM list (S:K1,K2,K3,K4,K5)
BOM = {1:[11,12,13,42,41]}

#Quantity demand of configuration
S, D = multidict({1:2})

#Decision variable
model = Model("Picking path")
x = {}
q = {}
u = {}
for l in L:
    for i in range(len(N)+1):
        q[i,l]=model.addVar(vtype="C", name="q(%s,%s)" %(i,l))
        for j in range(len(N)+1):
            x[i,j,l]=model.addVar(vtype="B", name="x(%s,%s,%s)" %(i,j,l))
for l in L:
    for i in range(len(N)+1):
        u[i,l]=model.addVar(vtype="C", name="u(%s)" %i)

model.update()

#Constraints
BigM = 10**6
for l in L:
    model.addConstr(quicksum(x[0,j,l] for j in N if j!=0)*BigM >= quicksum(q[j,l] for j in N), name="A.3")
    model.addConstr(quicksum(x[i,0,l] for i in N if i!=0)*BigM >= quicksum(q[j,l] for j in N), name="A.4")
    for j in N:
        model.addConstr(quicksum(x[i,j,l] for i in N if i!=j)\
                       -quicksum(x[j,v,l] for v in N if v!=j)==0, name="A.2")
        model.addConstr(quicksum(x[i,j,l] for i in N if i!=j)*BigM >= q[j,l], name="A.5")
        model.addConstr(q[j,l] <= C, name="A.6")

for i in range(1,len(N)):
    for s in S:
        for k in K:
            model.addConstr(quicksum(q[i,l] for l in L)\
                            ==quicksum(D[s] for s in BOM if K[i] in BOM[s]), name="A.7")

#subtour
for l in L:
    model.addConstr(u[0,l]==0)
    for i in range(len(N)+1):
        for j in N:
            if i!=j:
                model.addConstr(u[i,l]-u[j,l] + (len(N)+1)*x[i,j,l] <= (len(N)+1), name="A.8")

#Objective
model.setObjective(quicksum(R[i,j]*x[i,j,l] for i in N for j in N for l in L if i!=j), GRB.MINIMIZE)

model.optimize()

</code>```

I would like to have the solution go as 0-5 locations-0 as 1 big circle.
But now it's two circel (0-5-0 / 1-2-3-4-1), as below.

How can I modify the code to solve this issue?

Body:
I'm working on a Gurobi optimize question but can't not find the solution I want.
This question is trying to find the best path for picking materials in warehouse.

Here is the current solution.

x(0,5,33) 1.0
q(1,33) 2.0
x(1,2,33) 1.0
q(2,33) 2.0
x(2,3,33) 1.0
q(3,33) 2.0
x(3,4,33) 1.0
q(4,33) 2.0
x(4,1,33) 1.0
q(5,33) 2.0
x(5,0,33) 1.0

Here is my code.

from gurobipy import*

N = [0, 1, 2, 3, 4, 5] #Material location in warehosue, 0 is depot
S = [1] #The configuration need to be pick up

#Material list with location n
I, K = multidict({1:11, 2:12, 3:13, 4:42, 5:41})

#Distance between each location
R1 = {(0,1): 3, (0,2): 6, (0,3): 5, (0,4):4, (0,5): 2,\
      (1,2): 3, (1,3): 4, (1,4): 3, (1,5): 3,\
     (2,3): 3, (2,4): 6, (2,5): 4, (3,4): 3, (3,5): 7, (4,5): 6}
R = {}
for i,j in R1:
    R[j,i]=R1[i,j]
    R[i,j]=R1[i,j] #把0,1 -> 1,0

#Capacity
C = 10
#the batch of picking
L = [l for l in range(1,60)]

#BOM list (S:K1,K2,K3,K4,K5)
BOM = {1:[11,12,13,42,41]}

#Quantity demand of configuration
S, D = multidict({1:2})

#Decision variable
model = Model("Picking path")
x = {}
q = {}
u = {}
for l in L:
    for i in range(len(N)+1):
        q[i,l]=model.addVar(vtype="C", name="q(%s,%s)" %(i,l))
        for j in range(len(N)+1):
            x[i,j,l]=model.addVar(vtype="B", name="x(%s,%s,%s)" %(i,j,l))
for l in L:
    for i in range(len(N)+1):
        u[i,l]=model.addVar(vtype="C", name="u(%s)" %i)

model.update()

#Constraints
BigM = 10**6
for l in L:
    model.addConstr(quicksum(x[0,j,l] for j in N if j!=0)*BigM >= quicksum(q[j,l] for j in N), name="A.3")
    model.addConstr(quicksum(x[i,0,l] for i in N if i!=0)*BigM >= quicksum(q[j,l] for j in N), name="A.4")
    for j in N:
        model.addConstr(quicksum(x[i,j,l] for i in N if i!=j)\
                       -quicksum(x[j,v,l] for v in N if v!=j)==0, name="A.2")
        model.addConstr(quicksum(x[i,j,l] for i in N if i!=j)*BigM >= q[j,l], name="A.5")
        model.addConstr(q[j,l] <= C, name="A.6")

for i in range(1,len(N)):
    for s in S:
        for k in K:
            model.addConstr(quicksum(q[i,l] for l in L)\
                            ==quicksum(D[s] for s in BOM if K[i] in BOM[s]), name="A.7")

#subtour
for l in L:
    model.addConstr(u[0,l]==0)
    for i in range(len(N)+1):
        for j in N:
            if i!=j:
                model.addConstr(u[i,l]-u[j,l] + (len(N)+1)*x[i,j,l] <= (len(N)+1), name="A.8")

#Objective
model.setObjective(quicksum(R[i,j]*x[i,j,l] for i in N for j in N for l in L if i!=j), GRB.MINIMIZE)

model.optimize()

I would like to have the solution go as 0-5 locations-0 as 1 big circle.
But now it's two circel (0-5-0 / 1-2-3-4-1), as below.

How can I modify the code to solve this issue?