问:
Exporting from Access Database (.mdb) via Python to Pandas Dataframe
I'm looking for a method to programmatically access an access database file (.mdb) using python in an Ubuntu environment (hosted on a Windows 10 machine) to export tables to pandas dataframes.
I've attempted the solutions previously posted, such as using pandas access, pyodbc, or mdbtools, however all have failed due to errors relating to missing tables or files in the packages.

Any feedback or insights would be much appreciated!

pyodc failure:

```<code>OperationalError                          Traceback (most recent call last)
Cell In[6], line 2
      1 pypyodbc.lowercase = False
----> 2 conn = pypyodbc.connect(
      3     r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
      4     r"/home/kevin/scratch/HDINEWTON.mdb;")
      5 cur = conn.cursor()
      6 # cur.execute("SELECT CreatureID, Name_EN, Name_JP FROM Creatures");
      7 # while True:
      8 #     row = cur.fetchone()
   (...)
     11 #     print(u"Creature with ID {0} is {1} ({2})".format(
     12 #         row.get("CreatureID"), row.get("Name_EN"), row.get("Name_JP")))

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pypyodbc.py:2454, in Connection.__init__(self, connectString, autocommit, ansi, timeout, unicode_results, readonly, **kargs)
   2450 if self.connection_timeout != 0:
   2451     self.set_connection_timeout(connection_timeout)
-> 2454 self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly)

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pypyodbc.py:2507, in Connection.connect(self, connectString, autocommit, ansi, timeout, unicode_results, readonly)
   2505 else:
   2506     ret = odbc_func(self.dbc_h, 0, c_connectString, len(self.connectString), None, 0, None, SQL_DRIVER_NOPROMPT)
-> 2507 check_success(self, ret)
   2510 # Set the connection's attribute of "autocommit"
   2511 #
   2512 self.autocommit = autocommit

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pypyodbc.py:1009, in check_success(ODBC_obj, ret)
   1007     ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
   1008 elif isinstance(ODBC_obj, Connection):
-> 1009     ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi)
   1010 else:
   1011     ctrl_err(SQL_HANDLE_ENV, ODBC_obj, ret, False)

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pypyodbc.py:983, in ctrl_err(ht, h, val_ret, ansi)
    981     raise NotSupportedError(state,err_text)
    982 elif state in (raw_s('HYT00'),raw_s('HYT01'),raw_s('01000')):
--> 983     raise OperationalError(state,err_text)
    984 elif state[:2] in (raw_s('IM'),raw_s('HY')):
    985     raise Error(state,err_text)

OperationalError: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'Microsoft Access Driver (*.mdb, *.accdb)' : file not found")
</code>```

pandas access failure:

```<code>---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[4], line 2
      1 path_to_mdb_database = '/home/kevin/scratch/HDINEWTON.mdb'
----> 2 mdb.list_tables(path_to_mdb_database)

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pandas_access/__init__.py:25, in list_tables(rdb_file, encoding)
     17 def list_tables(rdb_file, encoding="latin-1"):
     18     """
     19     :param rdb_file: The MS Access database file.
     20     :param encoding: The content encoding of the output. I assume `latin-1`
   (...)
     23     :return: A list of the tables in a given database.
     24     """
---> 25     tables = subprocess.check_output(['mdb-tables', rdb_file]).decode(encoding)
     26     return tables.strip().split(" ")

File ~/miniconda3/envs/mdb_access/lib/python3.11/subprocess.py:465, in check_output(timeout, *popenargs, **kwargs)
    462         empty = b''
    463     kwargs['input'] = empty
--> 465 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
    466            **kwargs).stdout

File ~/miniconda3/envs/mdb_access/lib/python3.11/subprocess.py:546, in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    543     kwargs['stdout'] = PIPE
    544     kwargs['stderr'] = PIPE
--> 546 with Popen(*popenargs, **kwargs) as process:
    547     try:
    548         stdout, stderr = process.communicate(input, timeout=timeout)

File ~/miniconda3/envs/mdb_access/lib/python3.11/subprocess.py:1022, in Popen.__init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask, pipesize, process_group)
   1018         if self.text_mode:
   1019             self.stderr = io.TextIOWrapper(self.stderr,
   1020                     encoding=encoding, errors=errors)
-> 1022     self._execute_child(args, executable, preexec_fn, close_fds,
   1023                         pass_fds, cwd, env,
   1024                         startupinfo, creationflags, shell,
   1025                         p2cread, p2cwrite,
   1026                         c2pread, c2pwrite,
   1027                         errread, errwrite,
   1028                         restore_signals,
   1029                         gid, gids, uid, umask,
   1030                         start_new_session, process_group)
   1031 except:
   1032     # Cleanup if the child failed starting.
   1033     for f in filter(None, (self.stdin, self.stdout, self.stderr)):

File ~/miniconda3/envs/mdb_access/lib/python3.11/subprocess.py:1899, in Popen._execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, gid, gids, uid, umask, start_new_session, process_group)
   1897     if errno_num != 0:
   1898         err_msg = os.strerror(errno_num)
-> 1899     raise child_exception_type(errno_num, err_msg, err_filename)
   1900 raise child_exception_type(err_msg)

FileNotFoundError: [Errno 2] No such file or directory: 'mdb-tables'
</code>```

mdb tools failure:

```<code>ModuleNotFoundError                       Traceback (most recent call last)
Cell In[2], line 5
      3 import os
      4 import pandas_access as mdb
----> 5 import mdbtools
      7 print('Imports Successful')

File ~/miniconda3/envs/mdb/lib/python3.11/site-packages/mdbtools/__init__.py:1
----> 1 from .MDBcli import *
      2 from .MDBnetrc import *
      3 from .MDBtool import *

File ~/miniconda3/envs/mdb/lib/python3.11/site-packages/mdbtools/MDBcli.py:21
     19 import sys
     20 import argparse
---> 21 from MDButils import *
     23 # Stop Python from complaining when I/O pipes are closed
     24 from signal import signal, SIGPIPE, SIG_DFL

ModuleNotFoundError: No module named 'MDButils'
</code>```
```<code></code>```

Body:
I'm looking for a method to programmatically access an access database file (.mdb) using python in an Ubuntu environment (hosted on a Windows 10 machine) to export tables to pandas dataframes.
I've attempted the solutions previously posted, such as using pandas access, pyodbc, or mdbtools, however all have failed due to errors relating to missing tables or files in the packages.

Any feedback or insights would be much appreciated!

pyodc failure:

OperationalError                          Traceback (most recent call last)
Cell In[6], line 2
      1 pypyodbc.lowercase = False
----> 2 conn = pypyodbc.connect(
      3     r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
      4     r"/home/kevin/scratch/HDINEWTON.mdb;")
      5 cur = conn.cursor()
      6 # cur.execute("SELECT CreatureID, Name_EN, Name_JP FROM Creatures");
      7 # while True:
      8 #     row = cur.fetchone()
   (...)
     11 #     print(u"Creature with ID {0} is {1} ({2})".format(
     12 #         row.get("CreatureID"), row.get("Name_EN"), row.get("Name_JP")))

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pypyodbc.py:2454, in Connection.__init__(self, connectString, autocommit, ansi, timeout, unicode_results, readonly, **kargs)
   2450 if self.connection_timeout != 0:
   2451     self.set_connection_timeout(connection_timeout)
-> 2454 self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly)

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pypyodbc.py:2507, in Connection.connect(self, connectString, autocommit, ansi, timeout, unicode_results, readonly)
   2505 else:
   2506     ret = odbc_func(self.dbc_h, 0, c_connectString, len(self.connectString), None, 0, None, SQL_DRIVER_NOPROMPT)
-> 2507 check_success(self, ret)
   2510 # Set the connection's attribute of "autocommit"
   2511 #
   2512 self.autocommit = autocommit

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pypyodbc.py:1009, in check_success(ODBC_obj, ret)
   1007     ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
   1008 elif isinstance(ODBC_obj, Connection):
-> 1009     ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi)
   1010 else:
   1011     ctrl_err(SQL_HANDLE_ENV, ODBC_obj, ret, False)

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pypyodbc.py:983, in ctrl_err(ht, h, val_ret, ansi)
    981     raise NotSupportedError(state,err_text)
    982 elif state in (raw_s('HYT00'),raw_s('HYT01'),raw_s('01000')):
--> 983     raise OperationalError(state,err_text)
    984 elif state[:2] in (raw_s('IM'),raw_s('HY')):
    985     raise Error(state,err_text)

OperationalError: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'Microsoft Access Driver (*.mdb, *.accdb)' : file not found")

pandas access failure:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[4], line 2
      1 path_to_mdb_database = '/home/kevin/scratch/HDINEWTON.mdb'
----> 2 mdb.list_tables(path_to_mdb_database)

File ~/miniconda3/envs/mdb_access/lib/python3.11/site-packages/pandas_access/__init__.py:25, in list_tables(rdb_file, encoding)
     17 def list_tables(rdb_file, encoding="latin-1"):
     18     """
     19     :param rdb_file: The MS Access database file.
     20     :param encoding: The content encoding of the output. I assume `latin-1`
   (...)
     23     :return: A list of the tables in a given database.
     24     """
---> 25     tables = subprocess.check_output(['mdb-tables', rdb_file]).decode(encoding)
     26     return tables.strip().split(" ")

File ~/miniconda3/envs/mdb_access/lib/python3.11/subprocess.py:465, in check_output(timeout, *popenargs, **kwargs)
    462         empty = b''
    463     kwargs['input'] = empty
--> 465 return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
    466            **kwargs).stdout

File ~/miniconda3/envs/mdb_access/lib/python3.11/subprocess.py:546, in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    543     kwargs['stdout'] = PIPE
    544     kwargs['stderr'] = PIPE
--> 546 with Popen(*popenargs, **kwargs) as process:
    547     try:
    548         stdout, stderr = process.communicate(input, timeout=timeout)

File ~/miniconda3/envs/mdb_access/lib/python3.11/subprocess.py:1022, in Popen.__init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask, pipesize, process_group)
   1018         if self.text_mode:
   1019             self.stderr = io.TextIOWrapper(self.stderr,
   1020                     encoding=encoding, errors=errors)
-> 1022     self._execute_child(args, executable, preexec_fn, close_fds,
   1023                         pass_fds, cwd, env,
   1024                         startupinfo, creationflags, shell,
   1025                         p2cread, p2cwrite,
   1026                         c2pread, c2pwrite,
   1027                         errread, errwrite,
   1028                         restore_signals,
   1029                         gid, gids, uid, umask,
   1030                         start_new_session, process_group)
   1031 except:
   1032     # Cleanup if the child failed starting.
   1033     for f in filter(None, (self.stdin, self.stdout, self.stderr)):

