问:
Creating Van der Pol oscillator class with data frames
I'm trying to recreate this graph:

... and this table:

... using this set of equations:

It has to include these methods:

Instructions: Create a class that can be used to simulate Van der Pol oscillators. That class should contain at least the following methods:

add_oscillator(self, mu, x0=1, y0=0): Add a new oscillator with parameters mu initial values x(0)=x0 (default: 1) and y(0)=y0 (default: 0).

delete_oscillator(self, i): Delete the i-th oscillator from the list of available oscillators.

getsim_data(self, duration=30.0, dt=0.01): Simulate the N oscillators previously added to the object (using add_oscilator) for the specified duration (default: 30s) and with a sampling step dt (default: 0.01s) and return the simulated data as a pandas DataFrame of shape (duration/dt, N). "Simulating" these oscillators mean obtaining x(t) by solving the ODE above. This can be done manually using the Euler integration scheme (as seen in previous labs) or using an ODE solver (e.g., scipy.solve_ivp() function).

plot(fself, tmin=0.0, tmax=30.0): Plot the time course of the different oscillators from tmin to tmax.

Here is an example of use:

vdp = VanDerPol()
vdp.add_oscillator(1.0)  # oscilator 0
vdp.add_oscillator(3.0)  # oscilator 1
vdp.add_oscillator(2.0)  # oscilator 2
vdp.delete_oscilator(1)
print(vdp.get_sim_data(dt=0.01))
vdp.plot(tmin=10)
```
<p>I am trying to create a Python class to simulate a Van der Pol oscillator using <code>numpy</code>, <code>scipy</code>, <code>DataFrame</code>, and <code>matplotlib</code>.</p>
<p>This is my first exposure to coding, so I'm aware my code might be very junky.</p>
<p>I started off by completing the <code>add_oscillator</code> and <code>delete_oscillator</code> functions. Both seem to work, though I'm unsure if the <code>new_oscillator</code> class is the best way to achieve what I did.</p>
<p>I began running into problems in <code>get_sim_data</code>. I used information from this link to get a function working, and then adding the data to a <code>DataFrame</code>. The resulting data seems to be wrong, and I'm not sure where the mistake is.</p>
<p>The graphed plot also doesn't look like what I need it to look alike, and the <code>x-axis</code> numbers are <code>0-3000</code>, instead of <code>10-30</code>.</p>
<p>Any help is appreciated. Thanks.</p>
<pre class="lang-py prettyprint-override"><code>from scipy.integrate import solve_ivp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class VanDerPol:
    def __init__(self):
        self.oscillators = []
        self.df = pd.DataFrame()

    def add_oscillator(self, mu, x0=1, y0=0):
        class new_oscillator:
            def __init__(self, mu, x0, y0):
                self.mu = mu
                self.x0 = x0
                self.y0 = y0

            def __str__(self):
                return f"mu={self.mu}, x0={self.x0}, y0={self.y0}"

        self.oscillators.append(new_oscillator(mu, x0, y0))

    def delete_oscillator(self, i):
        self.oscillators.pop(i)

    def get_sim_data(self, duration=30.0, dt=0.01):
        # durations = np.arange(0, duration, dt, dtype=float)
        durations = np.linspace(0, duration, int(duration / dt))
        # df = pd.DataFrame(durations)

        for o in self.oscillators:

            def vdp(t, z):
                x, y = z
                return [y, o.mu * (1 - x**2) * y - x]

            data = solve_ivp(vdp, [0, duration], [o.x0, o.y0], t_eval=durations)
            # df = pd.DataFrame(data.y[0])
            # df = pd.DataFrame()
            df = pd.DataFrame(data.y[0])
            # df[o] = pd.Series(data.y[0])
            # print(data.y[0])
            self.df[o] = df
            # print(self.df)
            print(self.df)

    def plot(self, tmin=0.0, tmax=30.0):
        plt.plot(self.df)

vdp = VanDerPol()
vdp.add_oscillator(1.0)  # oscillator 0
vdp.add_oscillator(3.0)  # oscillator 1
vdp.add_oscillator(2.0)  # oscillator 2
vdp.delete_oscillator(1)
print(vdp.get_sim_data(dt=0.01))
vdp.plot(tmin=10)
</code>```

Body:
I'm trying to recreate this graph:

... and this table:

... using this set of equations:

It has to include these methods:

Instructions: Create a class that can be used to simulate Van der Pol oscillators. That class should contain at least the following methods:

add_oscillator(self, mu, x0=1, y0=0): Add a new oscillator with parameters mu initial values x(0)=x0 (default: 1) and y(0)=y0 (default: 0).

delete_oscillator(self, i): Delete the i-th oscillator from the list of available oscillators.

getsim_data(self, duration=30.0, dt=0.01): Simulate the N oscillators previously added to the object (using add_oscilator) for the specified duration (default: 30s) and with a sampling step dt (default: 0.01s) and return the simulated data as a pandas DataFrame of shape (duration/dt, N). "Simulating" these oscillators mean obtaining x(t) by solving the ODE above. This can be done manually using the Euler integration scheme (as seen in previous labs) or using an ODE solver (e.g., scipy.solve_ivp() function).

plot(fself, tmin=0.0, tmax=30.0): Plot the time course of the different oscillators from tmin to tmax.

Here is an example of use:

vdp = VanDerPol()
vdp.add_oscillator(1.0)  # oscilator 0
vdp.add_oscillator(3.0)  # oscilator 1
vdp.add_oscillator(2.0)  # oscilator 2
vdp.delete_oscilator(1)
print(vdp.get_sim_data(dt=0.01))
vdp.plot(tmin=10)

I am trying to create a Python class to simulate a Van der Pol oscillator using numpy, scipy, DataFrame, and matplotlib.

This is my first exposure to coding, so I'm aware my code might be very junky.

I started off by completing the add_oscillator and delete_oscillator functions. Both seem to work, though I'm unsure if the new_oscillator class is the best way to achieve what I did.

I began running into problems in get_sim_data. I used information from this link to get a function working, and then adding the data to a DataFrame. The resulting data seems to be wrong, and I'm not sure where the mistake is.

The graphed plot also doesn't look like what I need it to look alike, and the x-axis numbers are 0-3000, instead of 10-30.

Any help is appreciated. Thanks.

from scipy.integrate import solve_ivp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class VanDerPol:
    def __init__(self):
        self.oscillators = []
        self.df = pd.DataFrame()

    def add_oscillator(self, mu, x0=1, y0=0):
        class new_oscillator:
            def __init__(self, mu, x0, y0):
                self.mu = mu
                self.x0 = x0
                self.y0 = y0

            def __str__(self):
                return f"mu={self.mu}, x0={self.x0}, y0={self.y0}"

        self.oscillators.append(new_oscillator(mu, x0, y0))

    def delete_oscillator(self, i):
        self.oscillators.pop(i)

    def get_sim_data(self, duration=30.0, dt=0.01):
        # durations = np.arange(0, duration, dt, dtype=float)
        durations = np.linspace(0, duration, int(duration / dt))
        # df = pd.DataFrame(durations)

        for o in self.oscillators:

            def vdp(t, z):
                x, y = z
                return [y, o.mu * (1 - x**2) * y - x]

            data = solve_ivp(vdp, [0, duration], [o.x0, o.y0], t_eval=durations)
            # df = pd.DataFrame(data.y[0])
            # df = pd.DataFrame()
            df = pd.DataFrame(data.y[0])
            # df[o] = pd.Series(data.y[0])
            # print(data.y[0])
            self.df[o] = df
            # print(self.df)
            print(self.df)

    def plot(self, tmin=0.0, tmax=30.0):
        plt.plot(self.df)

vdp = VanDerPol()
vdp.add_oscillator(1.0)  # oscillator 0
vdp.add_oscillator(3.0)  # oscillator 1
vdp.add_oscillator(2.0)  # oscillator 2
vdp.delete_oscillator(1)
print(vdp.get_sim_data(dt=0.01))
vdp.plot(tmin=10)


来源: stackexchange

问:
How to prevent UrlFetchApp.fetch from going on forever?
First of all let me clarify that I have read the answers of the similar questions

Lower the timeout for urlFetchApp.fetch function and
Timeout Error - DHL API to Google Sheets - UrlFetchApp

but this question is different. Here I'm asking why UrlFetchApp.fetch and UrlFetchApp.fetchAll are blocking the script execution entirely (never return response) until you get an "Exceeded maximum execution time" error. It happens occasionally for some URLs like the one at the example shown bellow

function fetch_test() {
  const res = UrlFetchApp.fetch('https://www.usnews.com/news/world/articles/2022-12-06/turkey-again-threatens-greece-for-arming-aegean-islands')
}
```

You will notice that fetch never ends until you get an "Exceeded maximum execution time" error.
It happens to fetch and fetchAll but I can't figure out why. How can I prevent/handle this situation?

ContentLicense: CC BY-SA 4.0

Body:
First of all let me clarify that I have read the answers of the similar questions

Lower the timeout for urlFetchApp.fetch function and
Timeout Error - DHL API to Google Sheets - UrlFetchApp

but this question is different. Here I'm asking why UrlFetchApp.fetch and UrlFetchApp.fetchAll are blocking the script execution entirely (never return response) until you get an "Exceeded maximum execution time" error. It happens occasionally for some URLs like the one at the example shown bellow

function fetch_test() {
  const res = UrlFetchApp.fetch('https://www.usnews.com/news/world/articles/2022-12-06/turkey-again-threatens-greece-for-arming-aegean-islands')
}

You will notice that fetch never ends until you get an "Exceeded maximum execution time" error.
It happens to fetch and fetchAll but I can't figure out why. How can I prevent/handle this situation?


问:
Is there a way to log the React component hierarchy to the console?
I would like to log the React component hierarchy (not the DOM!) to the console so that I can see what components are in the tree during Jest tests, but have not come across any pre-built way to do this.

Is there an existing way to accomplish this, either via an official or 3rd party package?


问:
IntelliJ template dialog list
I have created a code template in IntelliJ IDEA that creates a new class for me.
The problem is, as far as I understood, IntelliJ by default supports only simple strings as variables in the dialog box.

How can I create not a simple string line but a drop-down list with my predefined values? See the example on the screenshot.

Title: IntelliJ template dialog list


问:
NSWindow title bar color only works for active window?
I've got a Qt app running under MacOS/X, and I'd like to set the color of the app's windows.  Based on various Stackoverflow answers I came up with this little Objective-C function which more or less works:

```<code>extern "C" void changeTitleBarColor(WId winId, double red, double green, double blue, double alpha, bool makeTextWhite)
{
   if (winId == 0) return;

   NSView* view = (NSView*)winId;
   NSWindow* window = [view window];
   if (alpha > 0.0) window.backgroundColor = [NSColor colorWithRed:red green:green blue:blue alpha:alpha];
               else window.backgroundColor = NULL;  // set title bar back to its default appearance
}
</code>```

However, there's one problem -- the only time the window displays its custom title-bar color is when it's the active window (i.e. after I click on it).  Any other windows in my app that aren't currently the active window revert their title bar back to the system-default appearance until I click on them again.

Is there any way to get MacOS/X to retain my custom color when the window isn't the currently active window?

(see attached screenshot -- desired behavior is that all three windows' title bars would be green, not just the one I most recently clicked on)

Body:
I've got a Qt app running under MacOS/X, and I'd like to set the color of the app's windows.  Based on various Stackoverflow answers I came up with this little Objective-C function which more or less works:

extern "C" void changeTitleBarColor(WId winId, double red, double green, double blue, double alpha, bool makeTextWhite)
{
   if (winId == 0) return;

   NSView* view = (NSView*)winId;
   NSWindow* window = [view window];
   if (alpha > 0.0) window.backgroundColor = [NSColor colorWithRed:red green:green blue:blue alpha:alpha];
               else window.backgroundColor = NULL;  // set title bar back to its default appearance
}

However, there's one problem -- the only time the window displays its custom title-bar color is when it's the active window (i.e. after I click on it).  Any other windows in my app that aren't currently the active window revert their title bar back to the system-default appearance until I click on them again.

Is there any way to get MacOS/X to retain my custom color when the window isn't the currently active window?

(see attached screenshot -- desired behavior is that all three windows' title bars would be green, not just the one I most recently clicked on)


问:
How to Renew Token/Activation Link for a Delta Share Recipient?
Seems like the old token expired. Is there a way to renew without deleting the recipient?</p>


问:
How to calculate the columnwise minimum of a dask pivot table?
I would like to create a pivot table in dask and then calculate the column wise minimum.

```<code>import dask.dataframe as dd
from dask.distributed import Client