File ~/miniconda3/envs/mdb_access/lib/python3.11/subprocess.py:1899, in Popen._execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, gid, gids, uid, umask, start_new_session, process_group)
   1897     if errno_num != 0:
   1898         err_msg = os.strerror(errno_num)
-> 1899     raise child_exception_type(errno_num, err_msg, err_filename)
   1900 raise child_exception_type(err_msg)

FileNotFoundError: [Errno 2] No such file or directory: 'mdb-tables'

mdb tools failure:

ModuleNotFoundError                       Traceback (most recent call last)
Cell In[2], line 5
      3 import os
      4 import pandas_access as mdb
----> 5 import mdbtools
      7 print('Imports Successful')

File ~/miniconda3/envs/mdb/lib/python3.11/site-packages/mdbtools/__init__.py:1
----> 1 from .MDBcli import *
      2 from .MDBnetrc import *
      3 from .MDBtool import *

File ~/miniconda3/envs/mdb/lib/python3.11/site-packages/mdbtools/MDBcli.py:21
     19 import sys
     20 import argparse
---> 21 from MDButils import *
     23 # Stop Python from complaining when I/O pipes are closed
     24 from signal import signal, SIGPIPE, SIG_DFL

ModuleNotFoundError: No module named 'MDButils'


来源: stackexchange

问:
TypeError: float() argument must be a string or a number, not 'Timedelta'
I have a timesheet.csv that I am trying to plot as a gantt chart.

Not quite sure what the issue is as my understanding is that the start_num is where the hbar begins and the end_num is where the hbar is supposed to end.

```<code>import pandas as pd
import matplotlib.pyplot as plt

f = 'timesheet_example.csv'
df = pd.read_csv(f)

df['total_hours'] = pd.to_datetime(df['total_hours'], format='%H')
df['start_time'] = pd.to_datetime(df['start_time'])
df['end_time'] = pd.to_datetime(df['end_time'])

# period start date
period_start = df.start_time.min()

# number of days from period_start to start of tasks
df['start_num'] = (df.start_time - period_start)

# number of days from period_start to end of tasks
df['end_num'] = (df.end_time - period_start)

# days between start and end of each taks
df['num_start_to_end'] = (df.end_num - df.start_num)

fig, ax = plt.subplots(1, figsize=(16,6))
ax.barh(df.client_name, df.num_start_to_end, left=df.start_num)
plt.show()
</code>```

Ideally, the gantt plot would be an approximate work day (9-5) with the intentions of making it either 15min or 1hr block ticks.

Console error:

```<code>File "P:\xxxxxxxxxxxxx\Timesheet.py", line 38, in <module>
    ax.barh(df.client_name, df.num_start_to_end, left=df.start_num)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 2551, in barh
    patches = self.bar(x=left, height=height, width=width, bottom=y,

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py", line 1412, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 2409, in bar
    self.add_patch(r)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py", line 2363, in add_patch
    self._update_patch_limits(p)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py", line 2386, in _update_patch_limits
    patch_trf = patch.get_transform()

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\patches.py", line 278, in get_transform
    return self.get_patch_transform() + artist.Artist.get_transform(self)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\patches.py", line 758, in get_patch_transform
    bbox = self.get_bbox()

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\patches.py", line 851, in get_bbox
    return transforms.Bbox.from_extents(x0, y0, x1, y1)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\transforms.py", line 839, in from_extents
    bbox = Bbox(np.reshape(args, (2, 2)))

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\transforms.py", line 775, in __init__
    points = np.asarray(points, float)

TypeError: float() argument must be a string or a number, not 'Timedelta'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a timesheet.csv that I am trying to plot as a gantt chart.

Not quite sure what the issue is as my understanding is that the start_num is where the hbar begins and the end_num is where the hbar is supposed to end.

import pandas as pd
import matplotlib.pyplot as plt

f = 'timesheet_example.csv'
df = pd.read_csv(f)

df['total_hours'] = pd.to_datetime(df['total_hours'], format='%H')
df['start_time'] = pd.to_datetime(df['start_time'])
df['end_time'] = pd.to_datetime(df['end_time'])

# period start date
period_start = df.start_time.min()

# number of days from period_start to start of tasks
df['start_num'] = (df.start_time - period_start)

# number of days from period_start to end of tasks
df['end_num'] = (df.end_time - period_start)

# days between start and end of each taks
df['num_start_to_end'] = (df.end_num - df.start_num)

fig, ax = plt.subplots(1, figsize=(16,6))
ax.barh(df.client_name, df.num_start_to_end, left=df.start_num)
plt.show()

Ideally, the gantt plot would be an approximate work day (9-5) with the intentions of making it either 15min or 1hr block ticks.

Console error:

File "P:\xxxxxxxxxxxxx\Timesheet.py", line 38, in <module>
    ax.barh(df.client_name, df.num_start_to_end, left=df.start_num)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 2551, in barh
    patches = self.bar(x=left, height=height, width=width, bottom=y,

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py", line 1412, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 2409, in bar
    self.add_patch(r)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py", line 2363, in add_patch
    self._update_patch_limits(p)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py", line 2386, in _update_patch_limits
    patch_trf = patch.get_transform()

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\patches.py", line 278, in get_transform
    return self.get_patch_transform() + artist.Artist.get_transform(self)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\patches.py", line 758, in get_patch_transform
    bbox = self.get_bbox()

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\patches.py", line 851, in get_bbox
    return transforms.Bbox.from_extents(x0, y0, x1, y1)

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\transforms.py", line 839, in from_extents
    bbox = Bbox(np.reshape(args, (2, 2)))

  File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\transforms.py", line 775, in __init__
    points = np.asarray(points, float)

TypeError: float() argument must be a string or a number, not 'Timedelta'


问:
Vendoring dependencies not working with --find-links
I'm trying to build a package with its dependencies and then install in a separate step.

I'm not using a requirements file I'm using setup.cfg and pyproject.toml.

```<code>pip download vendor --dest ./build/dependencies --no-cache-dir
python setup.py check
python setup.py bdist_wheel
python setup.py sdist
</code>```

That seems to install dependencies into the ./build/dependencies folder, but I can't figure out how to install the wheel by looking in that folder for dependencies.

--find-links doesn't appear to work because I get "Could not find a version that satisfies the requirement.." errors when doing this:

```<code>python -m pip install --no-index $(ls dist/*.whl) --find-links="./build/dependencies"
</code>```

It builds fine without --no-index fetching from the internet.

I also tried running pip install with --target like this,
pip install -e . --target=./build/dependencies

But get the same errors when trying to point to it with --find-links.

Body:
I'm trying to build a package with its dependencies and then install in a separate step.

I'm not using a requirements file I'm using setup.cfg and pyproject.toml.

pip download vendor --dest ./build/dependencies --no-cache-dir
python setup.py check
python setup.py bdist_wheel
python setup.py sdist

That seems to install dependencies into the ./build/dependencies folder, but I can't figure out how to install the wheel by looking in that folder for dependencies.

--find-links doesn't appear to work because I get "Could not find a version that satisfies the requirement.." errors when doing this:

python -m pip install --no-index $(ls dist/*.whl) --find-links="./build/dependencies"

It builds fine without --no-index fetching from the internet.

I also tried running pip install with --target like this,
pip install -e . --target=./build/dependencies

But get the same errors when trying to point to it with --find-links.


问:
How to replace a column after a search in Ag-Grid?
```<code>const columns = [
{ headerName: "Product", field: "product"},
{ headerName: "Name", field: "name" },
{ headerName: "Date", field: "date" },
];
</code>```
```<code>const columns1 = [
{ headerName: "Type", field: "type" },
{ headerName: "Open", field: "open" },
{ headerName: "High", field: "high" },
{ headerName: "Percentage", field: "pct" }
];
</code>```
```<code>useEffect(() => {
  fetch(`http://localhost:8080/all?product=${search}`)
    .then(res => { return res.json();
    })
    .then (data => { setRowData(data);
    })
}, [search]);

return (
  <div className="Products">
    <SearchBar onSubmit={setSearch} />
    <div
       className="ag-theme-balham"
       style={{
          height: "300px",
        width: "600px"
         }}
    >
        <AgGridReact
          columnDefs={columns}
        rowData={rowData}
        />
    </div>
  </div>
)
function SearchBar(props) {
    const [innerSearch, setInnerSearch] = useState("");
    return (
      <div >
        <input
          aria-labelledby="search-button"
          name="search"
          id="search"
          type="search"
          value={innerSearch}
          onChange={e => setInnerSearch(e.target.value)}
        />

        <button
          id="search-button"
          type="button"
          onClick={() => props.onSubmit(innerSearch)}
        >
          Search
        </button>
      </div>
    );
  }
};
</code>```

I've gone through a lot of resources to try and get my columns1 to appear after a search, rather than columns. All of the headers from both columns are fields in my API and they all display properly, but I can't seem to split them up and only have columns1 appear when a search is made.

No matter what I try and put in my search bar function, or if I create two <AgGrid/> tables and try to have only one appear, it doesn't work. Either all my columns appear together, or two tables appear.

Body:
const columns = [
{ headerName: "Product", field: "product"},
{ headerName: "Name", field: "name" },
{ headerName: "Date", field: "date" },
];

const columns1 = [
{ headerName: "Type", field: "type" },
{ headerName: "Open", field: "open" },
{ headerName: "High", field: "high" },
{ headerName: "Percentage", field: "pct" }
];

useEffect(() => {
  fetch(`http://localhost:8080/all?product=${search}`)
    .then(res => { return res.json();
    })
    .then (data => { setRowData(data);
    })
}, [search]);

return (

    <SearchBar onSubmit={setSearch} />

        <AgGridReact
          columnDefs={columns}
        rowData={rowData}
        />

)
function SearchBar(props) {
    const [innerSearch, setInnerSearch] = useState("");
    return (

        <input
          aria-labelledby="search-button"
          name="search"
          id="search"
          type="search"
          value={innerSearch}
          onChange={e => setInnerSearch(e.target.value)}
        />

        <button
          id="search-button"
          type="button"
          onClick={() => props.onSubmit(innerSearch)}
        >
          Search
        </button>

    );
  }
};

I've gone through a lot of resources to try and get my columns1 to appear after a search, rather than columns. All of the headers from both columns are fields in my API and they all display properly, but I can't seem to split them up and only have columns1 appear when a search is made.

No matter what I try and put in my search bar function, or if I create two <AgGrid/> tables and try to have only one appear, it doesn't work. Either all my columns appear together, or two tables appear.


问:
Is there a way to make a python plot with changing axis titles if zooming in or out
I'm not looking for an in-depth solution to this problem more so just a pointer in the right direction. I am logging data from 2019 until 2022, it is infrequent sometimes there is data once a day or maybe no data for some months. I would like to be able to view averages for different time scales on the same graph using something like a zoom button. If I'm zoomed out to the max I would like 4 points of data, each year's average, if I zoom in once it may zoom into 2022 and show me each month's average with 12 data points, zoom in again and the weekly average for maybe 24 weeks etc.
Another point to mention is each data point has 4 values, so my current approach is storing them in a list of dictionaries, which I'm hoping to unroll and access with whatever graphing method I end up using.

I'm not aware of what library could make this possible. Thanks


问:
Why my UICollectionView doesn't scroll to the last item of my list?
I have a UICollectionView with a horizontal scroll that shows 3 cells for each page but when I get to the last page there is only one element and it does not let me scroll to show this last element.

This is my list:

```<code>var benefitIcons = ["ic_benefit_frappe", "ic_benefit_birthday", "ic_benefit_2x1", "ic_benefit_points", "ic_benefit_combo", "ic_benefit_cine", "ic_benefit_tickets", "ic_benefit_refill", "ic_benefit_klic", "ic_benefit_pay"]
</code>```

This is the method for UICollectionView:

```<code>extension ProfileCCViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return benefitIcons.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell = benefitCollection.dequeueReusableCell(withReuseIdentifier: "BenefitCell", for: indexPath) as? UserBenefitsCell {
        cell.benefitIcon.image = UIImage(named: benefitIcons[indexPath.row])
        cell.benefitLbl.text = benefitDescriptions[indexPath.row]

        return cell
    } else {
        return UICollectionViewCell()
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: collectionView.bounds.width/3, height: collectionView.bounds.height)
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    benefitControl.currentPage = indexPath.row
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offSet = scrollView.contentOffset.x
    let width = scrollView.frame.width
    let horizontalCenter = width / 2

    benefitControl.currentPage = Int(offSet + horizontalCenter) / Int(width)
}
</code>```

}

This how look like correctly:

But when I'm scrolling to the last item and is uneven doesn't scroll to this last section:

Body:
I have a UICollectionView with a horizontal scroll that shows 3 cells for each page but when I get to the last page there is only one element and it does not let me scroll to show this last element.

This is my list:

var benefitIcons = ["ic_benefit_frappe", "ic_benefit_birthday", "ic_benefit_2x1", "ic_benefit_points", "ic_benefit_combo", "ic_benefit_cine", "ic_benefit_tickets", "ic_benefit_refill", "ic_benefit_klic", "ic_benefit_pay"]

This is the method for UICollectionView:

extension ProfileCCViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return benefitIcons.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell = benefitCollection.dequeueReusableCell(withReuseIdentifier: "BenefitCell", for: indexPath) as? UserBenefitsCell {
        cell.benefitIcon.image = UIImage(named: benefitIcons[indexPath.row])
        cell.benefitLbl.text = benefitDescriptions[indexPath.row]

        return cell
    } else {
        return UICollectionViewCell()
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: collectionView.bounds.width/3, height: collectionView.bounds.height)
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    benefitControl.currentPage = indexPath.row
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offSet = scrollView.contentOffset.x
    let width = scrollView.frame.width
    let horizontalCenter = width / 2

    benefitControl.currentPage = Int(offSet + horizontalCenter) / Int(width)
}

}

This how look like correctly:

But when I'm scrolling to the last item and is uneven doesn't scroll to this last section:


问:
Custom test annotation not working in Quarkus
I setup a multi-module project with quarkus, the core module contains custom test annotation like:

```<code>@QuarkusTest
@Tag("component")
@Documented
@Inherited
@Stereotype
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ComponentTest {
}
</code>```

When I try to use this annotation on any class in another module(my-api) then it says -  javax.enterprise.inject.UnsatisfiedResolutionException: No bean found for required type of that Test class.

Quarkus version 2.14.2.Final

If I move this annotation to my-api module then it works fine.

Body:
I setup a multi-module project with quarkus, the core module contains custom test annotation like:

@QuarkusTest
@Tag("component")
@Documented
@Inherited
@Stereotype
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ComponentTest {
}

When I try to use this annotation on any class in another module(my-api) then it says -  javax.enterprise.inject.UnsatisfiedResolutionException: No bean found for required type of that Test class.

Quarkus version 2.14.2.Final

If I move this annotation to my-api module then it works fine.


问:
Is there a way to place the jboss-eap management/console endpoints behind a different root context?
Good afternoon,

Trying to figure out a way to get the /console and /management endpoints for the jbosseap console to not live at the top level and instead be hosted under :9990/admin/console and :9990/admin/management.

So far all I can find is how to modify various webapps root-context and nothing for jboss specific/admin endpoints. Searched through the install folder as well and was unable to locate a config file that allowed this ability.

Redhat forums state all forums are now read-only and directed questions to stackoverflow.


问:
How can I do a connection with Filter component and Card component
I'm trying to do a "connection" with my Filter component and my Cards component. The user should select the filter, it would only show the Cards with that filter selected.
When the user click in a filter button, it shows the specific Cards correct, but when the user click again in another filter, it dissapear all the Cards. Problably is something in the filter function but I can't figure out.

Here is the page:
[

Here is the Filter component:

```<code>import React from "react";
import Carrousel from "react-elastic-carousel";
import "./filtro.css";

function Filtro({ filtros, itensFiltrado }) {
  const breakPoints = [
    { width: 1, itemsToShow: 1, pagination: false },
    { width: 600, itemsToShow: 2, pagination: false },
    { width: 860, itemsToShow: 5, pagination: false },
    { width: 1100, itemsToShow: 5, pagination: false },
    { width: 1700, itemsToShow: 6, pagination: false },
  ];

  return (
    <div className="filtro__segmento">
      <Carrousel breakPoints={breakPoints}>
        {filtros.map((filtro, id) => {
          return (
            <label
              className="card__segmento"
              key={id}
              onClick={() => itensFiltrado(filtro)}
            >
              <h2 className="segmento__titulo">{filtro}</h2>
              <input type="radio" className="input-radio" name="teste" />
              <span className="check"></span>
            </label>
          );
        })}
      </Carrousel>
    </div>
  );
}

export default Filtro;
</code>```

The Father Component:

```<code>import React, { useEffect, useState } from "react";
import "./popupOrcamentoSimultaneo.css";
import Filtro from "./Filtro";
import Card from "./Card";

import api from "../../../../api";

function PopupOrcamentoSimultaneo({ setOpenPopup, checkedState }) {
  const [profissionais, setProfissionais] = useState([]);
  const [filtroProfissionais, setFiltroProfissionais] = useState([]);
  const [filtros, setFiltros] = useState([]);
  const [value, setValue] = useState(
    "Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
  );

  useEffect(() => {
    api.get("profissionais/listarTodos/").then(({ data }) => {
      setProfissionais(data);
      const setOfFilters = new Set(
        data.map((profissional) => profissional.segmento)
      );
      setFiltros([...setOfFilters]);
    });
  }, []);

  const itensFiltrado = (segmentoEmpresa) => {
    const novosProfissionais = profissionais.filter(
      (profissional) => profissional.segmento === segmentoEmpresa
    );
    setProfissionais(novosProfissionais);
  };

  let cardsProfissionais = profissionais;
  let listaCardsProfissionais = [];

  for (let i = 0; i < cardsProfissionais.length; i++) {
    listaCardsProfissionais.push(
      <Card dadosProfissionais={cardsProfissionais[i]} />
    );
  }

  const changeValue = (e) => {
    setValue(e.target.value);
  };

  return (
    <div className="popup">
      <div className="popup__container">
        <div className="close-container" onClick={() => setOpenPopup(false)}>
          <i className="fa-solid fa-xmark"></i>
        </div>
        <h2 className="popup__titulo">
          Solicite orçamento à outros profissionais simultaneamente!
        </h2>
        <Filtro filtros={filtros} itensFiltrado={itensFiltrado} />
        <h3 className="popup__subtitulo">
          Profissionais recomendados para você.
        </h3>
       <div className="cards__profissionais">{listaCardsProfissionais}</div>

        <div className="input-box">
          <label for="input" className="input-label">
            Escreva sua mensagem
          </label>
          <div>
            <input
              type="text"
              id="input"
              className="input-text"
              placeholder="Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
              value={value}
              onChange={changeValue}
            />
            <i className="fa-solid fa-pencil"></i>
          </div>
        </div>
      </div>
    </div>
  );
}

export default PopupOrcamentoSimultaneo;
</code>```

The Card Component (if necessary):

```<code>import React, { useState } from "react";
import "./card.css";

function Card(props) {
  let nomeEmpresa = props.dadosProfissionais.nomeEmpresa;
  let segmento = props.dadosProfissionais.segmento;
  let valorMinimo = props.dadosProfissionais.valorMinimo;
  let cidade = props.dadosProfissionais.cidade;
  let estado = props.dadosProfissionais.estado;
  let idProfissional = props.dadosProfissionais.idProfissional;
  let imagemVitrine = props.dadosProfissionais.imagemMarketplace;

  let nomeArquivo = imagemVitrine ? imagemVitrine : "no-image.png";

  /*  const imagemVitrineProfissional = require(`../../../../../fileContents/imagensVitrineProfissional/${imagemVitrine}`); */

  const [checkedState, setCheckedState] = useState({});

  const handleOnChange = (e) => {
    setCheckedState((p) => ({ ...p, [e.target.name]: e.target.checked }));
  };

  return (
    <>
      <div className="card__profissional" key={idProfissional}>
        <div className="card__header">
          <img
            className="card-imagem"
            src={imagemVitrine}
            alt={`${nomeEmpresa}`}
          />
        </div>
        <div className="card__body">
          <h2 className="card__titulo">{nomeEmpresa}</h2>
          <span className="tag">{cidade}</span>
          <div className="checkbox">
            <label className="checkbox-label">
              Solicitar Orçamento
              <input
                type="checkbox"
                className="checkbox-input"
                name={nomeEmpresa}
                value={nomeEmpresa}
                checked={checkedState[nomeEmpresa] || false}
                onChange={handleOnChange}
              />
              <span className="checkmark"></span>
            </label>
          </div>
        </div>
      </div>
      <button type="submit" className="botao-orcamento">
        Solicitar Orçamento (
        {Object.keys(checkedState).filter((i) => checkedState[i]).length})
      </button>
    </>
  );
}