client = Client()

df = dd.read_csv("data.csv")

# In order to use pivot_table, the columns use as index and columns need to be categorical:
df = df.categorize(columns=['A', 'B'])

#df['A'] = df['A'].cat.as_ordered()
#df['B'] = df['B'].cat.as_ordered()

pt = df.pivot_table(index='A', columns='B', values='C', aggfunc='mean')

pt.min().compute()
</code>```

TypeError: Categorical is not ordered for operation min
you can use .as_ordered() to change the Categorical to an ordered one

```<code>...

# Trying to uncategorize the index, takes forever
pt.index = list(pt.index)
pt.min().compute()
</code>```

Is there a better way to archive this?

Body:
I would like to create a pivot table in dask and then calculate the column wise minimum.

import dask.dataframe as dd
from dask.distributed import Client

client = Client()

df = dd.read_csv("data.csv")

# In order to use pivot_table, the columns use as index and columns need to be categorical:
df = df.categorize(columns=['A', 'B'])

#df['A'] = df['A'].cat.as_ordered()
#df['B'] = df['B'].cat.as_ordered()

pt = df.pivot_table(index='A', columns='B', values='C', aggfunc='mean')

pt.min().compute()

TypeError: Categorical is not ordered for operation min
you can use .as_ordered() to change the Categorical to an ordered one

...

# Trying to uncategorize the index, takes forever
pt.index = list(pt.index)
pt.min().compute()

Is there a better way to archive this?


问:
Replacing all special characters but the dot in a string also replaces the dot
I am trying to replace special characters by an underscore in a given string (a badly formatted file path) but I cannot get it to work.

Here is the code:

import string, re
from unidecode import unidecode

punc = string.punctuation
punc = string.punctuation.replace(r'.','') # remove the dot from that string
pattern = re.compile(rf'[{punc}]')
# I also tried this as pattern; but it doesn't help:
# pattern = r'[' + punc + ']'

test_string = r"\\some\random.path${}[]~(éè%&)ç\file.txt"
test_string = unidecode(test_string) # kick off accented letters

print(re.sub(pattern, '_', test_string))
>: \\some\random_path_______ee___c\file_txt
```
<p>Actually, because the 'dot' is <em>not</em> in the pattern string, I cannot understand <em>why</em> it has been replaced? (I don't want it to be replaced)</p>
<p>More strangely, if I shuffle the punctuation string:</p>
```from random import shuffle

punc = string.punctuation
punc = string.punctuation.replace(r'.','') # remove the dot

# shuffle punctuation:
punc = list(punc)
shuffle(punc)
punc = ''.join(punc)

pattern = re.compile(rf'[{punc}]')

```
<p>it sometimes raise an error such as:</p>
<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):

  File "/tmp/ipykernel_3429192/3014469097.py", line 1, in <cell line: 1>
    pattern = re.compile(rf'[' + punc +']')

  File "/usr/lib/python3.10/re.py", line 251, in compile
    return _compile(pattern, flags)

  File "/usr/lib/python3.10/re.py", line 303, in _compile
    p = sre_compile.compile(pattern, flags)

  File "/usr/lib/python3.10/sre_compile.py", line 788, in compile
    p = sre_parse.parse(p, flags)

  File "/usr/lib/python3.10/sre_parse.py", line 969, in parse
    raise source.error("unbalanced parenthesis")

error: unbalanced parenthesis
</code>```

or, after some other shuffling which doesn't raise the above error, I got:

print(re.sub(pattern, '_', test_string))
>: \\some\random.path${}[]~(ee%&)c\file.txt

pattern
>: re.compile(r'[|)_&{;=^\'-~]@,["><$:/!}*\#+(?%`]', re.UNICODE)
```
<p>here it doesn't seem to work at all.</p>
<p>Also, as mentioned in the first code block and here, I also tried not to use <code>re.compile()</code> by directly using: <code>pattern = r'[' + punc + ']'</code> but it doesn't help.</p>
<p>This may also be interesting:</p>
<pre class="lang-py prettyprint-override"><code>for i in range(len(punc)):
    punc = punc[:-1]
    pattern = r'[' + punc + ']'
    print(f'{i}: pattern: {pattern} replaced_str: ',  re.sub(pattern, '_', test_string))

0: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_`{|}] replaced_str:  \\some\random_path_____~_ee___c\file_txt
1: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_`{|] replaced_str:  \\some\random_path__}__~_ee___c\file_txt
2: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_`{] replaced_str:  \\some\random_path__}__~_ee___c\file_txt
3: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_`] replaced_str:  \\some\random_path_{}__~_ee___c\file_txt
4: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_] replaced_str:  \\some\random_path_{}__~_ee___c\file_txt
5: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^] replaced_str:  \\some\random_path_{}__~_ee___c\file_txt
6: pattern: [!"#$%&'()*+,-/:;<=>?@[\]] replaced_str:  \\some\random_path_{}__~_ee___c\file_txt
Traceback (most recent call last):

  File "/tmp/ipykernel_3401192/4037584865.py", line 4, in <cell line: 1>
    print(f'{i}: pattern: {pattern} replaced_str: ',  re.sub(pattern, '_', test_string))

  File "/usr/lib/python3.10/re.py", line 209, in sub
    return _compile(pattern, flags).sub(repl, string, count)

  File "/usr/lib/python3.10/re.py", line 303, in _compile
    p = sre_compile.compile(pattern, flags)

  File "/usr/lib/python3.10/sre_compile.py", line 788, in compile
    p = sre_parse.parse(p, flags)

  File "/usr/lib/python3.10/sre_parse.py", line 955, in parse
    p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)

  File "/usr/lib/python3.10/sre_parse.py", line 444, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested + 1,

  File "/usr/lib/python3.10/sre_parse.py", line 550, in _parse
    raise source.error("unterminated character set",

error: unterminated character set
</code>```

In addition to the why, how could I achieve that goal properly?

Tested with Python 3.9, 3.10 and 3.11.

Ref: https://docs.python.org/3/library/string.html