export default Card;
</code>```

Body:
I'm trying to do a "connection" with my Filter component and my Cards component. The user should select the filter, it would only show the Cards with that filter selected.
When the user click in a filter button, it shows the specific Cards correct, but when the user click again in another filter, it dissapear all the Cards. Problably is something in the filter function but I can't figure out.

Here is the page:
[

Here is the Filter component:

import React from "react";
import Carrousel from "react-elastic-carousel";
import "./filtro.css";

function Filtro({ filtros, itensFiltrado }) {
  const breakPoints = [
    { width: 1, itemsToShow: 1, pagination: false },
    { width: 600, itemsToShow: 2, pagination: false },
    { width: 860, itemsToShow: 5, pagination: false },
    { width: 1100, itemsToShow: 5, pagination: false },
    { width: 1700, itemsToShow: 6, pagination: false },
  ];

  return (

      <Carrousel breakPoints={breakPoints}>
        {filtros.map((filtro, id) => {
          return (
             itensFiltrado(filtro)}
            >

{filtro}

              <input type="radio" className="input-radio" name="teste" />

          );
        })}
      </Carrousel>

  );
}

export default Filtro;

The Father Component:

import React, { useEffect, useState } from "react";
import "./popupOrcamentoSimultaneo.css";
import Filtro from "./Filtro";
import Card from "./Card";

import api from "../../../../api";

function PopupOrcamentoSimultaneo({ setOpenPopup, checkedState }) {
  const [profissionais, setProfissionais] = useState([]);
  const [filtroProfissionais, setFiltroProfissionais] = useState([]);
  const [filtros, setFiltros] = useState([]);
  const [value, setValue] = useState(
    "Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
  );

  useEffect(() => {
    api.get("profissionais/listarTodos/").then(({ data }) => {
      setProfissionais(data);
      const setOfFilters = new Set(
        data.map((profissional) => profissional.segmento)
      );
      setFiltros([...setOfFilters]);
    });
  }, []);

  const itensFiltrado = (segmentoEmpresa) => {
    const novosProfissionais = profissionais.filter(
      (profissional) => profissional.segmento === segmentoEmpresa
    );
    setProfissionais(novosProfissionais);
  };

  let cardsProfissionais = profissionais;
  let listaCardsProfissionais = [];

  for (let i = 0; i < cardsProfissionais.length; i++) {
    listaCardsProfissionais.push(
      <Card dadosProfissionais={cardsProfissionais[i]} />
    );
  }

  const changeValue = (e) => {
    setValue(e.target.value);
  };

  return (

 setOpenPopup(false)}>

          Solicite orçamento à outros profissionais simultaneamente!

        <Filtro filtros={filtros} itensFiltrado={itensFiltrado} />

          Profissionais recomendados para você.

{listaCardsProfissionais}

            Escreva sua mensagem

            <input
              type="text"
              id="input"
              className="input-text"
              placeholder="Olá! Vamos nos casar e gostariamos de mais informações sobre seu serviço."
              value={value}
              onChange={changeValue}
            />

  );
}

export default PopupOrcamentoSimultaneo;

The Card Component (if necessary):

import React, { useState } from "react";
import "./card.css";

function Card(props) {
  let nomeEmpresa = props.dadosProfissionais.nomeEmpresa;
  let segmento = props.dadosProfissionais.segmento;
  let valorMinimo = props.dadosProfissionais.valorMinimo;
  let cidade = props.dadosProfissionais.cidade;
  let estado = props.dadosProfissionais.estado;
  let idProfissional = props.dadosProfissionais.idProfissional;
  let imagemVitrine = props.dadosProfissionais.imagemMarketplace;

  let nomeArquivo = imagemVitrine ? imagemVitrine : "no-image.png";

  /*  const imagemVitrineProfissional = require(`../../../../../fileContents/imagensVitrineProfissional/${imagemVitrine}`); */

  const [checkedState, setCheckedState] = useState({});

  const handleOnChange = (e) => {
    setCheckedState((p) => ({ ...p, [e.target.name]: e.target.checked }));
  };

  return (
    <>

          <img
            className="card-imagem"
            src={imagemVitrine}
            alt={`${nomeEmpresa}`}
          />

{nomeEmpresa}

          {cidade}

              Solicitar Orçamento
              <input
                type="checkbox"
                className="checkbox-input"
                name={nomeEmpresa}
                value={nomeEmpresa}
                checked={checkedState[nomeEmpresa] || false}
                onChange={handleOnChange}
              />

      <button type="submit" className="botao-orcamento">
        Solicitar Orçamento (
        {Object.keys(checkedState).filter((i) => checkedState[i]).length})
      </button>
    </>
  );
}

export default Card;


问:
Activate A Device's Third-Party Video-Camera Software With HTML Form-File-Picker
I have an html form on my website which allows users to submit a short video file.

The code I am presently using effectively allows the user to either select a Pre-Recorded video file, or record a new video.

accept="video/*;capture=camcorder"

If I had my preference, I would opt to have the picker 'disable' the 'select-file' option, and only allow it to activate the device's video camera software. So the user could only record and submit a new video. But I'm not even sure that's possible, and that's not my immediate issue.

The immediate issue is, my present code will only activate the 'generic' Video Camera software on devices. It will not activate any 'third-party' or 'advanced' video camera software options.

Is there a working code available, or an adjustment to my existing code which would allow a fix for either or both of these issues?

Any suggestions would be greatly appreciated.

Below is my current code...

THE FORM

```<code><!DOCTYPE html>

<head>

<title>Video Form</title>

</head>

<body>

<form action="/videoformHandler.php" method="post"
enctype="multipart/form-data">

<h1>VIDEO FORM</h1>

<input type="text" id="userName" name="userName" placeholder=" User
Name"
onfocus="this.placeholder = ''" onblur="this.placeholder = ' Name'"
required=""><br><br>

<input type="email" id="userEmail" name="userEmail" placeholder="
user@email.com"
onfocus="this.placeholder = ''" onblur="this.placeholder = '
your@email.com'" required=""><br>
<br>

<input type="file" id="file" name="userImages"
accept="video/*;capture=camcorder" required=""/><br><br>

<input type="submit" id="submitButton" name="submitButton"
class="submit__button"
value="Submit">

</form>

</body>

</html>
</code>```

FORM HANDLER

```<code><?php

/////

$filenameee =  $_FILES['userImages']['name'];
$fileName = $_FILES['userImages']['tmp_name'];
$name = $_POST['userName'];
$email = $_POST['userEmail'];

/////

$composition =

"\r\n\n\nName: " . $name .
"\r\nEmail Address: " . $email;

/////

$subject ="Video Message";
$fromname ="$name";
$fromemail = "$email";
$mailto = 'receiving@email.com'; //recipient email

//The Content Action

$content = file_get_contents($fileName);
$content = chunk_split(base64_encode($content));

// A random hash will be necessary to send mixed content

$separator = md5(time());

// Carriage return type (RFC)

$eol = "\r\n";

/////

$headers = "From: ".$fromname." <".$fromemail.">" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator .
"\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;

/////

$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $composition . $eol;

/////

$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/octet-stream; name=\"" . $filenameee
. "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";

/////

//Mail send action

@mail($mailto, $subject, $body, $headers);

//Page Re-direct after form submission

header('location: /videoformsent.php');

?>
</code>```

SENT CONFIRMATION

```<code><!DOCTYPE html>

<head>

<title>Sent Confirmation</title>

</head>

<body>

Your Video Has Been Successfully Sent!

</body>

</html>
</code>```

Body:
I have an html form on my website which allows users to submit a short video file.

The code I am presently using effectively allows the user to either select a Pre-Recorded video file, or record a new video.

accept="video/*;capture=camcorder"

If I had my preference, I would opt to have the picker 'disable' the 'select-file' option, and only allow it to activate the device's video camera software. So the user could only record and submit a new video. But I'm not even sure that's possible, and that's not my immediate issue.

The immediate issue is, my present code will only activate the 'generic' Video Camera software on devices. It will not activate any 'third-party' or 'advanced' video camera software options.

Is there a working code available, or an adjustment to my existing code which would allow a fix for either or both of these issues?

Any suggestions would be greatly appreciated.

Below is my current code...

THE FORM

<!DOCTYPE html>

<title>Video Form</title>

<form action="/videoformHandler.php" method="post"
enctype="multipart/form-data">

VIDEO FORM

<input type="text" id="userName" name="userName" placeholder=" User
Name"
onfocus="this.placeholder = ''" onblur="this.placeholder = ' Name'"
required="">

<input type="email" id="userEmail" name="userEmail" placeholder="
user@email.com"
onfocus="this.placeholder = ''" onblur="this.placeholder = '
your@email.com'" required="">

<input type="file" id="file" name="userImages"
accept="video/*;capture=camcorder" required=""/>

<input type="submit" id="submitButton" name="submitButton"
class="submit__button"
value="Submit">

</form>

FORM HANDLER

<?php

/////

$filenameee =  $_FILES['userImages']['name'];
$fileName = $_FILES['userImages']['tmp_name'];
$name = $_POST['userName'];
$email = $_POST['userEmail'];

/////

$composition =

"\r\n\n\nName: " . $name .
"\r\nEmail Address: " . $email;

/////

$subject ="Video Message";
$fromname ="$name";
$fromemail = "$email";
$mailto = 'receiving@email.com'; //recipient email

//The Content Action

$content = file_get_contents($fileName);
$content = chunk_split(base64_encode($content));

// A random hash will be necessary to send mixed content

$separator = md5(time());

// Carriage return type (RFC)

$eol = "\r\n";

/////

$headers = "From: ".$fromname." <".$fromemail.">" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator .
"\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;

/////

$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $composition . $eol;

/////

$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/octet-stream; name=\"" . $filenameee
. "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";

/////

//Mail send action

@mail($mailto, $subject, $body, $headers);

//Page Re-direct after form submission

header('location: /videoformsent.php');

?>

SENT CONFIRMATION

<!DOCTYPE html>

<title>Sent Confirmation</title>

Your Video Has Been Successfully Sent!


问:
Download a google file from VBA
I tried Download Google Drive File from Excel Sheet using VBA.

It says success but I can't find the file. I made sure the directory exisited but it is not there. Where could it be going?

Download Google Drive File from Excel Sheet using VBA

No file even though success

Title: Download a google file from VBA


问:
rnotebook latex issue
Apologies in advance because I do not know how to communicate this question via code.

I have an R Notebook  document with some latex (maybe not formally latex, but it's mathematical notation). Previously, when the document was in visual mode, I could see my notation inside the notebook. Now, when I compile the document to a pdf the notion appears, however, the notation is no longer visible in visual mode. Does anyone know what is wrong? My first thought was it could be due to an update; however, I am fairly certain that I have not updated anything since.

Title: rnotebook latex issue


问:
how to solove React.js module not found :Error dependency (no request) error
this is my code

```<code>import React from 'react'
import './portfolio.css'
import IMG1 from '../../assets/PairUp.jpg'
import IMG2 from '../../assets/4AnimeArchive.jpg'
import IMG3 from '../../assets/console.log.jpg'
import IMG4 from ''
import IMG5 from '../../assets/weather.jpg'
import IMG6 from '../../assets/snakeGame.png'

const data = [
  {
    id: 1,
    image: IMG1,
    title: 'Pair_Up',
    github: 'https://github.com/Adipure/pairUp',
    demo: 'https://me0wmerz.github.io/pairUp/'
  },
  {
    id: 2,
    image: IMG2,
    title: '4AnimeArchive',
    github: 'https://github.com/Adipure/anotherAnimeArchive',
    demo: ''
  },
  {
    id: 3,
    image: IMG3,
    title: 'Console.log',
    github: 'https://github.com/Adipure/console.log',
    demo: ''
  },
  {
    id: 4,
    image: IMG4,
    title: '',
    github: '',
    demo: ''
  },
  {
    id: 5,
    image: IMG5,
    title: 'Weather App',
    github: 'https://github.com/Adipure/WeatherHomwork',
    demo: 'https://adipure.github.io/WeatherHomwork/'
  },
  {
    id: 6,
    image: IMG6,
    title: 'Snake Game',
    github: 'https://github.com/Adipure/snakeGame',
    demo: ''
  }
]

const Portfolio = () => {
  return (
    <section id='portfolio'>
      <h5>My Recent Projects</h5>
      <h2>Portfolio</h2>
      <div className='container portfolio_container'>
        {
          data.map(({ id, image, title, github, demo }) => {
            return (
              <article key={id} className='portfolio_item'>
                <div className='portfolio_item-image'>
                  <img src={image} alt={title} />
                </div>
                <h3>{title}</h3>
                <div className='portfolio_item-cta'>
                  <a href={github} className='btn' target='_blank' rel='noreferrer'>Github</a>
                  <a href={demo} className='btn btn-primary' target='_blank' rel='noreferrer'>Live View</a>
                </div>
              </article>
            )
          })
        }
      </div>
    </section>
  )
}

export default Portfolio

</code>```

and this is what i am getting with Failed to compile.

Module not found: Error: Empty dependency (no request)
ERROR in ./src/components/portfolio/Portfolio.jsx 9:0-20
Module not found: Error: Empty dependency (no request)

webpack compiled with 1 error

please help how to solve this error.

I have tried to re install NPM packages but it did not work

Body:
this is my code

import React from 'react'
import './portfolio.css'
import IMG1 from '../../assets/PairUp.jpg'
import IMG2 from '../../assets/4AnimeArchive.jpg'
import IMG3 from '../../assets/console.log.jpg'
import IMG4 from ''
import IMG5 from '../../assets/weather.jpg'
import IMG6 from '../../assets/snakeGame.png'

const data = [
  {
    id: 1,
    image: IMG1,
    title: 'Pair_Up',
    github: 'https://github.com/Adipure/pairUp',
    demo: 'https://me0wmerz.github.io/pairUp/'
  },
  {
    id: 2,
    image: IMG2,
    title: '4AnimeArchive',
    github: 'https://github.com/Adipure/anotherAnimeArchive',
    demo: ''
  },
  {
    id: 3,
    image: IMG3,
    title: 'Console.log',
    github: 'https://github.com/Adipure/console.log',
    demo: ''
  },
  {
    id: 4,
    image: IMG4,
    title: '',
    github: '',
    demo: ''
  },
  {
    id: 5,
    image: IMG5,
    title: 'Weather App',
    github: 'https://github.com/Adipure/WeatherHomwork',
    demo: 'https://adipure.github.io/WeatherHomwork/'
  },
  {
    id: 6,
    image: IMG6,
    title: 'Snake Game',
    github: 'https://github.com/Adipure/snakeGame',
    demo: ''
  }
]

const Portfolio = () => {
  return (

My Recent Projects

Portfolio

        {
          data.map(({ id, image, title, github, demo }) => {
            return (

{title}

                  Github
                  Live View

            )
          })
        }

  )
}

export default Portfolio

and this is what i am getting with Failed to compile.

Module not found: Error: Empty dependency (no request)
ERROR in ./src/components/portfolio/Portfolio.jsx 9:0-20
Module not found: Error: Empty dependency (no request)

webpack compiled with 1 error

please help how to solve this error.

I have tried to re install NPM packages but it did not work


问:
c++ if statements reading less than as an equal to
So TR[i] is an array which is set to 4 at the beginning of the code. Every verable is a float.

```<code>float = RA;
int i;
float TR[4] = { 4, 4, 4, 4 };

RA = 0.75f;
TR[i] = TR[i] - (RA + 0.25f);
// when you output TR[i] it is 3
if (TR[i] < 3)
{
    TR[i] = TR[i] - 0.25f;
}

cout << TR[i];
</code>```

the output should be 3 but it's saying it is 2.5

My problem is that the program is still running the if statment when it should not be doing that because 3 < 3 is not correct? would love to know what is wrong?

Body:
So TR[i] is an array which is set to 4 at the beginning of the code. Every verable is a float.

float = RA;
int i;
float TR[4] = { 4, 4, 4, 4 };

RA = 0.75f;
TR[i] = TR[i] - (RA + 0.25f);
// when you output TR[i] it is 3
if (TR[i] < 3)
{
    TR[i] = TR[i] - 0.25f;
}

cout << TR[i];

the output should be 3 but it's saying it is 2.5

My problem is that the program is still running the if statment when it should not be doing that because 3 < 3 is not correct? would love to know what is wrong?


问:
Mlflow ui cannot read logged runs from the right directory
I used mlflow.tensorflow.autolog function to track my keras deep learning model. However, the mlflow ui cannot find the /mlruns directory where the logged runs are stored.

My logged runs stored in /model/mlruns where the model's python code located in /model.

However, the mlflow ui tries to read logged run located at ./venv/Scripts/mlruns.

I need to manually copy the logged run from /model/mlruns to /venv/Scripts/mlruns in order to let mlflow ui find the logged run.

Is there any way to let mlflow ui read runs stored in /model/mlruns. Or make the output directory of logged run be /venv/Scripts/mlruns?


问:
KeyboardAvoidingView adding extra space or doing nothing-- not working as expected
I'm using a keyboardAvoidingView in my project, and I can get it to either add too much whitespace, pushing the actual page up to about halfway up the screen OR it does nothing at all and the keyboard just covers everything it normally would. I cannot get it to behave as anticipated.

I've tried wrapping the contents of App.js with a KeyboardAvoidingView, I've tried wrapping each individual page with a KeyboardAvoidingView, and I've tried various iterations of props. These include...

```<code><KeyboardAvoidingView
behavior="padding"
enabled
style={{flexGrow:1, height:'100%'}}
>
...
</KeyboardAvoidingView>