This is nice (not tested yet, I'll come latter to edit and share my results): Best way to strip punctuation from a string but it actually remove the special char, it doesn't replace them. And it doesn't explain why my solution is working in such a weird way.

Body:
I am trying to replace special characters by an underscore in a given string (a badly formatted file path) but I cannot get it to work.

Here is the code:

import string, re
from unidecode import unidecode

punc = string.punctuation
punc = string.punctuation.replace(r'.','') # remove the dot from that string
pattern = re.compile(rf'[{punc}]')
# I also tried this as pattern; but it doesn't help:
# pattern = r'[' + punc + ']'

test_string = r"\\some\random.path${}[]~(éè%&)ç\file.txt"
test_string = unidecode(test_string) # kick off accented letters

print(re.sub(pattern, '_', test_string))
>: \\some\random_path_______ee___c\file_txt

Actually, because the 'dot' is not in the pattern string, I cannot understand why it has been replaced? (I don't want it to be replaced)

More strangely, if I shuffle the punctuation string:

from random import shuffle

punc = string.punctuation
punc = string.punctuation.replace(r'.','') # remove the dot

# shuffle punctuation:
punc = list(punc)
shuffle(punc)
punc = ''.join(punc)

pattern = re.compile(rf'[{punc}]')

it sometimes raise an error such as:

Traceback (most recent call last):

  File "/tmp/ipykernel_3429192/3014469097.py", line 1, in <cell line: 1>
    pattern = re.compile(rf'[' + punc +']')

  File "/usr/lib/python3.10/re.py", line 251, in compile
    return _compile(pattern, flags)

  File "/usr/lib/python3.10/re.py", line 303, in _compile
    p = sre_compile.compile(pattern, flags)

  File "/usr/lib/python3.10/sre_compile.py", line 788, in compile
    p = sre_parse.parse(p, flags)

  File "/usr/lib/python3.10/sre_parse.py", line 969, in parse
    raise source.error("unbalanced parenthesis")

error: unbalanced parenthesis

or, after some other shuffling which doesn't raise the above error, I got:

print(re.sub(pattern, '_', test_string))
>: \\some\random.path${}[]~(ee%&)c\file.txt

pattern
>: re.compile(r'[|)_&{;=^\'-~]@,["><$:/!}*\#+(?%`]', re.UNICODE)

here it doesn't seem to work at all.

Also, as mentioned in the first code block and here, I also tried not to use re.compile() by directly using: pattern = r'[' + punc + ']' but it doesn't help.

This may also be interesting:

for i in range(len(punc)):
    punc = punc[:-1]
    pattern = r'[' + punc + ']'
    print(f'{i}: pattern: {pattern} replaced_str: ',  re.sub(pattern, '_', test_string))

0: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_`{|}] replaced_str:  \\some\random_path_____~_ee___c\file_txt
1: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_`{|] replaced_str:  \\some\random_path__}__~_ee___c\file_txt
2: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_`{] replaced_str:  \\some\random_path__}__~_ee___c\file_txt
3: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_`] replaced_str:  \\some\random_path_{}__~_ee___c\file_txt
4: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^_] replaced_str:  \\some\random_path_{}__~_ee___c\file_txt
5: pattern: [!"#$%&'()*+,-/:;<=>?@[\]^] replaced_str:  \\some\random_path_{}__~_ee___c\file_txt
6: pattern: [!"#$%&'()*+,-/:;<=>?@[\]] replaced_str:  \\some\random_path_{}__~_ee___c\file_txt
Traceback (most recent call last):

  File "/tmp/ipykernel_3401192/4037584865.py", line 4, in <cell line: 1>
    print(f'{i}: pattern: {pattern} replaced_str: ',  re.sub(pattern, '_', test_string))

  File "/usr/lib/python3.10/re.py", line 209, in sub
    return _compile(pattern, flags).sub(repl, string, count)

  File "/usr/lib/python3.10/re.py", line 303, in _compile
    p = sre_compile.compile(pattern, flags)

  File "/usr/lib/python3.10/sre_compile.py", line 788, in compile
    p = sre_parse.parse(p, flags)

  File "/usr/lib/python3.10/sre_parse.py", line 955, in parse
    p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)

  File "/usr/lib/python3.10/sre_parse.py", line 444, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested + 1,

  File "/usr/lib/python3.10/sre_parse.py", line 550, in _parse
    raise source.error("unterminated character set",

error: unterminated character set

In addition to the why, how could I achieve that goal properly?

Tested with Python 3.9, 3.10 and 3.11.

Ref: https://docs.python.org/3/library/string.html

This is nice (not tested yet, I'll come latter to edit and share my results): Best way to strip punctuation from a string but it actually remove the special char, it doesn't replace them. And it doesn't explain why my solution is working in such a weird way.


问:
how do i put the popup in front of other elements in react
I have a popup that opens when the Add New Device button in the navbar is pressed. I'm printing the devices saved from this popup in produtcs page. However, popup lags behind the cards created for each product. I want you to appear first. How can I fix?

App.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

</code>```

Navbar.js

```<code>import React, { useState } from 'react'
import AddProducts from './AddProduct';
import './components.css'
import 'reactjs-popup/dist/index.css';

function Navbar() {

    const [openPopup, setOpenPopup] = useState(false);

    return (
        <div>
            <nav className="navbar bg-light">
                <div className="container-fluid">
                    <div className='justify-content-start'>
                        <a className="navbar-brand">Products</a>
                        <button className="btn btn-outline-danger btn-sm" onClick={() => setOpenPopup(true)}>+ Add New</button>
                        <AddProducts trigger={openPopup} setTrigger={setOpenPopup}></AddProducts>
                    </div>
                    <form className="d-flex" role="search">
                        <input className="form-control me-2" type="search" placeholder="Search" aria-label="Search" />
                        <button className="btn btn-outline-success" type="submit">Search</button>
                    </form>
                </div>
            </nav>
        </div >
    )
}

export default Navbar

</code>```

AddProducts.js (popup)

```<code>import React, { useState } from 'react'
import './components.css';
import { BiX } from "react-icons/bi";
import { addDoc, collection } from "firebase/firestore"
import { db } from "../firebase-config";
import 'reactjs-popup/dist/index.css';

const AddProducts = (props) => {

    const [name, setName] = useState("");
    const [coordinates, setCoordinates] = useState("");
    const [format, setFormat] = useState();

    const productsCollectionRef = collection(db, "products");

    const add = async (e) => {
        e.preventDefault();
        await addDoc(productsCollectionRef, { name: name, coordinates: coordinates, format: format });
    };

    return (props.trigger) ? (
        <div className="popup">
            <div className="popupTop ">
                <div className="row">
                    <p className='col-md-10'>Add New Device</p>
                    <p className=" col-md-2 closeBtn" onClick={() => props.setTrigger(false)}>
                        <BiX size="20" color="black"></BiX>
                    </p>
                    {props.children}
                </div>
            </div>
            <div className="popupContent">
                <form autoComplete='off' className="form-group"
                    onSubmit={add}>
                    <div className="mb-3 inputAP">
                        <label className="form-label">Name *</label>
                        <input className="form-control"
                            required
                            onChange={(e) => setName(e.target.value)} value={name} />
                    </div>
                    <div className="mb-3 inputAP">
                        <label className="form-label">Coordinates *</label>
                        <input className="form-control"
                            required
                            onChange={(e) => setCoordinates(e.target.value)} value={coordinates} />
                    </div>
                    <div className="mb-3">
                        <label className="form-label">Format *</label>
                        <div className="form-check">
                            <input className="form-check-input" type="radio" name="format" value={"16:9"}
                                onChange={(e) => setFormat(e.target.value)} /> 16:9
                        </div>
                        <div className="form-check">
                            <input className="form-check-input" type="radio" name="format" value={"4:3"}
                                onChange={(e) => setFormat(e.target.value)} /> 4:3
                        </div>
                    </div>
                </form>
                <div className="mb-3">
                <button className="btn btn-success" onClick={add}>Submit</button>
                </div>
            </div>
        </div>

    ) : "";
}

export default AddProducts;
</code>```

Products.js

```<code>import React, { useEffect, useState } from 'react'
import { getDocs, collection, doc, deleteDoc } from 'firebase/firestore'
import { db } from '../firebase-config';
import './components.css';
import { BiTrash, BiDesktop } from "react-icons/bi";

function Products() {

  const [listProducts, setListProducts] = useState([]);
  const productsCollectionRef = collection(db, "products");

  useEffect(() => {
    const getProducts = async () => {
      const data = await getDocs(productsCollectionRef);
      setListProducts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    };
    getProducts();
  });

  const deleteProduct = async (id) => {
    const productDoc = doc(db, "products", id)
    await deleteDoc(productDoc);
  };

  return (
    <div className="container productList ">
      <div className="row productRow">
        {listProducts.map((product) => {
          return (
            <div class="card col-md-3 mb-3 mx-2 border-secondary ">
              <div class="card-header bg-transparent border-secondary">{product.name}</div>
              <div class="card-body text-secondary">
                <p class="card-text">Coordinates: {product.coordinates}</p>
              </div>
              <div class="card-footer bg-transparent border-secondary">
                <div className="formatProduct">
                  <p className='formatIcon formatItem mx-2'><BiDesktop size="20" color="black"></BiDesktop></p>
                  <p className="card-text formatItem">{product.format}</p>
                </div>
                <div className="deleteProduct">
                  <p onClick={() => { deleteProduct(product.id) }}><BiTrash size="20" color="red"></BiTrash></p>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div >
  );
}

export default Products

</code>```

This is how it looks now on the back of the cards.

Body:
I have a popup that opens when the Add New Device button in the navbar is pressed. I'm printing the devices saved from this popup in produtcs page. However, popup lags behind the cards created for each product. I want you to appear first. How can I fix?

App.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Navbar.js

import React, { useState } from 'react'
import AddProducts from './AddProduct';
import './components.css'
import 'reactjs-popup/dist/index.css';

function Navbar() {

    const [openPopup, setOpenPopup] = useState(false);

    return (

                        Products
                        <button className="btn btn-outline-danger btn-sm" onClick={() => setOpenPopup(true)}>+ Add New</button>
                        <AddProducts trigger={openPopup} setTrigger={setOpenPopup}></AddProducts>

                    <form className="d-flex" role="search">
                        <input className="form-control me-2" type="search" placeholder="Search" aria-label="Search" />
                        <button className="btn btn-outline-success" type="submit">Search</button>
                    </form>

    )
}

export default Navbar

AddProducts.js (popup)

import React, { useState } from 'react'
import './components.css';
import { BiX } from "react-icons/bi";
import { addDoc, collection } from "firebase/firestore"
import { db } from "../firebase-config";
import 'reactjs-popup/dist/index.css';

const AddProducts = (props) => {

    const [name, setName] = useState("");
    const [coordinates, setCoordinates] = useState("");
    const [format, setFormat] = useState();

    const productsCollectionRef = collection(db, "products");

    const add = async (e) => {
        e.preventDefault();
        await addDoc(productsCollectionRef, { name: name, coordinates: coordinates, format: format });
    };

    return (props.trigger) ? (

Add New Device

 props.setTrigger(false)}>
                        <BiX size="20" color="black"></BiX>

                    {props.children}

                <form autoComplete='off' className="form-group"
                    onSubmit={add}>

                        Name *
                        <input className="form-control"
                            required
                            onChange={(e) => setName(e.target.value)} value={name} />

                        Coordinates *
                        <input className="form-control"
                            required
                            onChange={(e) => setCoordinates(e.target.value)} value={coordinates} />

                        Format *

                            <input className="form-check-input" type="radio" name="format" value={"16:9"}
                                onChange={(e) => setFormat(e.target.value)} /> 16:9

                            <input className="form-check-input" type="radio" name="format" value={"4:3"}
                                onChange={(e) => setFormat(e.target.value)} /> 4:3

                </form>

                <button className="btn btn-success" onClick={add}>Submit</button>

    ) : "";
}

export default AddProducts;

Products.js

import React, { useEffect, useState } from 'react'
import { getDocs, collection, doc, deleteDoc } from 'firebase/firestore'
import { db } from '../firebase-config';
import './components.css';
import { BiTrash, BiDesktop } from "react-icons/bi";

function Products() {

  const [listProducts, setListProducts] = useState([]);
  const productsCollectionRef = collection(db, "products");

  useEffect(() => {
    const getProducts = async () => {
      const data = await getDocs(productsCollectionRef);
      setListProducts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    };
    getProducts();
  });

  const deleteProduct = async (id) => {
    const productDoc = doc(db, "products", id)
    await deleteDoc(productDoc);
  };

  return (

        {listProducts.map((product) => {
          return (

{product.name}

Coordinates: {product.coordinates}

<BiDesktop size="20" color="black"></BiDesktop>

{product.format}

 { deleteProduct(product.id) }}><BiTrash size="20" color="red"></BiTrash>

          );
        })}

  );
}

export default Products

This is how it looks now on the back of the cards.


Title: after slicing matrix, how to average between connecting arrays

Body:
I have a matrix A of size 256x256.

I have divided it in 16 arrays of 32 by 32, keeping its original array connections.

Then I want to average the border of each array with its adjacent  connection.

Let's say,  we have a matrix A of size 12x12, (then I want 16 chunks of 3x3)
I am using blockshaped ( Slice 2d array into smaller 2d arrays) to slice the matrix

np.random.seed(365)
c = np.arange(144).reshape((12, 12))

L=blockshaped(c, 3, 3)

Visually:

c=[[ 0   1   2 |  3   4   5  | 6   7   8   | 9  10  11]
  [ 12  13  14 | 15  16  17  | 18  19  20  | 21  22  23]
  [ 24  25  26 | 27  28  29  | 30  31  32  | 33  34  35]
------------------------------------------------------
  [ 36  37  38 | **39  40  41**  | 42  43  44  | 45  46  47]
  [ 48  49  50 | **51  52  53**  | 54  55  56  | 57  58  59]
  [ 60  61  62 | **63  64  65**  | 66  67  68  | 69  70  71]
------------------------------------------------------
  [ 72  73  74 | 75  76  77  | 78  79  80  | 81  82  83]
  [ 84  85  86 | 87  88  89  | 90  91  92  | 93  94  95]
  [ 96  97  98 | 99 100 101  | 102 103 104 | 105 106 107]
------------------------------------------------------
  [108 109 110 | 111 112 113 | 114 115 116 | 117 118 119]
  [120 121 122 | 123 124 125 | 126 127 128 | 129 130 131]
  [132 133 134 | 135 136 137 | 138 139 140 | 141 142 143]]

If I take the chuck marked with **

39  40  41
51  52  53
63  64  65

How can I average the value of the boundaries?

39  40  41 with 27  28  29

63 64 65 with 75 76 77

and

39  51  63 with 38  50  62
41  53  65 with 42  57  69

any ideas will help me a lot


问:
Google Analytics Data metrics doesnt match with UI
this is Sergio from Msights Team

We have some questions about some metrics that have differences between the UI and the API, including " total revenue ", but we have the same problem with other metrics.

We have tried to download data with more than 2 or 3 last days and not only with the day immediately before, in addition the data downloaded by api doesnt have some type of filter other than by date.

Could you help me see what the difference could be?

Thank you!


问:
After generating signed aab file in Android Studio, some files get size 0
When I generate the aab file, to put in the Google Store. Some MP4 files in the raw folder get size 0.

This only happens when I go to make the signed version.

If I make a normal Bundle (without subscription) it works.

Analyzing de App Bundle

I tried to update the Android Studio or Gradle version. And I was not successful.


问:
Receive data from any source and then print that data and the source
I am creating a program in C, and I need assistance identifying the source for an MPI program when I receive the data from any source. Essentially, the lines of code are below:

```<code>int i; // Declares the variable to store the received int in.

if(WORLD_RANK == 0) {

    MPI_Recv(&i, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("Received %d from %d\n", i, SOURCE_WORLD_RANK)

} else { MPI_Send()}// complete some work here and then send data back
</code>```

SOURCE_WORLD_RANK needs to be the source of the data I received, the value saved in I.

Body:
I am creating a program in C, and I need assistance identifying the source for an MPI program when I receive the data from any source. Essentially, the lines of code are below:

int i; // Declares the variable to store the received int in.

if(WORLD_RANK == 0) {

    MPI_Recv(&i, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("Received %d from %d\n", i, SOURCE_WORLD_RANK)

} else { MPI_Send()}// complete some work here and then send data back

SOURCE_WORLD_RANK needs to be the source of the data I received, the value saved in I.


问:
Changed requirements for automated web storage in Chrome
Some time ago I built a web application which sought to escalate privileges from the user so as to gain persistent storage privileges (to store a good amount of data). At the time and apparently now as well, Chrome advertised that sites could automatically get persistent storage by having one's site among one's bookmarks or by the user having granted the site notification permissions.

I am wondering if there has been an (undocumented) change in these requirements because it seems my web app now always skips over the permission asking for notification permissions because await navigator.storage.persist() always resolves to a true value, despite the fact that I no longer have the site I am testing (localhost) among my bookmarks and have removed the notifications permission for localhost.

Does anyone have information on what the current standards are for automatic storage persistence at least as far as Chrome? Are there any other site permissions I may have granted which might be treating localhost/127.0.0.1 as having escalated privileges?


问:
How to store data from odeint() directly into a menmap instead of array?
I am working on solving a differential equation that solves a system of double pendulums. However, my code requires me to do a billion calculations, so my memory runs out and an error appears.

My original question can be seen here: How can a billions of computations be done without having memory error in python?

An individual told me to use a menmap. The menmap documentation https://numpy.org/doc/stable/reference/generated/numpy.memmap.html#numpy-memmap shows me how to transfer from an array into a menmap but in my case, I want to transfer my data directly into the menmap as storing the data in the array returns a memory error.

Any kind of help to help to store the data directly into the menmap would be appreciated.


问:
How to track the opening of a tab in a browser?
Some of the chrome extension opens third-party sites, I would like to determine which one. Maybe the window object contains information about what exactly opened the tab, but I could not find it. Or maybe there are other options?

Tried to find information about the open tab in the window object through devtools.


问:
How to pull out the 3D model of the character selection screen?
is there any way to get a 3d model of the location that is behind the character? screenshot

I investigated mpq files in data folder, but there were only sets of textures (frames, buttons, etc.) I tried to download custom WoW interface to narrow down the textures, but there were also sets of buttons, although there was another location behind the character.


问:
Writing Javascript Fetch POST call to FileMaker Database. Receiving successful status, but 1630 error from FileMaker with empty Response Array
It seems to me that this is an extremely simple problem and task I'm trying to solve:

I have an HTML page I've made, extremely simple, the user types in a code they'll be given and presses the 'sign-in' button. This button triggers two API calls in sequence:

a POST call to a FileMaker database on the same server, retrieving an access token and returning it.

a GET call that executes a FileMaker script in that same database, retrieving a URL for the user based on the code they input.

Then, we do a redirect on the web-page taking them to their application... or at least that is what is supposed to happen. This error has been plaguing me for days and I'm sure at this point I must be missing something so fundamental and simple I'd never think of it. Below is all the code, with some obvious dummy info placed in for actual values:

```<code>    <script>

        function onSubmit() {

            token = document.getElementById('r0c0m2i1').value;

            // API Call to start session

                    async function GetToken() {

               let auth = {};

            const response = await
                  fetch('https://HostName/fmi/data/vLatest/databases/DatabaseName/sessions', {
                method: 'POST',
                body: auth,
                headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'Authorization': 'Basic Base64EncodedCredentials',
                     },
                               }
                             );

                        let Result = await response;

            // console.log(data);

            return Result

                    }

                      SessionResult = GetToken();

            // API Call to Get call script and get data

            URL = "";

            // fetch('https://HostName/fmi/data/vLatest/databases/ccNP_Config/layouts/LayoutName/ScriptName?script.param=' + token)
            // .then(URL => response.json())
            // .then(json => data.innerHTML = JSON.stringify(json))
            // .catch(err => console.log('GET Request Failed', err));

            // alert(json);

            // Go to returned URL

            // window.location.replace(URL);
        }

    </script>

</code>```

For what its worth, I'm not too concerned about the 'GET' call because I haven't even been able to really test that part with the 1st part not working yet.

https://help.claris.com/en/data-api-guide/content/log-in-database-session.html - The documentation from FileMaker for their Data API.

I've made many API calls and scripts within FileMaker using cURL protocols and way of doing things, so this is my first foray into Javascript API calls from a browser environment.

Basically, I'm getting a 200 status (indicating a successful call), but FileMaker returns a 1630 which apparently means the URL is incorrect in some fashion, with only the message below to guide my debugging:

message":"Unexpected token o in JSON at position 1","code":"1630"

According to everyone on the internet, this error indicates that there's some issue with my parsing or with the object in question (probably the body parameter in the POST call). I've tried making it a string, empty, an array; everything I can think of. It will not return the parameter successfully that the documentation indicates it should.

I have already done this API call in Postman successfully with all of my variations as well, but I know Postman is much easier to get a successful call for lots of reasons.

Please help guide my debugging and save me from this morass  I've found myself stuck in.

Body:
It seems to me that this is an extremely simple problem and task I'm trying to solve:

I have an HTML page I've made, extremely simple, the user types in a code they'll be given and presses the 'sign-in' button. This button triggers two API calls in sequence:

a POST call to a FileMaker database on the same server, retrieving an access token and returning it.

a GET call that executes a FileMaker script in that same database, retrieving a URL for the user based on the code they input.

Then, we do a redirect on the web-page taking them to their application... or at least that is what is supposed to happen. This error has been plaguing me for days and I'm sure at this point I must be missing something so fundamental and simple I'd never think of it. Below is all the code, with some obvious dummy info placed in for actual values:

For what its worth, I'm not too concerned about the 'GET' call because I haven't even been able to really test that part with the 1st part not working yet.

https://help.claris.com/en/data-api-guide/content/log-in-database-session.html - The documentation from FileMaker for their Data API.

I've made many API calls and scripts within FileMaker using cURL protocols and way of doing things, so this is my first foray into Javascript API calls from a browser environment.

Basically, I'm getting a 200 status (indicating a successful call), but FileMaker returns a 1630 which apparently means the URL is incorrect in some fashion, with only the message below to guide my debugging:

message":"Unexpected token o in JSON at position 1","code":"1630"

According to everyone on the internet, this error indicates that there's some issue with my parsing or with the object in question (probably the body parameter in the POST call). I've tried making it a string, empty, an array; everything I can think of. It will not return the parameter successfully that the documentation indicates it should.

I have already done this API call in Postman successfully with all of my variations as well, but I know Postman is much easier to get a successful call for lots of reasons.

Please help guide my debugging and save me from this morass  I've found myself stuck in.


问:
pyqt6 / AttributeError: type object 'QSettings' has no attribute 'IniFormat'
i upgraded from pyqt5 to pyqt6 but i get an error (AttributeError: type object 'QSettings' has no attribute 'IniFormat'.) with this simple code.

```<code>from PyQt6.QtCore import QSettings

class Savesettings:

    def __init__(self,parent):
        self.parent = parent
        self.settings = QSettings("config.ini", QSettings.IniFormat)
</code>```

it works with pyqt5 and even with pyside6 but not with pyqt6.
i assume they changed something a bit but i cant find about it anywhere on the internet.
i'd really appreciate it if someone could help me out

Body:
i upgraded from pyqt5 to pyqt6 but i get an error (AttributeError: type object 'QSettings' has no attribute 'IniFormat'.) with this simple code.

from PyQt6.QtCore import QSettings

class Savesettings:

    def __init__(self,parent):
        self.parent = parent
        self.settings = QSettings("config.ini", QSettings.IniFormat)

it works with pyqt5 and even with pyside6 but not with pyqt6.
i assume they changed something a bit but i cant find about it anywhere on the internet.
i'd really appreciate it if someone could help me out


问:
I need to install tensorflow 1.x and the code works until last week on google colab. Now it does not work
I need to install TensorFlow 1.x for solving my problem. When I run the below codes a week back on google colab (python version 3.8). It installed successfully, and since then I haven't changed anything on my code. However, now, when I run the same code a week later, it does not work,

```<code>!pip install tensorflow==1.14
</code>```

It shows the below error.

Alternatively, I tried to change the Python version to 3.6.9 by using the below command,

```<code>!sudo update-alternatives --config python3
!apt-get install python3-pip
!python -m pip install --upgrade pip --user
</code>```

After that I can install tensorflow 1.14. But then it says to restart the runtime. When I restart the runtime, it cannot connect anymore. It always shows connecting, below is the error view,

I do not know what changes of google colab cause this issue. Any help to resolve this issue would be appreciated.

Body:
I need to install TensorFlow 1.x for solving my problem. When I run the below codes a week back on google colab (python version 3.8). It installed successfully, and since then I haven't changed anything on my code. However, now, when I run the same code a week later, it does not work,

!pip install tensorflow==1.14

It shows the below error.

Alternatively, I tried to change the Python version to 3.6.9 by using the below command,

!sudo update-alternatives --config python3
!apt-get install python3-pip
!python -m pip install --upgrade pip --user

After that I can install tensorflow 1.14. But then it says to restart the runtime. When I restart the runtime, it cannot connect anymore. It always shows connecting, below is the error view,

I do not know what changes of google colab cause this issue. Any help to resolve this issue would be appreciated.


问:
Cloudformation conditionals Yaml
I have to create an auto scaling group in two regions and the only difference between the two are the subnets. us-east-1 has 1 subnet whereas us-east-2 has two. How can I use the condition to call the subnet value from region map.

Mappings:
  RegionMap:
    us-east-1:
      AMI: "ami-066f487d3b6819b0d"
      Subnet1: "subnet-0e6f12f64042ea5b1"
    us-east-2:
      AMI: "ami-0aef5e0adcbc7cc0f"
      Subnet1: "subnet-0e6f12f64042ea5b1"
      Subnet2: "subnet-0bc661bb8d98f3f03"

Conditions:
  region: !Equals [!Ref us-east-2, Subnet2]

  autoscaling:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      AutoScalingGroupName: asg1
      VPCZoneIdentifier:
        - !FindInMap [RegionMap, !Ref "AWS::Region", Subnet1]
        - If regions = us-east-2 then !FindInMap [RegionMap, !Ref "AWS::Region", Subnet2] # This is what I need to figure out

```

I couldn't find any examples of this.  Has anyone used a region map and used conditionals with it?

Title: Cloudformation conditionals Yaml

Body:
I have to create an auto scaling group in two regions and the only difference between the two are the subnets. us-east-1 has 1 subnet whereas us-east-2 has two. How can I use the condition to call the subnet value from region map.

Mappings:
  RegionMap:
    us-east-1:
      AMI: "ami-066f487d3b6819b0d"
      Subnet1: "subnet-0e6f12f64042ea5b1"
    us-east-2:
      AMI: "ami-0aef5e0adcbc7cc0f"
      Subnet1: "subnet-0e6f12f64042ea5b1"
      Subnet2: "subnet-0bc661bb8d98f3f03"

Conditions:
  region: !Equals [!Ref us-east-2, Subnet2]

  autoscaling:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      AutoScalingGroupName: asg1
      VPCZoneIdentifier:
        - !FindInMap [RegionMap, !Ref "AWS::Region", Subnet1]
        - If regions = us-east-2 then !FindInMap [RegionMap, !Ref "AWS::Region", Subnet2] # This is what I need to figure out

I couldn't find any examples of this.  Has anyone used a region map and used conditionals with it?


问:
How to do an action when a new data comes from API
I'm fetching some data from an API and displaying it in a list. When that API update data, I want to reproduce a sound, how can I do that?

I tried to use Streams to implement that, but it wasn't successful.


问:
React Native not connecting to Firebase Database
I've been working with a React Native app that utilizes the Firebase Realtime database for several months now. Recently, the app refuses to connect to the database despite having made no changes to the code. When I try to run database().ref("ref").on("value", ...), the function does not error but instead never resolves. Additionally, querying the .info/connected ref returns false.

Query function:

import database from "@react-native-firebase/database";

database().ref(".info/connected").on("value", v => console.log("connected", v.val()));
database().ref(`/v2/teams/${teamID}`).on("value", v => console.log("team", v.val()));
```
<p>Package.json dependencies:</p>
<pre class="lang-json prettyprint-override"><code>"dependencies": {
    "@react-native-firebase/analytics": "15.3.0",
    "@react-native-firebase/app": "15.3.0",
    "@react-native-firebase/auth": "9.2.1",
    "@react-native-firebase/database": "7.5.5",
    "@react-native-firebase/functions": "15.3.0",
    "react": "16.13.1",
    "react-native": "0.63.2",
}
</code>```

I tried creating a blank test project following the instructions here, but that test project also failed to connect to my database. I also have a website which queries the same database which is perfectly fine, and there are no issues with database load or performance. I'm not receiving any errors of any kind so I'm somewhat lost as what to pursue.

Body:
I've been working with a React Native app that utilizes the Firebase Realtime database for several months now. Recently, the app refuses to connect to the database despite having made no changes to the code. When I try to run database().ref("ref").on("value", ...), the function does not error but instead never resolves. Additionally, querying the .info/connected ref returns false.

Query function:

import database from "@react-native-firebase/database";

database().ref(".info/connected").on("value", v => console.log("connected", v.val()));
database().ref(`/v2/teams/${teamID}`).on("value", v => console.log("team", v.val()));

Package.json dependencies:

"dependencies": {
    "@react-native-firebase/analytics": "15.3.0",
    "@react-native-firebase/app": "15.3.0",
    "@react-native-firebase/auth": "9.2.1",
    "@react-native-firebase/database": "7.5.5",
    "@react-native-firebase/functions": "15.3.0",
    "react": "16.13.1",
    "react-native": "0.63.2",
}

I tried creating a blank test project following the instructions here, but that test project also failed to connect to my database. I also have a website which queries the same database which is perfectly fine, and there are no issues with database load or performance. I'm not receiving any errors of any kind so I'm somewhat lost as what to pursue.


问:
Vanilla JS - hoisting a querySelected variable to Window
I've been researching and trying different solutions to this literally all day.

** EDIT: regarding duplicate post: As I wrote below, a set timeout function has been attempted and successful around the function call. Please, before you close my question, atleast ask that what you’re describing as a duplicate hasn’t already been attempted… or in this case. INCLUDED in my original post. I’m not looking for cred, I’m looking for help. **

I have a reusable function takes in 3 params:

What to wrap,

wrap in what type of element

and the id of the new wrapping element (so I can control access it later.)

Here's a codeSandbox version to help you help me!
 https://codesandbox.io/s/queryselector-to-globe-jbffk0?file=/index.html

Goal: I'd like to include a querySelector within the function that takes in the id to eliminate the extra step, to ensure the selector is defined after the item is created, and to keep a cleaner code-base. The problem is I keep fighting between a function that's surrounded by parens...

Var wrap = (function(params){...})(window); to potentially give global scope to the queryselector(object ref) I'm trying to create, and a standard es6 function I'm more familiar with... Var wrap = (params) => {...};

```<code>    import "./styles.css";

    const item = document.querySelector(".item");

    var wrap = (function (toWrap, wrapper, id) {
      wrapper = wrapper || document.createElement("div");
      wrapper.setAttribute("id", `${id}`);
      toWrap.parentNode.appendChild(wrapper);

      // Non-working auto id something to
      // window.id = document.querySelector(`${id}`);

      return wrapper.appendChild(toWrap);
    })(window);

    // How can I "store the window.id" just as if it were manually written right here in global scope?

    wrap(item, "div", "itemadded");

</code>```

Note: the window thing I read at: http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

Like I said, I can provide more working code/attempts to show I've made a ton of effort if anyone is wondering.

PS, I'll definitely mark the answer and give upvotes for help.
Thanks in advance!

If your still reading, I've tried simplifying even further, adding a timeout function to ensure that the function takes in toWrap correctly... idk what else to try... :(

Body:
I've been researching and trying different solutions to this literally all day.

** EDIT: regarding duplicate post: As I wrote below, a set timeout function has been attempted and successful around the function call. Please, before you close my question, atleast ask that what you’re describing as a duplicate hasn’t already been attempted… or in this case. INCLUDED in my original post. I’m not looking for cred, I’m looking for help. **

I have a reusable function takes in 3 params:

What to wrap,

wrap in what type of element

and the id of the new wrapping element (so I can control access it later.)

Here's a codeSandbox version to help you help me!
 https://codesandbox.io/s/queryselector-to-globe-jbffk0?file=/index.html

Goal: I'd like to include a querySelector within the function that takes in the id to eliminate the extra step, to ensure the selector is defined after the item is created, and to keep a cleaner code-base. The problem is I keep fighting between a function that's surrounded by parens...

Var wrap = (function(params){...})(window); to potentially give global scope to the queryselector(object ref) I'm trying to create, and a standard es6 function I'm more familiar with... Var wrap = (params) => {...};

    import "./styles.css";

    const item = document.querySelector(".item");

    var wrap = (function (toWrap, wrapper, id) {
      wrapper = wrapper || document.createElement("div");
      wrapper.setAttribute("id", `${id}`);
      toWrap.parentNode.appendChild(wrapper);

      // Non-working auto id something to
      // window.id = document.querySelector(`${id}`);

      return wrapper.appendChild(toWrap);
    })(window);

    // How can I "store the window.id" just as if it were manually written right here in global scope?

    wrap(item, "div", "itemadded");

Note: the window thing I read at: http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

Like I said, I can provide more working code/attempts to show I've made a ton of effort if anyone is wondering.

PS, I'll definitely mark the answer and give upvotes for help.
Thanks in advance!

If your still reading, I've tried simplifying even further, adding a timeout function to ensure that the function takes in toWrap correctly... idk what else to try... :(


问:
Fillable PDF Form with PHP using PDFtk error
I am trying to  fill out pdf files using a github project that i found on [https://github.com/mrdigitalau/PHP-PDFTK-Tutorial]

Basically there is 2 page, one named: GeneratedPDF that hold code:

```<code><?php
namespace Classes;

if(!defined('ACCESSCHECK')) {
      die('Direct access not permitted');
}

use mikehaertl\pdftk\Pdf;

class GeneratePDF {

           public function generate($data)
           {
                  try {
                        $filename = 'pdf_' . rand(2000,1200000) . '.pdf';

                        $pdf = new Pdf('./test.pdf');
                        $pdf->fillForm($data)
                        ->flatten()
                        ->saveAs( './completed/' . $filename);
                        //->send( $filename . '.pdf');

                        return $filename;
                  }
                  catch(Exception $e)
                  {
                        return $e->getMessage();
                  }
           }
}
</code>```

And another page name generate.php that holds this code:

```<code><?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
     exit;
}

define('ACCESSCHECK', TRUE);

require_once 'vendor/autoload.php';

use Classes\GeneratePDF;

$data = [
      'name_field' => $_POST['fname'] .' ' . $_POST['lname'],
      'email_field' => $_POST['email'],
      'phone_field' => $_POST['phone'],
      'enquiry_field' => $_POST['enquiry']
];

$pdf = new GeneratePdf;
$response = $pdf->generate($data);

header('Location: thanks.php?fname=' . $_POST['fname'] . '&link=' . $response);
</code>```

The problem is every time i try to fill out a pdf I get this error:

Fatal error: Uncaught Error: Class 'Classes\GeneratePDF' not found in C:\xampp\htdocs\generate.php:23 Stack trace: #0 {main} thrown in C:\xampp\htdocs\generate.php on line 23

Any idea the problem here? Thanks in advance

Body:
I am trying to  fill out pdf files using a github project that i found on [https://github.com/mrdigitalau/PHP-PDFTK-Tutorial]

Basically there is 2 page, one named: GeneratedPDF that hold code:

<?php
namespace Classes;

if(!defined('ACCESSCHECK')) {
      die('Direct access not permitted');
}

use mikehaertl\pdftk\Pdf;

class GeneratePDF {

           public function generate($data)
           {
                  try {
                        $filename = 'pdf_' . rand(2000,1200000) . '.pdf';

                        $pdf = new Pdf('./test.pdf');
                        $pdf->fillForm($data)
                        ->flatten()
                        ->saveAs( './completed/' . $filename);
                        //->send( $filename . '.pdf');

                        return $filename;
                  }
                  catch(Exception $e)
                  {
                        return $e->getMessage();
                  }
           }
}

And another page name generate.php that holds this code:

<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
     exit;
}

define('ACCESSCHECK', TRUE);

require_once 'vendor/autoload.php';

use Classes\GeneratePDF;

$data = [
      'name_field' => $_POST['fname'] .' ' . $_POST['lname'],
      'email_field' => $_POST['email'],
      'phone_field' => $_POST['phone'],
      'enquiry_field' => $_POST['enquiry']
];

$pdf = new GeneratePdf;
$response = $pdf->generate($data);

header('Location: thanks.php?fname=' . $_POST['fname'] . '&link=' . $response);

The problem is every time i try to fill out a pdf I get this error:

Fatal error: Uncaught Error: Class 'Classes\GeneratePDF' not found in C:\xampp\htdocs\generate.php:23 Stack trace: #0 {main} thrown in C:\xampp\htdocs\generate.php on line 23

Any idea the problem here? Thanks in advance


问:
Creating multiple iframes to make a curved plane with synced iframes
I'm attempting to create a curved iframe. I know it is not possible to curve an iframe, although I have been researching and found a possible solution, which is, creating multiple iframes and later on syncing them.

 I have got some of the code from this post: Three js curved (bend) CSS3DObject which served me really well, although I can't seem to curve the frames and position them correctly.

Here is the fiddle I have created:
https://jsfiddle.net/niltonsf/2cwq38tb/1/

```<code>var scene, camera, renderer, container;

init();
animate();

function init() {

  scene = new THREE.Scene();
  var  createElements= function(url, divisions, parent) {
    var w = 100.0 / divisions;
    var x = 0;

    for (var x = 0; x < 100; x += w) {
      var el = document.createElement('iframe');
      el.src = url;
      var x2 = x + w;
      el.style = "clip-path:polygon(" + x + "% 0%, " + x2 + "% 0%, " + x2 + "% 100%, " + x + "% 100%);";
      var cssObject = new THREE.CSS3DObject(el);
/*       if (x > 90){
      cssObject.rotation.y = x * 0.4
      console.log(x*-1)
              cssObject.position.z = x * -1
      } else {
        cssObject.position.z = x * 1
      }
       */
       if (x >= 95 || x <= 1) {
        /* cssObject.position.z = 0 */
       } else if (x > 60) {
        cssObject.position.z = (x * -1) * 1 + 10
       } else {
       cssObject.position.z = x * -1
       }
      parent.add(cssObject);
    }
  }
    container = new THREE.Object3D();
  createElements("https://example.com/",24,container);
    scene.add(container);
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.z = 200;
  camera.position.y = 30;
  renderer = new THREE.CSS3DRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);

  document.body.appendChild(renderer.domElement);

}

function animate() {
container.rotation.y += .005;

  requestAnimationFrame(animate);

  renderer.render(scene, camera);

}

</code>```

As you can see in the image, the red and aqua circles are referring to the ends of the plane bend, the frames from the red circle on (until the middle of all frames) should go backwards until the green circle. On the green circle on the frames should go positive back to the aqua circle, achieving something like:

Body:
I'm attempting to create a curved iframe. I know it is not possible to curve an iframe, although I have been researching and found a possible solution, which is, creating multiple iframes and later on syncing them.

 I have got some of the code from this post: Three js curved (bend) CSS3DObject which served me really well, although I can't seem to curve the frames and position them correctly.

Here is the fiddle I have created:
https://jsfiddle.net/niltonsf/2cwq38tb/1/

var scene, camera, renderer, container;

init();
animate();

function init() {

  scene = new THREE.Scene();
  var  createElements= function(url, divisions, parent) {
    var w = 100.0 / divisions;
    var x = 0;

    for (var x = 0; x < 100; x += w) {
      var el = document.createElement('iframe');
      el.src = url;
      var x2 = x + w;
      el.style = "clip-path:polygon(" + x + "% 0%, " + x2 + "% 0%, " + x2 + "% 100%, " + x + "% 100%);";
      var cssObject = new THREE.CSS3DObject(el);
/*       if (x > 90){
      cssObject.rotation.y = x * 0.4
      console.log(x*-1)
              cssObject.position.z = x * -1
      } else {
        cssObject.position.z = x * 1
      }
       */
       if (x >= 95 || x <= 1) {
        /* cssObject.position.z = 0 */
       } else if (x > 60) {
        cssObject.position.z = (x * -1) * 1 + 10
       } else {
       cssObject.position.z = x * -1
       }
      parent.add(cssObject);
    }
  }
    container = new THREE.Object3D();
  createElements("https://example.com/",24,container);
    scene.add(container);
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.z = 200;
  camera.position.y = 30;
  renderer = new THREE.CSS3DRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);

  document.body.appendChild(renderer.domElement);

}

function animate() {
container.rotation.y += .005;

  requestAnimationFrame(animate);

  renderer.render(scene, camera);

}

As you can see in the image, the red and aqua circles are referring to the ends of the plane bend, the frames from the red circle on (until the middle of all frames) should go backwards until the green circle. On the green circle on the frames should go positive back to the aqua circle, achieving something like:


问:
What am I doing wrong with Out-File?
I cannot get this command to output to text file. I am trying to use the out-file command.

```<code>#Trim up the URL
$data = get-content C:\Dell\Temp\urlhausCopyDL.txt
$data | ForEach-Object {
    $items = $_.split(":")
    write-host  (-join('http:',$items[1])) | Out-File "C:\Dell\Temp\Formulated.txt" -Append
}
</code>```

It creates the file but it is blank.

It splits the URL and removes whatever is after the second : as we don't need it.

It outputs to Console great, but I just cant get it to write to a file!! :(

A snippet of urlhauscopyDL is here for you:
http://115.55.196.162:57955/bin.sh
http://182.240.54.209:60488/bin.sh
http://176.231.66.63:49310/.i
```

Thankyou For your help team  :)

Title: What am I doing wrong with Out-File?

Body:
I cannot get this command to output to text file. I am trying to use the out-file command.

#Trim up the URL
$data = get-content C:\Dell\Temp\urlhausCopyDL.txt
$data | ForEach-Object {
    $items = $_.split(":")
    write-host  (-join('http:',$items[1])) | Out-File "C:\Dell\Temp\Formulated.txt" -Append
}

It creates the file but it is blank.

It splits the URL and removes whatever is after the second : as we don't need it.

It outputs to Console great, but I just cant get it to write to a file!! :(

A snippet of urlhauscopyDL is here for you:
http://115.55.196.162:57955/bin.sh
http://182.240.54.209:60488/bin.sh
http://176.231.66.63:49310/.i

Thankyou For your help team  :)


问:
WPF MVVM Binding to a DataTable within a DataTable
I have created a DataTable with an unknown number of columns.
There is only one Row within the DataTable and it contains another DataTable for each cell.

```<code>CoordsDataTable = new();

    foreach (var coordset in DrillDesigns.Coordinates)
    {
        CoordsDataTable.Columns.Add(coordset!.CoordinateType!.CoordinateType, typeof(DataTable));
    }

    CoordsDataTable.Rows.Add();

    foreach (var coordset in DrillDesigns.Coordinates)
    {
        CoordsDataSet = new();
        CoordsDataSet.Columns.Add("X");
        CoordsDataSet.Columns.Add("Y");
        CoordsDataSet.Columns.Add("Z");
        CoordsDataSet.Rows.Add(coordset.X, coordset.Y, coordset.Z);
        CoordsDataTable.Rows[0][coordset!.CoordinateType!.CoordinateType] = CoordsDataSet;
    }
</code>```

How do I bind to this in WPF MVVM?
I can get the first table with autogenerated columns but I cannot bind to the second DataTable.

```<code><DataGrid
        x:Name="coordsDG"
        ItemsSource="{Binding CoordsDataTable }"
        DockPanel.Dock="Top">
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <DataGrid
                    ItemsSource="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"

                    AutoGenerateColumns="True"
                    CanUserAddRows="False">
                </DataGrid>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>
</code>```

Body:
I have created a DataTable with an unknown number of columns.
There is only one Row within the DataTable and it contains another DataTable for each cell.

CoordsDataTable = new();

    foreach (var coordset in DrillDesigns.Coordinates)
    {
        CoordsDataTable.Columns.Add(coordset!.CoordinateType!.CoordinateType, typeof(DataTable));
    }

    CoordsDataTable.Rows.Add();

    foreach (var coordset in DrillDesigns.Coordinates)
    {
        CoordsDataSet = new();
        CoordsDataSet.Columns.Add("X");
        CoordsDataSet.Columns.Add("Y");
        CoordsDataSet.Columns.Add("Z");
        CoordsDataSet.Rows.Add(coordset.X, coordset.Y, coordset.Z);
        CoordsDataTable.Rows[0][coordset!.CoordinateType!.CoordinateType] = CoordsDataSet;
    }

How do I bind to this in WPF MVVM?
I can get the first table with autogenerated columns but I cannot bind to the second DataTable.

<DataGrid
        x:Name="coordsDG"
        ItemsSource="{Binding CoordsDataTable }"
        DockPanel.Dock="Top">
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <DataGrid
                    ItemsSource="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"

                    AutoGenerateColumns="True"
                    CanUserAddRows="False">
                </DataGrid>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>


问:
How to apply `DisparityWLSFilter` to live stereo camera data using precomputed disparity map in OpenCV-Python
I am trying to post-filter my stereo cameras using cv2.ximgproc.createDisparityWLSFilter after block matching and rectification.

I have been following this tutorial and have implemented the suggestions in this answer and this answer in my code (snippet, below). However, I already have an instance of cv2.StereoBM_create, performed rectification, and computed the disparity.

```<code>    stereo = cv2.StereoBM_create()
    wls_filter = cv2.ximgproc.createDisparityWLSFilter(stereo)

    disparity = stereo.compute(Left_rect, Right_rect)
    disparity = disparity.astype(np.float32)

    # Scaling down the disparity values and normalizing them
    disparity = (disparity / 16.0 - minDisparity) / numDisparities

    # Normalize and apply a color map
    disparityImg = cv2.normalize(src=disparity, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX,
                                 dtype=cv2.CV_8UC1)
    disparityImg = cv2.applyColorMap(disparityImg, cv2.COLORMAP_JET)

    # Applying WLS filter to remove noise
    left_image = Left_rect
    right_image = Right_rect
    left_matcher = stereo
    right_matcher = cv2.ximgproc.createRightMatcher(left_matcher)
    left_disp = left_matcher.compute(left_image, right_image)
    right_disp = right_matcher.compute(right_image, left_image)

    # Now create DisparityWLSFilter
    wls_filter = cv2.ximgproc.createDisparityWLSFilter(left_matcher)
    filtered_disp = wls_filter.filter(left_disp, left_image, disparity_map_right=right_disp)

    # Displaying the disparity map
    cv2.imshow("disparity map", disparityImg)
    cv2.imshow("filtered disparity map", filtered_disp)
</code>```

The parameters for the stereoBM and wls filter are set using a GUI (see image below).

The above tutorial/code is written for two static left and right images. However, I need to apply it stereo webcams, as applied in this project.

When I run the code above, I get a blank disparity map image. Without the WLSFilter code the disparity map image shows is displayed.

I have tried feeding it my disparity map with left_matcher = disparity, but that obviously doesn't work as I need the left/right disparities separate.

I'm sure this is an easy fix/silly mistake I'm making, I just can't see it! Can anyone spot where I'm going wrong, please?

Body:
I am trying to post-filter my stereo cameras using cv2.ximgproc.createDisparityWLSFilter after block matching and rectification.

I have been following this tutorial and have implemented the suggestions in this answer and this answer in my code (snippet, below). However, I already have an instance of cv2.StereoBM_create, performed rectification, and computed the disparity.

    stereo = cv2.StereoBM_create()
    wls_filter = cv2.ximgproc.createDisparityWLSFilter(stereo)

    disparity = stereo.compute(Left_rect, Right_rect)
    disparity = disparity.astype(np.float32)

    # Scaling down the disparity values and normalizing them
    disparity = (disparity / 16.0 - minDisparity) / numDisparities

    # Normalize and apply a color map
    disparityImg = cv2.normalize(src=disparity, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX,
                                 dtype=cv2.CV_8UC1)
    disparityImg = cv2.applyColorMap(disparityImg, cv2.COLORMAP_JET)

    # Applying WLS filter to remove noise
    left_image = Left_rect
    right_image = Right_rect
    left_matcher = stereo
    right_matcher = cv2.ximgproc.createRightMatcher(left_matcher)
    left_disp = left_matcher.compute(left_image, right_image)
    right_disp = right_matcher.compute(right_image, left_image)

    # Now create DisparityWLSFilter
    wls_filter = cv2.ximgproc.createDisparityWLSFilter(left_matcher)
    filtered_disp = wls_filter.filter(left_disp, left_image, disparity_map_right=right_disp)

    # Displaying the disparity map
    cv2.imshow("disparity map", disparityImg)
    cv2.imshow("filtered disparity map", filtered_disp)

The parameters for the stereoBM and wls filter are set using a GUI (see image below).

The above tutorial/code is written for two static left and right images. However, I need to apply it stereo webcams, as applied in this project.

When I run the code above, I get a blank disparity map image. Without the WLSFilter code the disparity map image shows is displayed.

I have tried feeding it my disparity map with left_matcher = disparity, but that obviously doesn't work as I need the left/right disparities separate.

I'm sure this is an easy fix/silly mistake I'm making, I just can't see it! Can anyone spot where I'm going wrong, please?


问:
Google Collab- Fbprophet installation error
Hello stack overflow community,

I'm trying to import Prophet from fbProphet and I got an error message so I tried to install fbProphet and received another error message.
Can someone help me please?

```<code> Building wheel for fbprophet (setup.py) ... error
  ERROR: Failed building wheel for fbprophet
  Running setup.py clean for fbprophet
Failed to build fbprophet
Installing collected packages: fbprophet
    Running setup.py install for fbprophet ... error
ERROR: Command errored out with exit status 1: /usr/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-6nhgip9q/fbprophet_f5a0de9add594fa0a47241ba6cb37d86/setup.py'"'"'; __file__='"'"'/tmp/pip-install-6nhgip9q/fbprophet_f5a0de9add594fa0a47241ba6cb37d86/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-gqbipw4r/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.8/fbprophet Check the logs for full command output.
</code>```

!pip install fbprophet

Body:
Hello stack overflow community,

I'm trying to import Prophet from fbProphet and I got an error message so I tried to install fbProphet and received another error message.
Can someone help me please?

 Building wheel for fbprophet (setup.py) ... error
  ERROR: Failed building wheel for fbprophet
  Running setup.py clean for fbprophet
Failed to build fbprophet
Installing collected packages: fbprophet
    Running setup.py install for fbprophet ... error
ERROR: Command errored out with exit status 1: /usr/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-6nhgip9q/fbprophet_f5a0de9add594fa0a47241ba6cb37d86/setup.py'"'"'; __file__='"'"'/tmp/pip-install-6nhgip9q/fbprophet_f5a0de9add594fa0a47241ba6cb37d86/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-gqbipw4r/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.8/fbprophet Check the logs for full command output.

!pip install fbprophet


问:
how to change the mouse commands to mobile commands
I have been struggling to understand how to implement the mobile input system instead of mouse or example keyboard commands on my code with a simple touch
lets suppose I have to throw an object a script that works on Pc is this :

```<code>using UnityEngine;
using System.Collections;

public class ThrowObject : MonoBehaviour
{
    public Transform player;
    public Transform playerCam;
    public float throwForce = 10;
    bool hasPlayer = false;
    bool beingCarried = false;
    public AudioClip[] soundToPlay;
    private AudioSource audio;
    public int dmg;
    private bool touched = false;

    void Start()
    {
        audio = GetComponent<AudioSource>();
    }

    void Update()
    {
        float dist = Vector3.Distance(gameObject.transform.position, player.position);
        if (dist <= 2.5f)
        {
            hasPlayer = true;
        }
        else
        {
            hasPlayer = false;
        }
        if (hasPlayer && Input.GetButtonDown("Use"))
        {
            GetComponent<Rigidbody>().isKinematic = true;
            transform.parent = playerCam;
            beingCarried = true;
        }
        if (beingCarried)
        {
            if (touched)
            {
                GetComponent<Rigidbody>().isKinematic = false;
                transform.parent = null;
                beingCarried = false;
                touched = false;
            }
            if (Input.GetMouseButtonDown(0))
                {
                    GetComponent<Rigidbody>().isKinematic = false;
                    transform.parent = null;
                    beingCarried = false;
                    GetComponent<Rigidbody>().AddForce(playerCam.forward * throwForce);
                RandomAudio();
                }
                else if (Input.GetMouseButtonDown(1))
                {
                GetComponent<Rigidbody>().isKinematic = false;
                    transform.parent = null;
                beingCarried = false;
                }
            }
        }
    void RandomAudio()
    {
        if (audio.isPlaying){
            return;
                }
        audio.clip = soundToPlay[Random.Range(0, soundToPlay.Length)];
        audio.Play();

    }
   void OnTriggerEnter()
    {
        if (beingCarried)
        {
            touched = true;
        }
    }
    }
</code>```

How can I change this so I will use it only on mobile - with not the mouse..
I have been searching in internet /youtube for many different things but hard to find on about it.
Thanks in advance.
I was searching in internet and youtube videos example how to create mobile pick up or throw system just by touch but nothing I have been found nor videos for those.I tryed a lot of time to change the codes but I didn't managed to.

Body:
I have been struggling to understand how to implement the mobile input system instead of mouse or example keyboard commands on my code with a simple touch
lets suppose I have to throw an object a script that works on Pc is this :

using UnityEngine;
using System.Collections;

public class ThrowObject : MonoBehaviour
{
    public Transform player;
    public Transform playerCam;
    public float throwForce = 10;
    bool hasPlayer = false;
    bool beingCarried = false;
    public AudioClip[] soundToPlay;
    private AudioSource audio;
    public int dmg;
    private bool touched = false;

    void Start()
    {
        audio = GetComponent<AudioSource>();
    }

    void Update()
    {
        float dist = Vector3.Distance(gameObject.transform.position, player.position);
        if (dist <= 2.5f)
        {
            hasPlayer = true;
        }
        else
        {
            hasPlayer = false;
        }
        if (hasPlayer && Input.GetButtonDown("Use"))
        {
            GetComponent<Rigidbody>().isKinematic = true;
            transform.parent = playerCam;
            beingCarried = true;
        }
        if (beingCarried)
        {
            if (touched)
            {
                GetComponent<Rigidbody>().isKinematic = false;
                transform.parent = null;
                beingCarried = false;
                touched = false;
            }
            if (Input.GetMouseButtonDown(0))
                {
                    GetComponent<Rigidbody>().isKinematic = false;
                    transform.parent = null;
                    beingCarried = false;
                    GetComponent<Rigidbody>().AddForce(playerCam.forward * throwForce);
                RandomAudio();
                }
                else if (Input.GetMouseButtonDown(1))
                {
                GetComponent<Rigidbody>().isKinematic = false;
                    transform.parent = null;
                beingCarried = false;
                }
            }
        }
    void RandomAudio()
    {
        if (audio.isPlaying){
            return;
                }
        audio.clip = soundToPlay[Random.Range(0, soundToPlay.Length)];
        audio.Play();

    }
   void OnTriggerEnter()
    {
        if (beingCarried)
        {
            touched = true;
        }
    }
    }

How can I change this so I will use it only on mobile - with not the mouse..
I have been searching in internet /youtube for many different things but hard to find on about it.
Thanks in advance.
I was searching in internet and youtube videos example how to create mobile pick up or throw system just by touch but nothing I have been found nor videos for those.I tryed a lot of time to change the codes but I didn't managed to.


问:
how to access AWS.Response body from client SDK request?
I can't seem to work out how to access to the data or error object when making an AWS client request

I do NOT want to use the async promise feature. This is purely a question of how to access the data and error property of the AWS.Response object.

Here's the code:

```<code>const mediatailor = new AWS.MediaTailor();
</code>```
```<code>function describeSourceLocation(SourceLocationName) {
    let params = {
        SourceLocationName: SourceLocationName
    };
    return mediatailor.describeSourceLocation(params).response
}
</code>```
```<code>console.log(describeSourceLocation('test'))
</code>```

The output of the function always has error and data properties null. How can I read the response data of the request?

Body:
I can't seem to work out how to access to the data or error object when making an AWS client request

I do NOT want to use the async promise feature. This is purely a question of how to access the data and error property of the AWS.Response object.

Here's the code:

const mediatailor = new AWS.MediaTailor();

function describeSourceLocation(SourceLocationName) {
    let params = {
        SourceLocationName: SourceLocationName
    };
    return mediatailor.describeSourceLocation(params).response
}

console.log(describeSourceLocation('test'))

The output of the function always has error and data properties null. How can I read the response data of the request?


问:
Have user select which column to paste to instead of defined offset
This code searches for a column with "CPN" moves down two cells, copies the data, searches the selected data in another sheet, offsets to a defined sell, copies that data and returns to the original sheet.

My issue is, the row I am pasting the data into will sometimes change.. is there a way to have the user select the row that we are pasting into?

At the bottom of the code, you can see where I have offset 6 columns to the right to paste. I want the user to be able to select "Z" or something like that for example.

'Find CPN

```<code>Cells.Find(What:="CPN").Offset(2, 0).Select
</code>```

'Copy/search

```<code>Dim str1 As String
Dim Cntr As Integer
Cntr = 0
Do While Cntr <= 650

  Cntr = Cntr + 1
  str1 = ActiveCell.Value
  Selection.Copy

  Worksheets("Export").Activate
  ActiveCell.Select
  Cells.Find(What:=str1, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate
  Cells.FindNext(After:=ActiveCell).Activate
  ActiveCell.Offset(0, 15).Range("A1").Select
  Selection.Copy

  Worksheets("Quote").Activate

  ' Now find Part number and paste into price column
  ActiveCell.Offset(0, 6).Select
  Selection.PasteSpecial Paste:=xlPasteValues
Loop
</code>```

Body:
This code searches for a column with "CPN" moves down two cells, copies the data, searches the selected data in another sheet, offsets to a defined sell, copies that data and returns to the original sheet.

My issue is, the row I am pasting the data into will sometimes change.. is there a way to have the user select the row that we are pasting into?

At the bottom of the code, you can see where I have offset 6 columns to the right to paste. I want the user to be able to select "Z" or something like that for example.

'Find CPN

Cells.Find(What:="CPN").Offset(2, 0).Select

'Copy/search

Dim str1 As String
Dim Cntr As Integer
Cntr = 0
Do While Cntr <= 650

  Cntr = Cntr + 1
  str1 = ActiveCell.Value
  Selection.Copy

  Worksheets("Export").Activate
  ActiveCell.Select
  Cells.Find(What:=str1, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate
  Cells.FindNext(After:=ActiveCell).Activate
  ActiveCell.Offset(0, 15).Range("A1").Select
  Selection.Copy

  Worksheets("Quote").Activate

  ' Now find Part number and paste into price column
  ActiveCell.Offset(0, 6).Select
  Selection.PasteSpecial Paste:=xlPasteValues
Loop


问:
Morton Code sort gives the wrong coordinates
For the past few days I've been trying to procedurally piece together a bunch of small tiles that are sorted using Morton code. I got most of the script to work with a 4x4 test, but for whatever reason the image is slightly offset on the Y axis the further right it goes. I'm not sure how to fix this, I'm not really an expert on bitwise operators but maybe it has something to do with that?

Here's the code:

var fileDirectory = Folder.selectDialog("Select a folder");
var files = fileDirectory.getFiles("*.png");
var activeDoc = app.activeDocument;
var scale = 4;

var MASKS = [0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF];
var SHIFTS = [1, 2, 4, 8];

for (var fileIdx = 0; fileIdx < files.length; fileIdx++)
{
   app.load(files[fileIdx]);
   backFile = app.activeDocument;
   backFile.selection.selectAll();
   backFile.selection.copy();
   backFile.close(SaveOptions.DONOTSAVECHANGES);
   activeDoc.paste();
   activeDoc.activeLayer.name = fileIdx;

   var x = fileIdx % scale;
   var y = fileIdx / scale;

    x = (x | (x << SHIFTS[3])) & MASKS[3];
    x = (x | (x << SHIFTS[2])) & MASKS[2];
    x = (x | (x << SHIFTS[1])) & MASKS[1];
    x = (x | (x << SHIFTS[0])) & MASKS[0];

    y = (y | (y << SHIFTS[3])) & MASKS[3];
    y = (y | (y << SHIFTS[2])) & MASKS[2];
    y = (y | (y << SHIFTS[1])) & MASKS[1];
    y = (y | (y << SHIFTS[0])) & MASKS[0];

    var id = x | (y << 1);

    x = (id % scale) * 256;
    y = (id / scale) * 256;

    var LB = activeDoc.activeLayer.bounds;
    activeDoc.activeLayer.translate(-LB[0].as('px') + new UnitValue(x, 'px'), -LB[1].as('px') + new UnitValue(y, 'px'));
}
```


问:
Scanning for patterns in files modified under git
How do you scan for patterns on changed lines within a git repo?

I'm trying to find the pattern "<<<<<<<" in all files locally modified.

To do this I thought I'd output git's diff, which should show all changed lines, and then just do a grep, like:

```<code>git diff --diff-filter=d origin/master | grep -B 5 -A 5 '<<<<<<<'
</code>```

However, instead of outputting a diff, this launches my meld (on Ubuntu), my local git difftool. How do I stop it from launching meld and make it simply output a diff?

Body:
How do you scan for patterns on changed lines within a git repo?

I'm trying to find the pattern "<<<<<<<" in all files locally modified.

To do this I thought I'd output git's diff, which should show all changed lines, and then just do a grep, like:

git diff --diff-filter=d origin/master | grep -B 5 -A 5 '<<<<<<<'

However, instead of outputting a diff, this launches my meld (on Ubuntu), my local git difftool. How do I stop it from launching meld and make it simply output a diff?


问:
How to hide markdown punctuation from the output of PrismJS's markdown parser?
I am trying to implement PrismJS on my blog to syntax highlight code and it works like a charm. PrismJS also has the ability to parse markdown. However, the output of parsed Markdown is showing the punctuations (such as ##, *), which I don't want.

For example, the following code

```<code>*Italic*
**Bold on
multiple lines**
</code>```

looks like this in the output

*Italic*

**Bold on

multiple lines**

instead of looking like this

Italic

Bold on

multiple lines

Is this how it's supposed to be? The examples page on prismjs.com (you'll have to select Markdown from the 'Per language examples' section to see examples using Markdown) confirms the behavior that I am seeing (see attached image).

Is there a way I can get it to parse the markdown without showing the punctuations?

Body:
I am trying to implement PrismJS on my blog to syntax highlight code and it works like a charm. PrismJS also has the ability to parse markdown. However, the output of parsed Markdown is showing the punctuations (such as ##, *), which I don't want.

For example, the following code

*Italic*
**Bold on
multiple lines**

looks like this in the output

*Italic*

**Bold on

multiple lines**

instead of looking like this

Italic

Bold on

multiple lines

Is this how it's supposed to be? The examples page on prismjs.com (you'll have to select Markdown from the 'Per language examples' section to see examples using Markdown) confirms the behavior that I am seeing (see attached image).

Is there a way I can get it to parse the markdown without showing the punctuations?


问:
Why multiple strings are getting printed when I only print one in mips?
My code is working logically. However, multiple strings are printing even though I am calling only one.

I think that, inside my .data section, the order in which I allocate space for my array is causing this. Different combinations of allocations give a variety of outputs. For example:

```<code>.data
array:  .space 40
arraySize: .word 10
askUser:   .ascii "Please enter numbers: "
endl: .ascii "\n"
averageMsg: .ascii "The average is: "
</code>```

Outputs:

```<code>The average is: Please enter numbers:
                 # endl here
x # x is the average here
</code>```

However, when it is:

```<code>.data
arraySize: .word 10 # arraySize allocated before array
array:  .space 40
averageMsg: .ascii "The average is: "
askUser:   .ascii "Please enter numbers: "
endl: .ascii "\n"
</code>```

Output is:

```<code>The average is: Please enter numbers :
x      # no endl this time
</code>```

My code prompts, and calculates the average as it should. But I can't understand why "Please enter numbers: " is getting printed when I only print averageMsg. What might be the cause and solution for this?
(this is an assignment question, therefore I can't share my complete code.
I have to ask the user to enter 10 numbers, store them into array, then calculate their average.)

Body:
My code is working logically. However, multiple strings are printing even though I am calling only one.

I think that, inside my .data section, the order in which I allocate space for my array is causing this. Different combinations of allocations give a variety of outputs. For example:

.data
array:  .space 40
arraySize: .word 10
askUser:   .ascii "Please enter numbers: "
endl: .ascii "\n"
averageMsg: .ascii "The average is: "

Outputs:

The average is: Please enter numbers:
                 # endl here
x # x is the average here

However, when it is:

.data
arraySize: .word 10 # arraySize allocated before array
array:  .space 40
averageMsg: .ascii "The average is: "
askUser:   .ascii "Please enter numbers: "
endl: .ascii "\n"

Output is:

The average is: Please enter numbers :
x      # no endl this time

My code prompts, and calculates the average as it should. But I can't understand why "Please enter numbers: " is getting printed when I only print averageMsg. What might be the cause and solution for this?
(this is an assignment question, therefore I can't share my complete code.
I have to ask the user to enter 10 numbers, store them into array, then calculate their average.)


问:
How to implement a scrollspy in react with 2 columns connected to each other
I have column #1 thats on the left side of the page that is housing my Names and i have a second column that is housing all of its descriptions under that name. The left column is not scrollable, but as you scroll down the middle column, i want the Name on the left side of the column to be highlighted once the majority of the descriptions of that particular name are visible in the second column.

I tried to use react-use-scrollspy but the problem im seeing is that the Name only changes in its highlighting once i scroll OUTSIDE of the middle column, and does not update the highlighting as i scroll WITHIN the second column. I feel like I am missing something regarding how React rerenders the page to see where the reference window location is