</code>```
```<code><KeyboardAvoidingView
behavior="padding"
enabled
style={{flexGrow:1'}}
>
...
</KeyboardAvoidingView>

</code>```
```<code><KeyboardAvoidingView
behavior="padding"
enabled
style={{flexGrow:1'}}
keyboardVerticalOffset={100}
>
...
</KeyboardAvoidingView>

</code>```
```<code><KeyboardAvoidingView
behavior="padding"
enabled
style={{flexGrow:1'}}
keyboardVerticalOffset={-100}
>
...
</KeyboardAvoidingView>

</code>```
```<code><KeyboardAvoidingView
behavior="padding"
enabled
style={{flex:1'}}
keyboardVerticalOffset={-100}
>
...
</KeyboardAvoidingView>

</code>```

You get the idea. I've also done all of these with behavior='height' and with no behavior at all. Same results-- either too much extra space or no effect at all.

I've checked several other asked questions, nearly all of them suggest changing the behavior or adding keyboardVerticalOffset={100} but again, neither works. I have seen that Navigation.Stack can cause issues if used in App.js, but that makes no sense why it doesn't work individually then.

I currently have it wrapping App.js and that only works on one page for some reason, all the others it has no effect on. This really isn't a problem for most of the app because I just worked around it and kept all the inputs higher up on the page (not ideal) but for the messaging component this is not an option. Nothing seems to work on iOS. Does anyone have suggestions?

Body:
I'm using a keyboardAvoidingView in my project, and I can get it to either add too much whitespace, pushing the actual page up to about halfway up the screen OR it does nothing at all and the keyboard just covers everything it normally would. I cannot get it to behave as anticipated.

I've tried wrapping the contents of App.js with a KeyboardAvoidingView, I've tried wrapping each individual page with a KeyboardAvoidingView, and I've tried various iterations of props. These include...

<KeyboardAvoidingView
behavior="padding"
enabled
style={{flexGrow:1, height:'100%'}}
>
...
</KeyboardAvoidingView>

<KeyboardAvoidingView
behavior="padding"
enabled
style={{flexGrow:1'}}
>
...
</KeyboardAvoidingView>

<KeyboardAvoidingView
behavior="padding"
enabled
style={{flexGrow:1'}}
keyboardVerticalOffset={100}
>
...
</KeyboardAvoidingView>

<KeyboardAvoidingView
behavior="padding"
enabled
style={{flexGrow:1'}}
keyboardVerticalOffset={-100}
>
...
</KeyboardAvoidingView>

<KeyboardAvoidingView
behavior="padding"
enabled
style={{flex:1'}}
keyboardVerticalOffset={-100}
>
...
</KeyboardAvoidingView>

You get the idea. I've also done all of these with behavior='height' and with no behavior at all. Same results-- either too much extra space or no effect at all.

I've checked several other asked questions, nearly all of them suggest changing the behavior or adding keyboardVerticalOffset={100} but again, neither works. I have seen that Navigation.Stack can cause issues if used in App.js, but that makes no sense why it doesn't work individually then.

I currently have it wrapping App.js and that only works on one page for some reason, all the others it has no effect on. This really isn't a problem for most of the app because I just worked around it and kept all the inputs higher up on the page (not ideal) but for the messaging component this is not an option. Nothing seems to work on iOS. Does anyone have suggestions?


问:
Firebase function TypeError .once is not a function and onCreate not working
I was trying to deploy a function to Firebase to send notifications to all admin accounts when a new user signs up to the app, this is my current code:

```<code>const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.newDoctorNotification = functions.database.ref("/doctors/{pushId}")
    .onCreate((snapshot, context) => {
      const newDoctorID = context.params.pushId;
      const notificationContent = {
        notification: {
          title: "New Doctor",
          body: "A new doctor just signed up! uid: " + newDoctorID,
          icon: "default",
          sound: "default",
        },
      };

      const adminTokensRef = functions.database.ref("device_tokens/admin");
      const tokens = [];

      adminTokensRef.once("value", (querySnapshot) => {
            querySnapshot.forEach((adminToken) => {
              tokens.push(adminToken.val());
            });
          });

      if (tokens.length > 0) {
        return admin.messaging().sendToDevice(tokens, notificationContent)
            .then(function(result) {
              console.log("Notification sent");
              return null;
            })
            .catch(function(error) {
              console.log("Notification failed ", error);
              return null;
            });
      }
    });
</code>```

I have tried many variations such as the get() function and on(), but all give me the same error, I was trying to check the docs on this but they only talked about database triggers so I'm not sure if normal retrieval can work or not.

EDIT:
I updated my code to reach the database node through the snapshot given in the onCreate event, and now it works, although I am facing another problem now, if I push a new doctor under the node "doctors" it doesn't call the function.. but if I hit "test" in the Google Cloud console and it calls the function I get "null" in my snapshot.val() and "undefined" in the newDoctorID above, whereas the snapshot.key gives "doctors", why is it not calling the onCreate function?

Body:
I was trying to deploy a function to Firebase to send notifications to all admin accounts when a new user signs up to the app, this is my current code:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.newDoctorNotification = functions.database.ref("/doctors/{pushId}")
    .onCreate((snapshot, context) => {
      const newDoctorID = context.params.pushId;
      const notificationContent = {
        notification: {
          title: "New Doctor",
          body: "A new doctor just signed up! uid: " + newDoctorID,
          icon: "default",
          sound: "default",
        },
      };

      const adminTokensRef = functions.database.ref("device_tokens/admin");
      const tokens = [];

      adminTokensRef.once("value", (querySnapshot) => {
            querySnapshot.forEach((adminToken) => {
              tokens.push(adminToken.val());
            });
          });

      if (tokens.length > 0) {
        return admin.messaging().sendToDevice(tokens, notificationContent)
            .then(function(result) {
              console.log("Notification sent");
              return null;
            })
            .catch(function(error) {
              console.log("Notification failed ", error);
              return null;
            });
      }
    });

I have tried many variations such as the get() function and on(), but all give me the same error, I was trying to check the docs on this but they only talked about database triggers so I'm not sure if normal retrieval can work or not.

EDIT:
I updated my code to reach the database node through the snapshot given in the onCreate event, and now it works, although I am facing another problem now, if I push a new doctor under the node "doctors" it doesn't call the function.. but if I hit "test" in the Google Cloud console and it calls the function I get "null" in my snapshot.val() and "undefined" in the newDoctorID above, whereas the snapshot.key gives "doctors", why is it not calling the onCreate function?


问:
APS (Forge) Design Automation Inventor Lighting Styles
I am creating Inventor drawings with shaded drawing views as the component colors are important to be shown. The views appear much lighter when the drawings are created in Forge compared to when created locally. I have included the Design Data folder along with the project file pointing to it in the bucket upload.

I tried adjusting the lighting style for the assembly and saving both as a local style in the document and also to the Styles Library. This changed the appearance of the views for the drawings created locally, however had no effect on the drawings created in Forge.

It seems like some of the Design Data is being used as the dimension styles from the Design Data are working, but the lighting doesn't seem to be.

I also tried adding an iLogic rule that sets the Active Lighting Style before saving the assembly. This too had the same results.

How can I control the lighting style in Forge?


问:
Javascript: button onclick function which will increase the HTML output number per click
Want to create a small application which have the function of counter and alarm. So there is two button, -1 and +1. When click the button, the number will continuesly change according to the time you click. So if click -1 button once, it will shows 0-1, if click -1 again, it will shows 0-2. Button

I try to use localstorage command to record each time when the button is clicked. I wondered is there other easier way to solve it.


问:
ActiveBatch (ABv11) reporting or scripting about configured objects and tasks
Using ABv11, upgrading to v12 some time in near future.

Looking to cleanup the AB db ie. get rid of old objects that no longer serve a purpose prior to migration.

Thinking there should be a way to query the AB db for "last run timestamp" or maybe a tool to validate that the object/task still points to something at the other end on the production database. ie. a batch task no longer exists in the production tool but still has an AB task associated with it.

Is there any way to actually manage AB at a high level without having to go into each task/object and check individual TS's or reconcile against the target production objects?

Thanks.

Have researched different forums and the vendor site but nothingburger.


问:
Problem with skiping the if conditions in python
I need to create unique numbers for database.

First i'm getting all existing numbers from database:

```<code>conn.execute('SELECT numer FROM Brama')
BCheck = conn.getData()
</code>```

Then i'm creating additional list:

```<code>bramy = []
</code>```

and now with simple loop i'm creating new numbers:

```<code>while True:
    numer = random.randint(1,15)
    if numer not in BCheck or bramy:
        bramy.append(numer)
        print(BCheck)
        print(bramy)
        break
</code>```

And 'if' is skipping conditions:
enter image description here

BCheck is list of integers.
Any ideas why?

I have tried to force BCheck to be integer, then i checked if BCheck sums(like integer should) and it works.This exact While true loop works with strings in different part of code.

Body:
I need to create unique numbers for database.

First i'm getting all existing numbers from database:

conn.execute('SELECT numer FROM Brama')
BCheck = conn.getData()

Then i'm creating additional list:

bramy = []

and now with simple loop i'm creating new numbers:

while True:
    numer = random.randint(1,15)
    if numer not in BCheck or bramy:
        bramy.append(numer)
        print(BCheck)
        print(bramy)
        break

And 'if' is skipping conditions:
enter image description here

BCheck is list of integers.
Any ideas why?

I have tried to force BCheck to be integer, then i checked if BCheck sums(like integer should) and it works.This exact While true loop works with strings in different part of code.


问:
delta live table expectations syntax looks different
I was looking at a code and saw that the expect_all is coded as below

```<code>dlt.expect_all(dict_expectations)(dlt_quarantine_view)
</code>```

My understanding of the syntax was that it takes a dictionary of expectations and executes that, i am not able ti understand why the second argument in brackets is there.

Body:
I was looking at a code and saw that the expect_all is coded as below

dlt.expect_all(dict_expectations)(dlt_quarantine_view)

My understanding of the syntax was that it takes a dictionary of expectations and executes that, i am not able ti understand why the second argument in brackets is there.


问:
SCSS (PHP) - Rule applied despite media query
In my layout.scss I have the following code:

@media(max-width:1100px) {
  #wrap-nav .nav {@extends .block;} # Comes from generic scss file
}
```
<p>in my main <code>styles.scss</code> I import that file, it looks like this:</p>
<pre class="lang-scss prettyprint-override"><code>@import "layout.scss";

#wrap-nav .nav {display:flex;}
</code>```

I have no idea why but with a 1920px width I still see SCSS compiling this as

```<code>#wrap-nav .nav {
  display: block;
}
</code>```

but it shouldn't be compiled without the media query, should it? Am I missing something here?

Body:
In my layout.scss I have the following code:

@media(max-width:1100px) {
  #wrap-nav .nav {@extends .block;} # Comes from generic scss file
}

in my main styles.scss I import that file, it looks like this:

@import "layout.scss";

#wrap-nav .nav {display:flex;}

I have no idea why but with a 1920px width I still see SCSS compiling this as

#wrap-nav .nav {
  display: block;
}

but it shouldn't be compiled without the media query, should it? Am I missing something here?


问:
Generating Standardised Mean Differences in R
I would like to generate SMD and plot them without including the prediction model in my code; I am using the cobalt package and specifically the loveplot command to generate the plot. However, I would like to just include the probability of treatment in my code as opposed to including the full prediction model in the code as shown below.</p>
```<code>library(WeightIt); data("lalonde", package = "cobalt")

w.out1 <- weightit(treat ~ age + educ + race +
                     married + nodegree + re74 + re75,
                   data = lalonde)

love.plot(treat ~ age + educ + race +
            married + nodegree + re74 + re75,
          data = lalonde,
          weights = list(IPW =w.out1 ),
          var.order = "alphabetical", binary = "std",
          abs = FALSE, colors = c("red", "blue"),
          shapes = c("circle", "triangle"),
          sample.names = c("Unweighted", "PS Weighted"),
          line = FALSE,
          themes = list(theme(legend.position = "top")))

</code>```

Body:
I would like to generate SMD and plot them without including the prediction model in my code; I am using the cobalt package and specifically the loveplot command to generate the plot. However, I would like to just include the probability of treatment in my code as opposed to including the full prediction model in the code as shown below.

library(WeightIt); data("lalonde", package = "cobalt")

w.out1 <- weightit(treat ~ age + educ + race +
                     married + nodegree + re74 + re75,
                   data = lalonde)

love.plot(treat ~ age + educ + race +
            married + nodegree + re74 + re75,
          data = lalonde,
          weights = list(IPW =w.out1 ),
          var.order = "alphabetical", binary = "std",
          abs = FALSE, colors = c("red", "blue"),
          shapes = c("circle", "triangle"),
          sample.names = c("Unweighted", "PS Weighted"),
          line = FALSE,
          themes = list(theme(legend.position = "top")))


问:
How can I import a Postman collection to replace a forked instance of that collection?
I have been tasked with doing an extensive refactor of a fairly large Postman collection. To do a bulk of this work, I wanted to export the Postman collection to a .json file to do some string replacements on before importing it back in. This collection is in active use, so I want to be able to test my changes before making a pull request into the original collection using Postman's built in version control. The problem here is that when I go to import the collection back into the app, it wants to replace the original collection instead of my fork.

My steps that have led me to this situation are as follows:

Create a fork of the "Company APIs" collection.

Make a number of changes to folder structure, write a few scripts, etc.

Export the forked collection to a json file. Make a number of bulk string changes using my local text editor.

Attempt to import the collection back into postman. Risk clobbering the original collection and therefore my change process for the fork.

I tried performing the above process with a trivial change as a test, and can confirm that re-importing the collection replaces the original "Company APIs" collection, and not my fork of it.

Thank you.


问:
draw a shape with QPainterPath having a border strictly on the inside of the shape
Simply put, when I draw a border of a certain shape using QPainter with a pen of width e.g. penWidth = 10.0 then one half of the border width is actually painted outside of the shape area and one half is drawn inside.

I would however like to paint a shape with a pen such that the border is only on the inside of the shape area.

I probably can use this trick: I set the pen's width twice as big and I also set the clip path so that the outer half of the border line is clipped away and only the inner half of the border line remains.

Example:

```<code>QColor penColor(Qt::red);
qreal penWidth = 5.0;
QPainterPath shape;
// ...here I define the shape

QPainter painter(device);

// the trick comes here
QPen p(penColor, penWidth * 2); // we make the border pen twice as thick
painter.setClipPath(path); // and we clip the outer half of the border away

// now let's paint it
painter.drawPath(shape);
</code>```

I think this is probably not the most efficient way since clipping is probably quite expensive operation.

Isn't there any other more elegant way?

Body:
Simply put, when I draw a border of a certain shape using QPainter with a pen of width e.g. penWidth = 10.0 then one half of the border width is actually painted outside of the shape area and one half is drawn inside.

I would however like to paint a shape with a pen such that the border is only on the inside of the shape area.

I probably can use this trick: I set the pen's width twice as big and I also set the clip path so that the outer half of the border line is clipped away and only the inner half of the border line remains.

Example:

QColor penColor(Qt::red);
qreal penWidth = 5.0;
QPainterPath shape;
// ...here I define the shape

QPainter painter(device);

// the trick comes here
QPen p(penColor, penWidth * 2); // we make the border pen twice as thick
painter.setClipPath(path); // and we clip the outer half of the border away

// now let's paint it
painter.drawPath(shape);

I think this is probably not the most efficient way since clipping is probably quite expensive operation.

Isn't there any other more elegant way?


问:
Why doesn't this program prompt the user to enter the box name ? And what are the alternatives avaliable in this case?
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int id;
    char name[50];
}box;

void fill_boxes(box *boxes, int length)
{
    for (int i = 0; i < length; i++) {
        printf("Enter box %d id: ", i+1);
        scanf("%d",&boxes[i].id);

        printf("Enter box %d name: ", i+1);
        /* scanf("%s",boxes[i].name); */
        scanf("%[^\n]",boxes[i].name);

    }
}

void print_elements(box *boxes, int length)
{
    for (int i = 0; i < length; i++) {
        printf("\nbox %d \n\tid = %d\n\tname = %s",i+1,boxes[i].id, boxes[i].name);
    }
    printf("\n");
};

int main()
{
    box *boxes = malloc(2 * sizeof(box));
    fill_boxes(boxes, 2);
    print_elements(boxes, 2);
    free(boxes);

    return 0;
}
</code>```

I tried using scanf("%s",boxes[i].name) but it only accepts one word
and using fgets does not solve the problem either.
Actually it's a recurrent problem with my c programs so I'm surely missing some theory !

Body:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int id;
    char name[50];
}box;

void fill_boxes(box *boxes, int length)
{
    for (int i = 0; i < length; i++) {
        printf("Enter box %d id: ", i+1);
        scanf("%d",&boxes[i].id);

        printf("Enter box %d name: ", i+1);
        /* scanf("%s",boxes[i].name); */
        scanf("%[^\n]",boxes[i].name);

    }
}

void print_elements(box *boxes, int length)
{
    for (int i = 0; i < length; i++) {
        printf("\nbox %d \n\tid = %d\n\tname = %s",i+1,boxes[i].id, boxes[i].name);
    }
    printf("\n");
};

int main()
{
    box *boxes = malloc(2 * sizeof(box));
    fill_boxes(boxes, 2);
    print_elements(boxes, 2);
    free(boxes);

    return 0;
}

I tried using scanf("%s",boxes[i].name) but it only accepts one word
and using fgets does not solve the problem either.
Actually it's a recurrent problem with my c programs so I'm surely missing some theory !


问:
Spring Boot Yelp Fusion Api returning empty array from Business Search endpoint
I am trying to fetch from the Yelp Fusion api with a small Spring Boot backend, however I am not actually gettting anything back in the response and can't find any information about the issue.

I have set up a fetch using a rest endpoint that I made to consume the yelp api and return the response to my frontend. I've tried messing with the searc parameters but not luck. I am expecting a simple response of 20 businesses within the set location.

YelpService:

```<code>package hangrydevelopment.hangrybackend.services;

//import hangrydevelopment.hangrybackend.models.Restaurant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping(value = "/api/yelpFetch", produces = "application/json")
public class YelpService {

    @GetMapping("/{location}")
    public ResponseEntity<String> getRestaurants(@PathVariable String location) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer YELP-API-KEY");
        headers.add("accept", "application/json");
        String url = "https://api.yelp.com/v3/businesses/search?location=" + location + "&term=fast%20food&radius=40000&categories=Fast%20food&open_now=true&sort_by=best_match&matches_party_size_param=true&limit=20";
        HttpEntity<Object> entity = new HttpEntity<Object>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        System.out.println(response);
        return response;
    }
}

</code>```

Response:

<200,{"businesses": [], "total": 0, "region": {"center": {"longitude": -98.39630126953125, "latitude": 29.489805702433365}}},[Connection:"keep-alive", Content-Length:"119", content-type:"application/json", server:"envoy", x-zipkin-id:"500a9a12e3391cda", x-b3-sampled:"0", ratelimit-dailylimit:"5000", ratelimit-remaining:"4980", x-routing-service:"routing-main--useast1-64bdc8b4bb-kdhkg; site=public_api_v3", ratelimit-resettime:"2022-12-13T00:00:00+00:00", x-cloudmap:"routing_useast1", x-mode:"ro", x-proxied:"10-65-175-143-useast1bprod", x-extlb:"10-65-175-143-useast1bprod", cache-control:"max-age=0, no-store, private, no-transform", Accept-Ranges:"bytes", Date:"Mon, 12 Dec 2022 22:57:49 GMT", Via:"1.1 varnish", X-Served-By:"cache-iah17260-IAH", X-Cache:"MISS", X-Cache-Hits:"0"]>

Body:
I am trying to fetch from the Yelp Fusion api with a small Spring Boot backend, however I am not actually gettting anything back in the response and can't find any information about the issue.

I have set up a fetch using a rest endpoint that I made to consume the yelp api and return the response to my frontend. I've tried messing with the searc parameters but not luck. I am expecting a simple response of 20 businesses within the set location.

YelpService:

package hangrydevelopment.hangrybackend.services;

//import hangrydevelopment.hangrybackend.models.Restaurant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping(value = "/api/yelpFetch", produces = "application/json")
public class YelpService {

    @GetMapping("/{location}")
    public ResponseEntity<String> getRestaurants(@PathVariable String location) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer YELP-API-KEY");
        headers.add("accept", "application/json");
        String url = "https://api.yelp.com/v3/businesses/search?location=" + location + "&term=fast%20food&radius=40000&categories=Fast%20food&open_now=true&sort_by=best_match&matches_party_size_param=true&limit=20";
        HttpEntity<Object> entity = new HttpEntity<Object>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        System.out.println(response);
        return response;
    }
}

Response:

<200,{"businesses": [], "total": 0, "region": {"center": {"longitude": -98.39630126953125, "latitude": 29.489805702433365}}},[Connection:"keep-alive", Content-Length:"119", content-type:"application/json", server:"envoy", x-zipkin-id:"500a9a12e3391cda", x-b3-sampled:"0", ratelimit-dailylimit:"5000", ratelimit-remaining:"4980", x-routing-service:"routing-main--useast1-64bdc8b4bb-kdhkg; site=public_api_v3", ratelimit-resettime:"2022-12-13T00:00:00+00:00", x-cloudmap:"routing_useast1", x-mode:"ro", x-proxied:"10-65-175-143-useast1bprod", x-extlb:"10-65-175-143-useast1bprod", cache-control:"max-age=0, no-store, private, no-transform", Accept-Ranges:"bytes", Date:"Mon, 12 Dec 2022 22:57:49 GMT", Via:"1.1 varnish", X-Served-By:"cache-iah17260-IAH", X-Cache:"MISS", X-Cache-Hits:"0"]>


问:
Logging to the very same mlflow run across multiple scripts
I have separate preprocessing and training Python scripts. I would like to track my experiments using mlflow.

Because my scripts are separate, I am using a Powershell script (think of it as a shell script, but on Windows) to trigger the Python scripts with the same configuration and to make sure that all the scripts operate with the same parameters and data.

How can I track across scripts into the same mlflow run?

I am passing the same experiment name to the scripts. To make sure the same run is picked up, I thought to generate a (16 bit hex) run ID in my Powershell script and pass it to all the Python scripts.

This doesn't work as when a run ID is given to mlflow_start_run(), mlflow expects that run ID to already exist and it fails with mlflow.exceptions.MlflowException: Run 'dfa31595f0b84a1e0d1343eedc81ee75' not found.

If I pass a run name, each of the scripts gets logged to a different run anyways (which is expected).

I cannot use mlflow.last_active_run() in subsequent scripts, because I need to preserve the ability to run and track/log each script separately.


问:
how to use "for" with two variables
I have two files with different information that I want to execute simultaneously each line of both files in a loop until it finishes, but the "name" is stuck in the first lines and the "id" executes normally.

```<code>def get_data(account_id,key):
    name_entity = open('C:/Graphiql/Alerts/Update Alerts Policy/map/name','r')
    id_alerts = open('C:/Graphiql/Alerts/Update Alerts Policy/map/id_alerts','r')

    for entity in name_entity:
        name = entity.strip('\n')
        for alerts in id_alerts:
            id = alerts.strip('\n')
            endpoint = "https://api.newrelic.com/graphql"
            head = {"Content-type": "application/json", 'api-Key': f'{key}'}
            payload = 'mutation {alertsNrqlConditionStaticUpdate(accountId: ' + str(account_id) + ', condition: {nrql: {query: "SELECT average(memoryFreeBytes) FROM SystemSample where hostname = \u0027' + str(name) + '\u0027"}}, id: ' + str(id) + ') {id}}'
</code>```

I've already changed the order and changed the functions but that doesn't work.

Title: how to use "for" with two variables

Body:
I have two files with different information that I want to execute simultaneously each line of both files in a loop until it finishes, but the "name" is stuck in the first lines and the "id" executes normally.

def get_data(account_id,key):
    name_entity = open('C:/Graphiql/Alerts/Update Alerts Policy/map/name','r')
    id_alerts = open('C:/Graphiql/Alerts/Update Alerts Policy/map/id_alerts','r')

    for entity in name_entity:
        name = entity.strip('\n')
        for alerts in id_alerts:
            id = alerts.strip('\n')
            endpoint = "https://api.newrelic.com/graphql"
            head = {"Content-type": "application/json", 'api-Key': f'{key}'}
            payload = 'mutation {alertsNrqlConditionStaticUpdate(accountId: ' + str(account_id) + ', condition: {nrql: {query: "SELECT average(memoryFreeBytes) FROM SystemSample where hostname = \u0027' + str(name) + '\u0027"}}, id: ' + str(id) + ') {id}}'

I've already changed the order and changed the functions but that doesn't work.


问:
Paho python client connection failure to HiveMQ with connection return code 7
I have been testing a python client (Paho) with my local MQTT server (windows 10). It is working fine with passwords and TLS as well.

My Paho python client successfully connects to HiveMQ public mosquito broker using port 1883 without any issues as well!

But when I tried to connect to my hiveMQ cloud broker using port 8883, it fails to connect to the broker with return code 7. According to my understanding MQTT Connection Return Codes are only defined up to 5, can someone explain what causes this error?

I successfully connected to the cloud broker using my Linux mosquito broker using the following command

```<code>mosquitto_sub -h f86f3a7384644b569094607fbe400e2e.s2.eu.hivemq.cloud -p 8883 -u manoj2 -P my_PASSWORD -t my/test/topic
</code>```

But when I tried the same command on the windows 10 mosquito broker it returns the following error

```<code>Error: protocol error
</code>```

Appreciate your help!

Body:
I have been testing a python client (Paho) with my local MQTT server (windows 10). It is working fine with passwords and TLS as well.

My Paho python client successfully connects to HiveMQ public mosquito broker using port 1883 without any issues as well!

But when I tried to connect to my hiveMQ cloud broker using port 8883, it fails to connect to the broker with return code 7. According to my understanding MQTT Connection Return Codes are only defined up to 5, can someone explain what causes this error?

I successfully connected to the cloud broker using my Linux mosquito broker using the following command

mosquitto_sub -h f86f3a7384644b569094607fbe400e2e.s2.eu.hivemq.cloud -p 8883 -u manoj2 -P my_PASSWORD -t my/test/topic

But when I tried the same command on the windows 10 mosquito broker it returns the following error

Error: protocol error

Appreciate your help!


问:
Javascript: mute/unmute button doesn't work TypeError: null is not an object
My site displays a video in autoplay (no controls) and I would like to have a button in a fixed position to mute/unmute the audio while scrolling the page.
I did it (as visible here by code snippet) but while here works on my site it doesn't (if I push the button nothing happens) and console displays this: " TypeError: null is not an object (evaluating 'video.muted') "

Why? Any suggestion to fix this problem?
I am a newbie in javascript.
Thank you in advance!

var video = document.getElementById("myVideo");
var btn = document.getElementById("myBtn");

function myFunction() {
    video.muted = !video.muted;
    btn.innerHTML = video.muted ? "Unmute":'Mute';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.video-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px auto 80px;
}

.video-description {
  text-align: center;
  max-width: 66%;
  margin: 0 auto 24px;
  font: inherit;
  letter-spacing: 4px;
}

#myVideo {
  border-radius: 5px;
  max-width: 46%;
  object-fit: cover;
}

#myBtn {
  top: 10%;
  right: 3%;
  position: fixed;
  z-index: 50;
  cursor: pointer;
  padding: 10px 20px;
  background: #D3D3D3;
  color: #000;
  border-radius: 5px;
  display: inline-block;
}</code>```

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  <video id="myVideo" autoplay loop>
    <source src="https://www.w3schools.com/tags/movie.mp4" type="video/mp4">
    Your browser does not support HTML5 video.
  </video>

    <button id="myBtn" onclick="myFunction()">Toggle Mute</button>

```

Body:
My site displays a video in autoplay (no controls) and I would like to have a button in a fixed position to mute/unmute the audio while scrolling the page.
I did it (as visible here by code snippet) but while here works on my site it doesn't (if I push the button nothing happens) and console displays this: " TypeError: null is not an object (evaluating 'video.muted') "

Why? Any suggestion to fix this problem?
I am a newbie in javascript.
Thank you in advance!

var video = document.getElementById("myVideo");
var btn = document.getElementById("myBtn");

function myFunction() {
    video.muted = !video.muted;
    btn.innerHTML = video.muted ? "Unmute":'Mute';
}

.video-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px auto 80px;
}

.video-description {
  text-align: center;
  max-width: 66%;
  margin: 0 auto 24px;
  font: inherit;
  letter-spacing: 4px;
}

#myVideo {
  border-radius: 5px;
  max-width: 46%;
  object-fit: cover;
}

#myBtn {
  top: 10%;
  right: 3%;
  position: fixed;
  z-index: 50;
  cursor: pointer;
  padding: 10px 20px;
  background: #D3D3D3;
  color: #000;
  border-radius: 5px;
  display: inline-block;
}

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  <video id="myVideo" autoplay loop>
    <source src="https://www.w3schools.com/tags/movie.mp4" type="video/mp4">
    Your browser does not support HTML5 video.
  </video>

    <button id="myBtn" onclick="myFunction()">Toggle Mute</button>


问:
Are POST requests with Content-Disposition header supported in Postman?
I did some research both in the Postman GUI (auto-completion for request headers which does not offer "Content-Disposition") and in learning.postman.com/docs and there is no mention of "Content-Disposition" request header.  I am using this request header in a POST request to upload a PDF file to an existing document.  The operation is successful.  But this is currently being done in a Jersey REST client Java project.  I'm trying to create a similar POST REST request in Postman as part of a test collection.

Any workaround for this or just not supported?  The "standard" multipart/form-data example cited everywhere and including Postman docs/examples is not supported by this upload POST API.

The Java/REST client code was based on this SO code: Upload file via streaming using Jersey 2 only difference in my client I am using "application/pdf" as MediaType.


问:
Internationalisation and Localisation with Ionic 6 and Angular 15 best practices
I'm trying to understand how to make an app created with Angular 15 and Ionic 6 ready for different countries (internationalisation and localisation).
There is a way to use the default Angular approach with Ionic? If it is so will I need to create different apps for the Stores, one for each supported locale-id?

I hope the question is clear, thanks in advance to whom will spend some time to help me.

Looking around I saw that Angular has its way to do it https://angular.io/guide/i18n-overview) but it seems that when the application is packed for the Apple or Google store it doesn't work very well. The other approach I've found is using a package ngx-translate (http://www.ngx-translate.com). In this approach it's not clear how to localise currencies and date time format for example.
I'd like to have the web application ready to be released in different countries. I'll start to publish the web app on a website and then I'd like to publish a version in the Apple and Google store without keeping different codebase.


问:
Additional input in the authorize modal with Swashbuckle.AspNetCore
How can I have an additional input (in this example tenant_hint) in the authorize modal that will behave as an oauth additional query string param like this:


问:
TypeError when using modin with pd.cut(df[column],300)
I first sub in Modin for Pandas for the benefit of distributed work over multiple cores:

```<code>import modin.pandas as pd
from modin.config import Engine
Engine.put("dask")
</code>```

After initializing my dataframe, I attempt to use:

```<code>
df['bins'] = pd.cut(df[column],300)
</code>```

I get this error:

```<code>TypeError: ('Could not serialize object of type function.', '<function PandasDataframe._build_mapreduce_func.<locals>._map_reduce_func at 0x7fbe78580680>')
</code>```

Would be glad to get help.

I can't seem to get Modin to perform the way that I want out of the box, the way I expected.

Body:
I first sub in Modin for Pandas for the benefit of distributed work over multiple cores:

import modin.pandas as pd
from modin.config import Engine
Engine.put("dask")

After initializing my dataframe, I attempt to use:

df['bins'] = pd.cut(df[column],300)

I get this error:

TypeError: ('Could not serialize object of type function.', '<function PandasDataframe._build_mapreduce_func.<locals>._map_reduce_func at 0x7fbe78580680>')

Would be glad to get help.

I can't seem to get Modin to perform the way that I want out of the box, the way I expected.


问:
How to safely (not to brake internal consistency of the repo) edit git config and refs manually (by text editor)?
Search found How can I edit the .git / config file from the git terminal?. The answer tells e.g. to use editor of choice to edit .git/config. I'm currently investigating IMO strange behavior of git in my repo and suspect my manual edit of .git/config might play a role.

As of now I see many files in .git are text files expect objects (which AFAIK are "actual work files", delta's of them). However there are binary index and sometimes packed-refs. I recall reading packed-refs is used to speed up search (How to unpack packed-refs?).

Say:

```<code>git branch --set-upstream-to=origin/test
error: the requested upstream branch 'origin/test' does not exist
</code>```

But I can just edit config replacing main with test in merge = refs/heads/main. Also replace URL of remote (that I did many times), replace commit hashes in refs, add refs and folders with refs (say copy refs/remotes from other repo), add lines to .git/config, literally write/add/delete anything that is valid git syntax.

Can any of the above break some internal git repo consistency? If yes, is there an easy way to update repo to consistent state honoring my edits?

Body:
Search found How can I edit the .git / config file from the git terminal?. The answer tells e.g. to use editor of choice to edit .git/config. I'm currently investigating IMO strange behavior of git in my repo and suspect my manual edit of .git/config might play a role.

As of now I see many files in .git are text files expect objects (which AFAIK are "actual work files", delta's of them). However there are binary index and sometimes packed-refs. I recall reading packed-refs is used to speed up search (How to unpack packed-refs?).

Say:

git branch --set-upstream-to=origin/test
error: the requested upstream branch 'origin/test' does not exist

But I can just edit config replacing main with test in merge = refs/heads/main. Also replace URL of remote (that I did many times), replace commit hashes in refs, add refs and folders with refs (say copy refs/remotes from other repo), add lines to .git/config, literally write/add/delete anything that is valid git syntax.

Can any of the above break some internal git repo consistency? If yes, is there an easy way to update repo to consistent state honoring my edits?