问:
Pyinstaller compiling is not working in Python
I am currently working on making a Python IDLE, I am giving an option to convert the python file to an executable file (.exe). But I get a Pyinstaller Error.

I imported:

import os
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkFont
from tkinter import filedialog
from tkinter import messagebox
```
<p>I defined the root variable. Below is a toplevel of the root.</p>
<p>I had tried:</p>
<pre class="lang-py prettyprint-override"><code>def compile2():
    def compile(event):
        realico = ico.get()
        l = " --icon=\"%s\"" % realico
        texta = "pyinstaller"
        if onefile:
            texta += " --onefile"
        if windowed:
            texta += " --windowed"
        texta += l
        texta += " " + file.name
        textb = texta
        print(texta)
        while True:
            if textb[-1] != "/":
                textb = textb[:-1]
            else:
                break
        i = 0
        while i != 41:
            i += 1
            textb = textb.replace(textb[0], '', 1)
        textb = str(textb)
        texta = rreplace(texta, textb, '', 1)
        os.system("cd %s" % textb)
        sure = messagebox.askyesno(title="Python Code Editor", message="This requires to download a Python Package to your computer.\nAre you sure?")
        if sure:
            os.system("pip install pyinstaller")
            messagebox.showinfo(title="Python Code Editor", message="The package has downloaded.")
            os.system(texta)
        else:
            messagebox.showinfo(title="Python Code Editor", message="The package did not download.")
    file = filedialog.askopenfile(defaultextension=".py", filetypes=[("Python Files", "*.py")])
    new = tk.Toplevel(root)
    ico = tk.StringVar()
    ft = tkFont.Font(family='Times',size=10)
    onefile = tk.Checkbutton(new, font=ft, fg="#333333", text="ONEFILE", offvalue="0", onvalue="1", command=toggle_onefile)
    windowed = tk.Checkbutton(new, font=ft, fg="#333333", text="WINDOWED", offvalue="0", onvalue="1", command=toggle_windowed)
    icon = tk.Entry(new, textvariable=ico)
    onefile.place(x=10,y=10,width=80,height=25)
    windowed.place(x=10,y=40,width=100,height=25)
    new.bind("<Return>", compile)
</code>```

I expected:

(compile2 function is called)
(Python Code Editor is title of root.)

|-Open---[X]
|          |
| Selected |
(Open is clicked)

|-Python Code Editor-------[-[]X]
|  [/]ONEFILE                   |
|  [/]WINDOWED                  |
|_______________________________
(Enter is pressed)

|-Python Code Editor--------------------[X]
| (?) This will install a python package. |
|     Are you sure?                       |
|              Yes / No                   |
|_________________________________________|
(Yes is clicked)

|-Python Code Editor--------------------[X]
| (I) The Python package has downloaded.  |
|                  OK                     |
|_________________________________________|
(OK is clicked)
(Console: )

(pyinstaller compiling)
```
<p>I got:</p>
<p>(compile2 function is called)
(Python Code Editor is title of root.)</p>
<pre class="lang-py prettyprint-override"><code>|-Open---[X]
|          |
| Selected |
(Open is clicked)

|-Python Code Editor-------[-[]X]
|  [/]ONEFILE                   |
|  [/]WINDOWED                  |
|_______________________________
(Enter is pressed)

|-Python Code Editor--------------------[X]
| (?) This will install a python package. |
|     Are you sure?                       |
|              Yes / No                   |
|_________________________________________|
(Yes is clicked)

|-Python Code Editor--------------------[X]
| (I) The Python package has downloaded.  |
|                  OK                     |
|_________________________________________|
(OK is clicked)
(Console: )

usage: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME] [--add-data <SRC;DEST or SRC:DEST>] [--add-binary <SRC;DEST or SRC:DEST>] [-p DIR] [--hidden-import MODULENAME] [--collect-submodules MODULENAME] [--collect-data MODULENAME]
                   [--collect-binaries MODULENAME] [--collect-all MODULENAME] [--copy-metadata PACKAGENAME] [--recursive-copy-metadata PACKAGENAME] [--additional-hooks-dir HOOKSPATH] [--runtime-hook RUNTIME_HOOKS] [--exclude-module EXCLUDES] [--key KEY]
                   [--splash IMAGE_FILE] [-d {all,imports,bootloader,noarchive}] [--python-option PYTHON_OPTION] [-s] [--noupx] [--upx-exclude FILE] [-c] [-w] [-i <FILE.ico or FILE.exe,ID or FILE.icns or Image or "NONE">] [--disable-windowed-traceback]
                   [--version-file FILE] [-m <FILE or XML>] [--no-embed-manifest] [-r RESOURCE] [--uac-admin] [--uac-uiaccess] [--win-private-assemblies] [--win-no-prefer-redirects] [--argv-emulation] [--osx-bundle-identifier BUNDLE_IDENTIFIER]
                   [--target-architecture ARCH] [--codesign-identity IDENTITY] [--osx-entitlements-file FILENAME] [--runtime-tmpdir PATH] [--bootloader-ignore-signals] [--distpath DIR] [--workpath WORKPATH] [-y] [--upx-dir UPX_DIR] [-a] [--clean]
                   [--log-level LEVEL]
                   scriptname [scriptname ...]
pyinstaller: error: the following arguments are required: scriptname

</code>```

Body:
I am currently working on making a Python IDLE, I am giving an option to convert the python file to an executable file (.exe). But I get a Pyinstaller Error.

I imported:

import os
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkFont
from tkinter import filedialog
from tkinter import messagebox

I defined the root variable. Below is a toplevel of the root.

I had tried:

def compile2():
    def compile(event):
        realico = ico.get()
        l = " --icon=\"%s\"" % realico
        texta = "pyinstaller"
        if onefile:
            texta += " --onefile"
        if windowed:
            texta += " --windowed"
        texta += l
        texta += " " + file.name
        textb = texta
        print(texta)
        while True:
            if textb[-1] != "/":
                textb = textb[:-1]
            else:
                break
        i = 0
        while i != 41:
            i += 1
            textb = textb.replace(textb[0], '', 1)
        textb = str(textb)
        texta = rreplace(texta, textb, '', 1)
        os.system("cd %s" % textb)
        sure = messagebox.askyesno(title="Python Code Editor", message="This requires to download a Python Package to your computer.\nAre you sure?")
        if sure:
            os.system("pip install pyinstaller")
            messagebox.showinfo(title="Python Code Editor", message="The package has downloaded.")
            os.system(texta)
        else:
            messagebox.showinfo(title="Python Code Editor", message="The package did not download.")
    file = filedialog.askopenfile(defaultextension=".py", filetypes=[("Python Files", "*.py")])
    new = tk.Toplevel(root)
    ico = tk.StringVar()
    ft = tkFont.Font(family='Times',size=10)
    onefile = tk.Checkbutton(new, font=ft, fg="#333333", text="ONEFILE", offvalue="0", onvalue="1", command=toggle_onefile)
    windowed = tk.Checkbutton(new, font=ft, fg="#333333", text="WINDOWED", offvalue="0", onvalue="1", command=toggle_windowed)
    icon = tk.Entry(new, textvariable=ico)
    onefile.place(x=10,y=10,width=80,height=25)
    windowed.place(x=10,y=40,width=100,height=25)
    new.bind("<Return>", compile)

I expected:

(compile2 function is called)
(Python Code Editor is title of root.)

|-Open---[X]
|          |
| Selected |
(Open is clicked)

|-Python Code Editor-------[-[]X]
|  [/]ONEFILE                   |
|  [/]WINDOWED                  |
|_______________________________
(Enter is pressed)

|-Python Code Editor--------------------[X]
| (?) This will install a python package. |
|     Are you sure?                       |
|              Yes / No                   |
|_________________________________________|
(Yes is clicked)

|-Python Code Editor--------------------[X]
| (I) The Python package has downloaded.  |
|                  OK                     |
|_________________________________________|
(OK is clicked)
(Console: )

(pyinstaller compiling)

I got:

(compile2 function is called)
(Python Code Editor is title of root.)

|-Open---[X]
|          |
| Selected |
(Open is clicked)

|-Python Code Editor-------[-[]X]
|  [/]ONEFILE                   |
|  [/]WINDOWED                  |
|_______________________________
(Enter is pressed)

|-Python Code Editor--------------------[X]
| (?) This will install a python package. |
|     Are you sure?                       |
|              Yes / No                   |
|_________________________________________|
(Yes is clicked)

|-Python Code Editor--------------------[X]
| (I) The Python package has downloaded.  |
|                  OK                     |
|_________________________________________|
(OK is clicked)
(Console: )

usage: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME] [--add-data <SRC;DEST or SRC:DEST>] [--add-binary <SRC;DEST or SRC:DEST>] [-p DIR] [--hidden-import MODULENAME] [--collect-submodules MODULENAME] [--collect-data MODULENAME]
                   [--collect-binaries MODULENAME] [--collect-all MODULENAME] [--copy-metadata PACKAGENAME] [--recursive-copy-metadata PACKAGENAME] [--additional-hooks-dir HOOKSPATH] [--runtime-hook RUNTIME_HOOKS] [--exclude-module EXCLUDES] [--key KEY]
                   [--splash IMAGE_FILE] [-d {all,imports,bootloader,noarchive}] [--python-option PYTHON_OPTION] [-s] [--noupx] [--upx-exclude FILE] [-c] [-w] [-i <FILE.ico or FILE.exe,ID or FILE.icns or Image or "NONE">] [--disable-windowed-traceback]
                   [--version-file FILE] [-m <FILE or XML>] [--no-embed-manifest] [-r RESOURCE] [--uac-admin] [--uac-uiaccess] [--win-private-assemblies] [--win-no-prefer-redirects] [--argv-emulation] [--osx-bundle-identifier BUNDLE_IDENTIFIER]
                   [--target-architecture ARCH] [--codesign-identity IDENTITY] [--osx-entitlements-file FILENAME] [--runtime-tmpdir PATH] [--bootloader-ignore-signals] [--distpath DIR] [--workpath WORKPATH] [-y] [--upx-dir UPX_DIR] [-a] [--clean]
                   [--log-level LEVEL]
                   scriptname [scriptname ...]
pyinstaller: error: the following arguments are required: scriptname


来源: stackexchange

问:
keytab not found when the keytab file name is passed via workflow.xml
I am trying to submit a spark application (written in java) through oozie on a secured Azure cluster. The workflow.xml has a shell action and inside that I give the bash script name, script path, the name of keytab file - xxx.keytab as the argument and the hdfs path of keytab file in the file tag. Inside the bash script I read the keytab file name as  The bash script is:

```<code>keyt=$1
spark-submit --master yarn --deploy-mode client --keytab $keyt --class myclass applicationxyz.jar
</code>```

But the yarn log says xxx.keytab not found.
However, if I directly specify the keytab file name in the bash script then the job gets submitted successfuly -

```<code>spark-submit --master yarn --deploy-mode client --keytab xxx.keytab --class myclass applicationxyz.jar
</code>```

Please explain the reason for this.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to submit a spark application (written in java) through oozie on a secured Azure cluster. The workflow.xml has a shell action and inside that I give the bash script name, script path, the name of keytab file - xxx.keytab as the argument and the hdfs path of keytab file in the file tag. Inside the bash script I read the keytab file name as  The bash script is:

keyt=$1
spark-submit --master yarn --deploy-mode client --keytab $keyt --class myclass applicationxyz.jar

But the yarn log says xxx.keytab not found.
However, if I directly specify the keytab file name in the bash script then the job gets submitted successfuly -

spark-submit --master yarn --deploy-mode client --keytab xxx.keytab --class myclass applicationxyz.jar

Please explain the reason for this.


问:
Exception "Cannot get a connection as the driver manager is not properly initialized" while connecting to MySQL from the Java hibernate application
I am trying to setup a third party Java hibernate application. Currently, I am experiencing the following exception. Could anyone help me with this?

```<code>java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized
        at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:172) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
</code>```

I have modified the hibernate config xml file with different options. But still facing the issue.
MySQL Version : 5
Config file looks like :

```<code><hibernate-configuration>
        <session-factory>

                <!-- Set URL -->
                <property name = "hibernate.connection.url">jdbc:mysql://localhost:3300/testdb1</property>

                <!-- Set User Name -->
                <property name = "hibernate.connection.username">testuser1</property>

                <!-- Set Password -->
                <property name = "hibernate.connection.password">testpassword</property>

                <!-- Set Driver Name -->
                <property name = "hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

                <property name = "hibernate.show_sql">true</property>

                <!-- property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property -->
                <property name= "hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

        </session-factory>
</hibernate-configuration>
</code>```

Body:
I am trying to setup a third party Java hibernate application. Currently, I am experiencing the following exception. Could anyone help me with this?

java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized
        at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:172) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]

I have modified the hibernate config xml file with different options. But still facing the issue.
MySQL Version : 5
Config file looks like :

<hibernate-configuration>
        <session-factory>

                <property name = "hibernate.connection.url">jdbc:mysql://localhost:3300/testdb1</property>

                <property name = "hibernate.connection.username">testuser1</property>

                <property name = "hibernate.connection.password">testpassword</property>

                <property name = "hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

                <property name = "hibernate.show_sql">true</property>

                <property name= "hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

        </session-factory>
</hibernate-configuration>


问:
Count the number of segments in audio file with python
I have the following audio file

When i plot it using the following code, i get this:

```<code>audio_data, sr = librosa.load('test.wav')
plt.plot(audio_data)
plt.show()
</code>```

Wave plot of audio

I am trying to get the number of segments in this audio. For this example, there are three dictinct segments.

Here is what I have tried so far:

I set a minimum of 0.

And then I have 2 pointers, i and j

I iterate through the data (with i) and if i see a difference of greater than 0.05, i set a variable called in_segment to true, and I start to iterate from that point onwards with j. If i see a difference less than 0.025, i stop, increment my segment count by 1, and then restart the process from that point

It didnt work, so I decided to get rid of the negative values in the array, but still not getting 3 as the output. I get 1620

Here is the code:

```<code>audio_data, sr = librosa.load(audio_data)
segments = 0
in_segment = False
end_segment = False

audio_data = audio_data[audio_data > 0]#np.abs(audio_data)
n = len(audio_data)
minimum = 0 #np.min(audio_data)

for i in range(n):
    diff = audio_data[i] - minimum
    if (diff > 0.05):
        in_segment = True
        for j in range(i, n):
            diff = audio_data[j] - minimum
            if (diff < 0.05 and in_segment):
                end_segment = True
                in_segment = False
                break

        if (end_segment):
            segments += 1
            end_segment = False
            i = j

print(segments)
</code>```

I expect to get 3 as the answer, but I am not sure how to fix this code. I suspect there are sudden spikes, which is whats causing the error. I also tried the abs values of the array, but did not work. Any one know how to fix this or a library that can count the rises in the data?

Body:
I have the following audio file

When i plot it using the following code, i get this:

audio_data, sr = librosa.load('test.wav')
plt.plot(audio_data)
plt.show()

Wave plot of audio

I am trying to get the number of segments in this audio. For this example, there are three dictinct segments.

Here is what I have tried so far:

I set a minimum of 0.

And then I have 2 pointers, i and j

I iterate through the data (with i) and if i see a difference of greater than 0.05, i set a variable called in_segment to true, and I start to iterate from that point onwards with j. If i see a difference less than 0.025, i stop, increment my segment count by 1, and then restart the process from that point

It didnt work, so I decided to get rid of the negative values in the array, but still not getting 3 as the output. I get 1620

Here is the code:

audio_data, sr = librosa.load(audio_data)
segments = 0
in_segment = False
end_segment = False

audio_data = audio_data[audio_data > 0]#np.abs(audio_data)
n = len(audio_data)
minimum = 0 #np.min(audio_data)

for i in range(n):
    diff = audio_data[i] - minimum
    if (diff > 0.05):
        in_segment = True
        for j in range(i, n):
            diff = audio_data[j] - minimum
            if (diff < 0.05 and in_segment):
                end_segment = True
                in_segment = False
                break

        if (end_segment):
            segments += 1
            end_segment = False
            i = j

print(segments)

I expect to get 3 as the answer, but I am not sure how to fix this code. I suspect there are sudden spikes, which is whats causing the error. I also tried the abs values of the array, but did not work. Any one know how to fix this or a library that can count the rises in the data?


问:
How to get google OAuth redirect URL in a json response instead of the redirection html page (Passport, NestJS)?
```<code>  @Get('/google/redirect')
  @Public()
  @UseGuards(AuthGuard('google'))
  googleAuth() {
    // auto redirect to google auth page beacause of the google auth guard
  }
</code>```

I want the redirection url from the google auth guard but it is returning the google auth html page. How can I intercept the redirection url and stop the redirection to an html page? I want this api to send a json response containing the redirection url.

Tried to intercept the http response to see if it contains any data related to redirection but no luck there.

Body:
  @Get('/google/redirect')
  @Public()
  @UseGuards(AuthGuard('google'))
  googleAuth() {
    // auto redirect to google auth page beacause of the google auth guard
  }

I want the redirection url from the google auth guard but it is returning the google auth html page. How can I intercept the redirection url and stop the redirection to an html page? I want this api to send a json response containing the redirection url.

Tried to intercept the http response to see if it contains any data related to redirection but no luck there.


Title: Take the average of each row of pandas dataframe

Body:
I want to take the average of each row of kirp_df, such that it returns the average for each row indices. My code returned NaN for each row despite removing NA.

kirp_df = df.loc[:, df.loc["subtype"] == "KIRP"][:-2].dropna()
kirp_df.mean(axis=1)

Traceback:

/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:1: FutureWarning: Dropping of nuisance columns in DataFrame reductions (with 'numeric_only=None') is deprecated; in a future version this will raise TypeError.  Select only valid columns before calling the reduction.
  """Entry point for launching an IPython kernel.
cg00000029   NaN
cg00000165   NaN
cg00000236   NaN
cg00000289   NaN
cg00000292   NaN
              ..
cg09560658   NaN
cg09560763   NaN
cg09560811   NaN
cg09560911   NaN
cg09560953   NaN
Length: 142513, dtype: float64

#####################################################
Data:

kirp_df.iloc[1:10,1:10].to_dict()

{'TCGA-2Z-A9J1-01A': {'cg00000165': 0.0807243779293262,
  'cg00000236': 0.867305510246114,
  'cg00000289': 0.70680600651273,
  'cg00000292': 0.217862460492399,
  'cg00000321': 0.169408257004071,
  'cg00000363': 0.173115013795265,
  'cg00000622': 0.0108902025634162,
  'cg00000658': 0.813866558997356,
  'cg00000721': 0.938576461648791},
 'TCGA-2Z-A9J2-01A': {'cg00000165': 0.437447195378987,
  'cg00000236': 0.898927359292032,
  'cg00000289': 0.758108726247342,
  'cg00000292': 0.868604834806246,
  'cg00000321': 0.577744851436078,
  'cg00000363': 0.567241575633452,
  'cg00000622': 0.0122683781097633,
  'cg00000658': 0.881366097769717,
  'cg00000721': 0.936584647488041},
 'TCGA-2Z-A9J3-01A': {'cg00000165': 0.0642332527783939,
  'cg00000236': 0.917290578229414,
  'cg00000289': 0.675537604266578,
  'cg00000292': 0.543087013952312,
  'cg00000321': 0.85044433769089,
  'cg00000363': 0.470810530680518,
  'cg00000622': 0.0125681212511168,
  'cg00000658': 0.870735609192125,
  'cg00000721': 0.956356142020249},
 'TCGA-2Z-A9J5-01A': {'cg00000165': 0.126118535539944,
  'cg00000236': 0.928017823091886,
  'cg00000289': 0.677846427070521,
  'cg00000292': 0.850473788130218,
  'cg00000321': 0.44473521937132,
  'cg00000363': 0.204529155293748,
  'cg00000622': 0.0122330126903632,
  'cg00000658': 0.906102120405464,
  'cg00000721': 0.938145301973259},
 'TCGA-2Z-A9J6-01A': {'cg00000165': 0.112151024422993,
  'cg00000236': 0.881981171862823,
  'cg00000289': 0.695606438687072,
  'cg00000292': 0.846718372472362,
  'cg00000321': 0.757733166615607,
  'cg00000363': 0.172813874013867,
  'cg00000622': 0.0124341091006015,
  'cg00000658': 0.875702288602203,
  'cg00000721': 0.949350493096875},
 'TCGA-2Z-A9J7-01A': {'cg00000165': 0.559088973726113,
  'cg00000236': 0.901815470518336,
  'cg00000289': 0.805920947304252,
  'cg00000292': 0.640825631457383,
  'cg00000321': 0.621308654785173,
  'cg00000363': 0.0722588860930127,
  'cg00000622': 0.0100408106849315,
  'cg00000658': 0.856460615834933,
  'cg00000721': 0.945808996938907},
 'TCGA-2Z-A9J8-01A': {'cg00000165': 0.0993225901397478,
  'cg00000236': 0.889537978677822,
  'cg00000289': 0.691597185851671,
  'cg00000292': 0.813122933295151,
  'cg00000321': 0.710712761159508,
  'cg00000363': 0.579117830986195,
  'cg00000622': 0.0145401029579807,
  'cg00000658': 0.833725365229449,
  'cg00000721': 0.930732020027994},
 'TCGA-2Z-A9J9-01A': {'cg00000165': 0.0871408483321741,
  'cg00000236': 0.879968490399937,
  'cg00000289': 0.549769911227498,
  'cg00000292': 0.283154379541085,
  'cg00000321': 0.48310833426734,
  'cg00000363': 0.0694935460463862,
  'cg00000622': 0.0126142511240202,
  'cg00000658': 0.885015967416138,
  'cg00000721': 0.933393915741336},
 'TCGA-2Z-A9JD-01A': {'cg00000165': 0.0954830889751504,
  'cg00000236': 0.877101253439035,
  'cg00000289': 0.700443114118019,
  'cg00000292': 0.645773476077286,
  'cg00000321': 0.446177255074733,
  'cg00000363': 0.389318735766059,
  'cg00000622': 0.0155373951272166,
  'cg00000658': 0.882984941909313,
  'cg00000721': 0.92890097781832}}

Example output:

cg00000165    0.184634
cg00000236    0.893550
cg00000289    0.695737
cg00000292    0.634403
cg00000321    0.562375
cg00000363    0.299855
cg00000622    0.012570
cg00000658    0.867329
cg00000721    0.939761


问:
how to access aws rds in eks in same vpc and subnet
I am working on importing data from rds using debezium cdc source connector from eks. rds and eks share same vpc and subnet.

And i added the eks security group to rds security group, but it was not connecting.

As a test, we added the IP of the pad to the RDS security group, but we confirmed that it works well.
Is there anything else that should be touched by eks iam or security group? eks security groups are both inbound and outbound open!


问:
ordered terms + selecting terms in tab_model
I have a MLM to report which i saved as .rds file and load. But i need to report only several coefficients and in a particular order.

I set my labels for coefficients:

```<code>coefs =c(
"mother_l1_recode1"=  "Northern European",
"mother_l1_recode2"=  "Southern European",
"mother_l1_recode3"=  "Eastern European",
"mother_l1_recode4"=  "Southwest and Central Asian",
"mother_l1_recode5"=  "Southern Asian",
"mother_l1_recode6"=  "Southeast Asian",
"mother_l1_recode7"=  "Eastern Asian",
"mother_l1_recode9"=  "Other",
"mother_l1_recodenot_provided"=  "Not provided",
"mother_dummy_12011"=  "Non English"
)
</code>```

And included the list of terms as terms in the order I need them, but eventually, the print does not come in this order. How can I fix this?

```<code>tab_model(mlm1, mlm1_non1201,
          title=" ",
          pred.labels=coefs,

        terms = c(
          "mother_l1_recode1",
          "mother_l1_recode2",
          "mother_l1_recode3",
          "mother_l1_recode4",
          "mother_l1_recode5",
          "mother_l1_recode6",
          "mother_l1_recode7",
          "mother_l1_recode9",
          "mother_l1_recodenot_provided"
        ),
          show.intercept = FALSE,
          show.ci=FALSE,
          show.se = TRUE,
          string.se = "S.E.",
          dv.labels = c(
            paste("Year", parse_number(Year_Level_2_use), sep=" "),
            paste("Year", parse_number(Year_Level_2_use)+4, sep=" ")
          ),
          string.pred = as.character(year),
          string.est = "Coefficient",
          p.style="stars",
        show.icc = FALSE,
      show.re.var = FALSE,
      show.obs = FALSE,
      show.r2 =FALSE,
      show.ngroups = FALSE,
          auto.label = TRUE)
</code>```

Body:
I have a MLM to report which i saved as .rds file and load. But i need to report only several coefficients and in a particular order.

I set my labels for coefficients:

coefs =c(
"mother_l1_recode1"=  "Northern European",
"mother_l1_recode2"=  "Southern European",
"mother_l1_recode3"=  "Eastern European",
"mother_l1_recode4"=  "Southwest and Central Asian",
"mother_l1_recode5"=  "Southern Asian",
"mother_l1_recode6"=  "Southeast Asian",
"mother_l1_recode7"=  "Eastern Asian",
"mother_l1_recode9"=  "Other",
"mother_l1_recodenot_provided"=  "Not provided",
"mother_dummy_12011"=  "Non English"
)

And included the list of terms as terms in the order I need them, but eventually, the print does not come in this order. How can I fix this?

tab_model(mlm1, mlm1_non1201,
          title=" ",
          pred.labels=coefs,

        terms = c(
          "mother_l1_recode1",
          "mother_l1_recode2",
          "mother_l1_recode3",
          "mother_l1_recode4",
          "mother_l1_recode5",
          "mother_l1_recode6",
          "mother_l1_recode7",
          "mother_l1_recode9",
          "mother_l1_recodenot_provided"
        ),
          show.intercept = FALSE,
          show.ci=FALSE,
          show.se = TRUE,
          string.se = "S.E.",
          dv.labels = c(
            paste("Year", parse_number(Year_Level_2_use), sep=" "),
            paste("Year", parse_number(Year_Level_2_use)+4, sep=" ")
          ),
          string.pred = as.character(year),
          string.est = "Coefficient",
          p.style="stars",
        show.icc = FALSE,
      show.re.var = FALSE,
      show.obs = FALSE,
      show.r2 =FALSE,
      show.ngroups = FALSE,
          auto.label = TRUE)


问:
Eureka client not registering to server in docker spring boot
The eureka server and client is working if i run locally but with docker compose i am getting error Connection Refused. Below are the configuration which i am using.

Eureka server property file (Discovery Service):

```<code>spring.application.name=eureka-server
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
</code>```

Eureka client property file (Gateway service)

```<code>server.port=8762
spring.application.name=gateway-service
#tried eureka.client.service-url.default-zone with localhost and hostip as well (Not working)
eureka.client.serviceUrl.defaultZone=http://sm-discovery:8761/eureka
</code>```

Docker file of Eureka Server (Discovery Service)

```<code>From tomcat:9.0.48-jdk11-openjdk-slim
RUN rm -rf /usr/local/tomcat/webapps/*
COPY ./target/discovery-service.war /usr/local/tomcat/webapps/ROOT.war
CMD ["catalina.sh","run"]
</code>```

Docker file of Eureka Client (Gateway Service)

```<code>From tomcat:9.0.48-jdk11-openjdk-slim
RUN rm -rf /usr/local/tomcat/webapps/*
COPY ./target/discovery-service.war /usr/local/tomcat/webapps/ROOT.war
CMD ["catalina.sh","run"]
</code>```

docker-compose.yml file

```<code>version: "3"
services:
  sm-discovery:
    image: sm-discovery
    container_name: sm-discovery
    build: ./discovery-service
    ports:
      - "8761:8080"
    restart: always
  sm-gateway:
    image: sm-gateway
    container_name: sm-gateway
    build: ./gateway-service
    ports:
      - "8762:8080"
    restart: always
    depends_on:
      - sm-discovery
</code>```

When i build and run docker compose, i am getting following error in eureka client:

```<code>Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://sm-discovery:8761/eureka/}, exception=I/O error on POST request for "http://sm-discovery:8761/eureka/apps/GATEWAY-SERVICE": Connect to sm-discovery:8761 [sm-discovery/172.29.0.2] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to sm-discovery:8761 [sm-discovery/172.29.0.2] failed: Connection refused (Connection refused) stacktrace=org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://sm-discovery:8761/eureka/apps/GATEWAY-SERVICE": Connect to sm-discovery:8761 [sm-discovery/172.29.0.2] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to sm-discovery:8761 [sm-discovery/172.29.0.2] failed: Connection refused (Connection refused)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
</code>```

Docker network inspect:

```<code>[
    {
        "Name": "social-media_default",
        "Id": "0513ee1d4b80f21723e772f7eb3a100d9d78f3cb2a7a10a0f78bf5eb57ec4c6a",
        "Created": "2022-12-27T10:32:37.9902248Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.29.0.0/16",
                    "Gateway": "172.29.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "43f35536a4cb8470b8a3278de9a62bc26284be9955409b83fba6c2d210995d42": {
                "Name": "sm-discovery",
                "EndpointID": "4babebdfadcf8a233e21ae87eea6d38ac22b0a75231505846eac97331127e24c",
                "MacAddress": "02:42:ac:1d:00:02",
                "IPv4Address": "172.29.0.2/16",
                "IPv6Address": ""
            },
            "634c47e82d3c9d2dd85c9e23830a3bc579a874171dcb021a44d78041adb17fab": {
                "Name": "sm-gateway",
                "EndpointID": "3b2b128b8cd11b713cc0d19d5187bdf0d7503eeff03389449a3094ff221f1366",
                "MacAddress": "02:42:ac:1d:00:03",
                "IPv4Address": "172.29.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "default",
            "com.docker.compose.project": "social-media",
            "com.docker.compose.version": "2.12.1"
        }
    }
]
</code>```

I have checked many solutions in stackoverflow but none worked. Can someone please let me know what is the error here ?

Body:
The eureka server and client is working if i run locally but with docker compose i am getting error Connection Refused. Below are the configuration which i am using.

Eureka server property file (Discovery Service):

spring.application.name=eureka-server
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

Eureka client property file (Gateway service)

server.port=8762
spring.application.name=gateway-service
#tried eureka.client.service-url.default-zone with localhost and hostip as well (Not working)
eureka.client.serviceUrl.defaultZone=http://sm-discovery:8761/eureka

Docker file of Eureka Server (Discovery Service)

From tomcat:9.0.48-jdk11-openjdk-slim
RUN rm -rf /usr/local/tomcat/webapps/*
COPY ./target/discovery-service.war /usr/local/tomcat/webapps/ROOT.war
CMD ["catalina.sh","run"]

Docker file of Eureka Client (Gateway Service)

From tomcat:9.0.48-jdk11-openjdk-slim
RUN rm -rf /usr/local/tomcat/webapps/*
COPY ./target/discovery-service.war /usr/local/tomcat/webapps/ROOT.war
CMD ["catalina.sh","run"]

docker-compose.yml file

version: "3"
services:
  sm-discovery:
    image: sm-discovery
    container_name: sm-discovery
    build: ./discovery-service
    ports:
      - "8761:8080"
    restart: always
  sm-gateway:
    image: sm-gateway
    container_name: sm-gateway
    build: ./gateway-service
    ports:
      - "8762:8080"
    restart: always
    depends_on:
      - sm-discovery

When i build and run docker compose, i am getting following error in eureka client:

Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://sm-discovery:8761/eureka/}, exception=I/O error on POST request for "http://sm-discovery:8761/eureka/apps/GATEWAY-SERVICE": Connect to sm-discovery:8761 [sm-discovery/172.29.0.2] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to sm-discovery:8761 [sm-discovery/172.29.0.2] failed: Connection refused (Connection refused) stacktrace=org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://sm-discovery:8761/eureka/apps/GATEWAY-SERVICE": Connect to sm-discovery:8761 [sm-discovery/172.29.0.2] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to sm-discovery:8761 [sm-discovery/172.29.0.2] failed: Connection refused (Connection refused)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)

Docker network inspect:

[
    {
        "Name": "social-media_default",
        "Id": "0513ee1d4b80f21723e772f7eb3a100d9d78f3cb2a7a10a0f78bf5eb57ec4c6a",
        "Created": "2022-12-27T10:32:37.9902248Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.29.0.0/16",
                    "Gateway": "172.29.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "43f35536a4cb8470b8a3278de9a62bc26284be9955409b83fba6c2d210995d42": {
                "Name": "sm-discovery",
                "EndpointID": "4babebdfadcf8a233e21ae87eea6d38ac22b0a75231505846eac97331127e24c",
                "MacAddress": "02:42:ac:1d:00:02",
                "IPv4Address": "172.29.0.2/16",
                "IPv6Address": ""
            },
            "634c47e82d3c9d2dd85c9e23830a3bc579a874171dcb021a44d78041adb17fab": {
                "Name": "sm-gateway",
                "EndpointID": "3b2b128b8cd11b713cc0d19d5187bdf0d7503eeff03389449a3094ff221f1366",
                "MacAddress": "02:42:ac:1d:00:03",
                "IPv4Address": "172.29.0.3/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "default",
            "com.docker.compose.project": "social-media",
            "com.docker.compose.version": "2.12.1"
        }
    }
]

I have checked many solutions in stackoverflow but none worked. Can someone please let me know what is the error here ?


问:
How do we create a Cloud Run instance, Dataflow pipeline in GCP using Ansible
Is there a way to create managed services(Cloud Run, Dataflow, Workflows), network components(Subnets, VPC Service Controls) in GCP using Ansible? Ansible Community link for GCP do not have any plugins for these services. (https://docs.ansible.com/ansible/latest/collections/google/cloud/)

Is it a good idea to develop custom plugins for these services(Cloud Run, Dataflow, Workflows)?  Any other approach to handle this only through Ansible.

We can create the managed services(Cloud Run, Dataflow, Workflows), network components with Terraform. Can use Cloud Build to build/ deploy managed services(Cloud Run, Dataflow, Workflows). But I want to achieve this through Ansible.


问:
How to resolve Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import './foo/' is not supported resolving ES modules imported from ./foo/host/build.js?
Here is the sequence of errors I am getting.

First, I am in a Node.js/TypeScript project and had this in my tsconfig.json:

```<code>"compilerOptions": {
  "module": "commonjs"
}
</code>```

My ~200 file Node.js/TypeScript project worked fine so far as CommonJS (which I realize is probably out of date now). I compile with tsc && tsc-alias (TypeScript compiler and tsc-alias is for resolving path aliases) into the ./host directory, with the file I'm running in host/build.js.

Then I do import chalk from 'chalk' in some file, after npm installing chalk, and get this error:

```<code>const chalk_1 = __importDefault(require("chalk"));
                                ^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/lancepollard/start/drumwork/deck/base.link/node_modules/chalk/source/index.js from /Users/lancepollard/start/drumwork/deck/base.link/host/builder/error.js not supported.
Instead change the require of index.js in /Users/lancepollard/start/drumwork/deck/base.link/host/builder/error.js to a dynamic import() which is available in all CommonJS modules.
</code>```

How do I resolve that error?

So I try resolving it by changing my tsconfig.json to be ES6:

```<code>{
  "compilerOptions": {
    "module": "ES6",
    "target": "es2020",
    "lib": ["es2020"],
    "outDir": "host",
    "rootDir": "make",
    "sourceMap": true,
    "strictNullChecks": true,
    "strict": true,
    "esModuleInterop": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": "./make",
    "paths": {
      "~": ["."]
    },
    "noImplicitAny": true
  },
  "include": ["make"],
  "exclude": ["node_modules"]
}
</code>```

And add this to my package.json:

```<code>"type": "module"
</code>```

That gives me this error:

```<code>$ node host/build
node:internal/process/esm_loader:108
    internalBinding('errors').triggerUncaughtException(
                              ^
Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/Users/lancepollard/start/drumwork/deck/base.link/host/' is not supported resolving ES modules imported from /Users/lancepollard/start/drumwork/deck/base.link/host/build.js
Did you mean to import ../index.js?
    at new NodeError (node:internal/errors:393:5)
    at finalizeResolution (node:internal/modules/esm/resolve:253:17)
    at moduleResolve (node:internal/modules/esm/resolve:876:10)
    at defaultResolve (node:internal/modules/esm/resolve:1084:11)
    at nextResolve (node:internal/modules/esm/loader:161:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:831:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:413:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36) {
  code: 'ERR_UNSUPPORTED_DIR_IMPORT',
  url: 'file:///Users/lancepollard/start/drumwork/deck/base.link/host/'
}
</code>```

The original source for build.ts (which gets compiled to host/build.js) is this:

```<code>import { api } from '~'

const link = api.findPath('@treesurf/wolf')
api.assertString(link)
const base = api.createBase()
api.setEnvironmentVariable(base, 'dock', 'javascript')
api.setEnvironmentVariable(base, 'site', 'test')
api.handle_deckCard(base, link)
</code>```

Where ~ resolves to the base folder/index of the project.

How do I get chalk to compile for my project, either by updating to ES6 or by doing "dynamic imports"? I would prefer to use the latest, whether that is commonjs or ES6.

Body:
Here is the sequence of errors I am getting.

First, I am in a Node.js/TypeScript project and had this in my tsconfig.json:

"compilerOptions": {
  "module": "commonjs"
}

My ~200 file Node.js/TypeScript project worked fine so far as CommonJS (which I realize is probably out of date now). I compile with tsc && tsc-alias (TypeScript compiler and tsc-alias is for resolving path aliases) into the ./host directory, with the file I'm running in host/build.js.

Then I do import chalk from 'chalk' in some file, after npm installing chalk, and get this error:

const chalk_1 = __importDefault(require("chalk"));
                                ^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/lancepollard/start/drumwork/deck/base.link/node_modules/chalk/source/index.js from /Users/lancepollard/start/drumwork/deck/base.link/host/builder/error.js not supported.
Instead change the require of index.js in /Users/lancepollard/start/drumwork/deck/base.link/host/builder/error.js to a dynamic import() which is available in all CommonJS modules.

How do I resolve that error?

So I try resolving it by changing my tsconfig.json to be ES6:

{
  "compilerOptions": {
    "module": "ES6",
    "target": "es2020",
    "lib": ["es2020"],
    "outDir": "host",
    "rootDir": "make",
    "sourceMap": true,
    "strictNullChecks": true,
    "strict": true,
    "esModuleInterop": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": "./make",
    "paths": {
      "~": ["."]
    },
    "noImplicitAny": true
  },
  "include": ["make"],
  "exclude": ["node_modules"]
}

And add this to my package.json:

"type": "module"

That gives me this error:

$ node host/build
node:internal/process/esm_loader:108
    internalBinding('errors').triggerUncaughtException(
                              ^
Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/Users/lancepollard/start/drumwork/deck/base.link/host/' is not supported resolving ES modules imported from /Users/lancepollard/start/drumwork/deck/base.link/host/build.js
Did you mean to import ../index.js?
    at new NodeError (node:internal/errors:393:5)
    at finalizeResolution (node:internal/modules/esm/resolve:253:17)
    at moduleResolve (node:internal/modules/esm/resolve:876:10)
    at defaultResolve (node:internal/modules/esm/resolve:1084:11)
    at nextResolve (node:internal/modules/esm/loader:161:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:831:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:413:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36) {
  code: 'ERR_UNSUPPORTED_DIR_IMPORT',
  url: 'file:///Users/lancepollard/start/drumwork/deck/base.link/host/'
}

The original source for build.ts (which gets compiled to host/build.js) is this:

import { api } from '~'

const link = api.findPath('@treesurf/wolf')
api.assertString(link)
const base = api.createBase()
api.setEnvironmentVariable(base, 'dock', 'javascript')
api.setEnvironmentVariable(base, 'site', 'test')
api.handle_deckCard(base, link)

Where ~ resolves to the base folder/index of the project.

How do I get chalk to compile for my project, either by updating to ES6 or by doing "dynamic imports"? I would prefer to use the latest, whether that is commonjs or ES6.


问:
flutter : Unhandled Exception: PlatformException(error, MediaSource
suddenly this error is coming,
I am using better_player plugin, before today it was working fine,
I don't know what is problem?</p>
```<code>[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: PlatformException(error, MediaSource.Factory#setDrmSessionManagerProvider no longer handles null by instantiating a new DefaultDrmSessionManagerProvider. Explicitly construct and pass an instance in order to retain the old behavior., null, java.lang.NullPointerException: MediaSource.Factory#setDrmSessionManagerProvider no longer handles null by instantiating a new DefaultDrmSessionManagerProvider. Explicitly construct and pass an instance in order to retain the old behavior.
E/flutter (16072):  at b9.a.f()
E/flutter (16072):  at e8.j0$b.d()
E/flutter (16072):  at com.jhomlala.better_player.a.p()
E/flutter (16072):  at com.jhomlala.better_player.a.H()
E/flutter (16072):  at cd.g.t()
E/flutter (16072):  at cd.g.q()
E/flutter (16072):  at cd.g.f()
E/flutter (16072):  at te.k$a.a()
E/flutter (16072):  at ge.c.l()
E/flutter (16072):  at ge.c.m()
E/flutter (16072):  at ge.c.i()
E/flutter (16072):  at ge.b.run()
E/flutter (16072):  at android.os.Handler.handleCallback(Handler.java:754)
E/flutter (16072):  at android.os.Handler.dispatchMessage(Handler.java:95)
E/flutter (16072):  at android.os.Looper.loop(Looper.java:163)
E/flutter (16072):  at android.app.ActivityThread.main(ActivityThread.java:6238)
E/flutter (16072):  at java.lang.reflect.Method.invoke(Native Method)
E/flutter (16072):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
E/flutter (16072):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
E/flutter (16072): )
E/flutter (16072): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607)
E/flutter (16072): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072): #2      MethodChannelVideoPlayer.setDataSource (package:better_player/src/video_player/method_channel_video_player.dart:118)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072): #3      VideoPlayerController._setDataSource (package:better_player/src/video_player/video_player.dart:408)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072): #4      BetterPlayerController._setupDataSource (package:better_player/src/core/better_player_controller.dart:444)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072): #5      BetterPlayerController.setupDataSource (package:better_player/src/core/better_player_controller.dart:274)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072):

</code>```

Body:
suddenly this error is coming,
I am using better_player plugin, before today it was working fine,
I don't know what is problem?

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: PlatformException(error, MediaSource.Factory#setDrmSessionManagerProvider no longer handles null by instantiating a new DefaultDrmSessionManagerProvider. Explicitly construct and pass an instance in order to retain the old behavior., null, java.lang.NullPointerException: MediaSource.Factory#setDrmSessionManagerProvider no longer handles null by instantiating a new DefaultDrmSessionManagerProvider. Explicitly construct and pass an instance in order to retain the old behavior.
E/flutter (16072):  at b9.a.f()
E/flutter (16072):  at e8.j0$b.d()
E/flutter (16072):  at com.jhomlala.better_player.a.p()
E/flutter (16072):  at com.jhomlala.better_player.a.H()
E/flutter (16072):  at cd.g.t()
E/flutter (16072):  at cd.g.q()
E/flutter (16072):  at cd.g.f()
E/flutter (16072):  at te.k$a.a()
E/flutter (16072):  at ge.c.l()
E/flutter (16072):  at ge.c.m()
E/flutter (16072):  at ge.c.i()
E/flutter (16072):  at ge.b.run()
E/flutter (16072):  at android.os.Handler.handleCallback(Handler.java:754)
E/flutter (16072):  at android.os.Handler.dispatchMessage(Handler.java:95)
E/flutter (16072):  at android.os.Looper.loop(Looper.java:163)
E/flutter (16072):  at android.app.ActivityThread.main(ActivityThread.java:6238)
E/flutter (16072):  at java.lang.reflect.Method.invoke(Native Method)
E/flutter (16072):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
E/flutter (16072):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
E/flutter (16072): )
E/flutter (16072): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607)
E/flutter (16072): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072): #2      MethodChannelVideoPlayer.setDataSource (package:better_player/src/video_player/method_channel_video_player.dart:118)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072): #3      VideoPlayerController._setDataSource (package:better_player/src/video_player/video_player.dart:408)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072): #4      BetterPlayerController._setupDataSource (package:better_player/src/core/better_player_controller.dart:444)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072): #5      BetterPlayerController.setupDataSource (package:better_player/src/core/better_player_controller.dart:274)
E/flutter (16072): <asynchronous suspension>
E/flutter (16072):


问:
How to make popup window fullscreen in Ubuntu microsoft edge broswer?

I am struggling to make popup window with fullscreen mode in ubuntu edge broswer.

I already have searched a lot however the methods I only found are applicable in Window environment like adding "--kiosk www.top-password.com --edge-kiosk-type=fullscreen" to properties.

Does anyone know how to make popup window fullscreen mode especially in Ubuntu edge broswer..?

It doesn't matter what browser it is!!

I share my source code that I tried but didn't work in Chrome, Firefox, Edge as below.

```<code>function popOpen(){
   pop=window.open('https://htmlcodex.com/demo/? item=2463','title','height=' + screen.height + ',width=' + screen.width + 'fullscreen=yes, location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1');
}
</code>```

Thanks in advance!!

Body:
I am struggling to make popup window with fullscreen mode in ubuntu edge broswer.

I already have searched a lot however the methods I only found are applicable in Window environment like adding "--kiosk www.top-password.com --edge-kiosk-type=fullscreen" to properties.

Does anyone know how to make popup window fullscreen mode especially in Ubuntu edge broswer..?

It doesn't matter what browser it is!!

I share my source code that I tried but didn't work in Chrome, Firefox, Edge as below.

function popOpen(){
   pop=window.open('https://htmlcodex.com/demo/? item=2463','title','height=' + screen.height + ',width=' + screen.width + 'fullscreen=yes, location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1');
}

Thanks in advance!!


问:
How to get reference of a nested collection of firebase in Angular
I've a simple collection in firebase and I done this to get the data:

```<code>getBusinessRecords(): Observable<businessData[]> {
    let businessRecords = collection(this.fs, 'businesses');
    return collectionData(businessRecords, { idField: 'id' }) as Observable<businessData[]>;
}
</code>```

But I also have a collection where every document has also a sub collection in it. As I have a collection named "drivers" and every driver document has an collection vehicle. I just want to access vehicle with the specific driver in Angular. So, What can I do to achieve this?

I tried the above method and I succeed but I'm unable to get the data of sub collection in Angular.

Body:
I've a simple collection in firebase and I done this to get the data:

getBusinessRecords(): Observable<businessData[]> {
    let businessRecords = collection(this.fs, 'businesses');
    return collectionData(businessRecords, { idField: 'id' }) as Observable<businessData[]>;
}

But I also have a collection where every document has also a sub collection in it. As I have a collection named "drivers" and every driver document has an collection vehicle. I just want to access vehicle with the specific driver in Angular. So, What can I do to achieve this?

I tried the above method and I succeed but I'm unable to get the data of sub collection in Angular.


问:
How I can add a image to excel table when I export my html table
I want to adding a company logo to my excel table which I export CSV. I am using Vuejs.

Anyone have experience about it ? I am open to suggestions modules or someting.

Thanks you

I just want to export my company logo to excel file


问:
How to query data from specific primary shards in elasticsearch
I want to query data only from primary shards (not replica shards) in elasticsearch.

I try using preference to query specific shards in elasticsearch. But how do I know which shards are primary shards to fill after preference=_shards: ?

```<code>GET my_index/_search?preference=_shards:0
{
  "_source": ["id", "handle"],
  "size": 10,
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            ...
          }
        }
      ]
    }
  }
}
</code>```

Body:
I want to query data only from primary shards (not replica shards) in elasticsearch.

I try using preference to query specific shards in elasticsearch. But how do I know which shards are primary shards to fill after preference=_shards: ?

GET my_index/_search?preference=_shards:0
{
  "_source": ["id", "handle"],
  "size": 10,
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            ...
          }
        }
      ]
    }
  }
}


问:
SAML 2 Assertion Fail to Unmarshal
I want to convert following SAML string to Response object. But when I try to unmarshal it, it returns unmarshaller to null. Can anyone help what is wrong here?

Code:

```<code>private static XMLObject unmarshallObject(String xmlString) throws Exception {
          BasicParserPool parser = new BasicParserPool();
          parser.setNamespaceAware(true);
          /* Base64URL encoded */
          byte bytes[] = xmlString.getBytes("utf-8");
          if (bytes == null || bytes.length == 0)
            throw new Exception("Invalid assertion encoding");
          Reader reader = new InputStreamReader(new FileInputStream(new File("assertion.xml")));
          Document doc = parser.parse(reader);
          Element samlElement = doc.getDocumentElement();
          UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
          Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(samlElement);
          if (unmarshaller == null) {
            throw new Exception("Unsuccessful to unmarshal assertion string");
          }
          return unmarshaller.unmarshall(samlElement);
        }
</code>```

SAML File

https://drive.google.com/file/d/1IIEsqWSDBt2W35l2Gx2vaNNxZr2zmx2u/view

Title: SAML 2 Assertion Fail to Unmarshal

Body:
I want to convert following SAML string to Response object. But when I try to unmarshal it, it returns unmarshaller to null. Can anyone help what is wrong here?

Code:

private static XMLObject unmarshallObject(String xmlString) throws Exception {
          BasicParserPool parser = new BasicParserPool();
          parser.setNamespaceAware(true);
          /* Base64URL encoded */
          byte bytes[] = xmlString.getBytes("utf-8");
          if (bytes == null || bytes.length == 0)
            throw new Exception("Invalid assertion encoding");
          Reader reader = new InputStreamReader(new FileInputStream(new File("assertion.xml")));
          Document doc = parser.parse(reader);
          Element samlElement = doc.getDocumentElement();
          UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
          Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(samlElement);
          if (unmarshaller == null) {
            throw new Exception("Unsuccessful to unmarshal assertion string");
          }
          return unmarshaller.unmarshall(samlElement);
        }

SAML File

https://drive.google.com/file/d/1IIEsqWSDBt2W35l2Gx2vaNNxZr2zmx2u/view


问:
How to make bitmap bigger without resizing the actual image
I am using Pax A920 device.

I have an issue when printing a bitmap, there is no option to center the bitmap(image) documentation

Methods reference:

The issue is when the bitmap's width is short, its left-aligned on the printed receipt.

I can scale the bitmap using:

Bitmap.createScaledBitmap(receiptLogo, 512, receiptLogo.getHeight(), false);

But it looks bad, I'm thinking of creating a new Bitmap with width of 512 & height of receipt.Logo.getHeight() then put the receipt logo in the middle so it wont look stretch.

Is this doable?


问:
Animation missing while Sheet in SwiftUI?
For few screen when I present the sheet below view comes little down with some transition effect and width get shrink, I guess its default behaviour of sheet, but when I push to other view and try to present sheet from there I am not getting that effect, even though the code syntax is same. Is there any way to achieve that animation

```<code>        .sheet(isPresented: $showPopView) {
                    DetailsView(
                        viewModel: viewModel.detailsViewModel
                    )
                }
</code>```

for ex. Transition showed in this link
https://www.hackingwithswift.com/quick-start/swiftui/how-to-present-a-new-view-using-sheets

Body:
For few screen when I present the sheet below view comes little down with some transition effect and width get shrink, I guess its default behaviour of sheet, but when I push to other view and try to present sheet from there I am not getting that effect, even though the code syntax is same. Is there any way to achieve that animation

        .sheet(isPresented: $showPopView) {
                    DetailsView(
                        viewModel: viewModel.detailsViewModel
                    )
                }

for ex. Transition showed in this link
https://www.hackingwithswift.com/quick-start/swiftui/how-to-present-a-new-view-using-sheets


问:
(Unity3d) How to set horizontal layout group child's rect transform to stretch for fit to screen?
I want to set Horizontal layout group child's rect transform to stretch for fit to screen.Horizontal layout group layout group's child

I tried this options but these are not working layout options


问:
getting symbols(???) instead of Arabic letters in processed excel file
```<code>Private Sub Convert()

Dim Workbook_Folder As String
Dim CWS As Worksheet

Workbook_Folder = Application.ActiveWorkbook.Path

    Application.DisplayAlerts = False
'ActiveWorkbook.WebOptions.Encoding = msoEncodingUTF-8-sig

ActiveWorkbook.SaveAs Filename:=Workbook_Folder & "\" & "Othaim_EPOS.csv", encoding="utf-8-sig"

    'Worksheets("Sheet1").Copy '  Forks a copy of the sheet in a new, active WB
    'With ActiveWorkbook
        '.SaveAs Filename:=Workbook_Folder & "\" & "Othaim_EPOS.csv", FileFormat:=xlUnicodeText, CreateBackup:=False
        '.Close False
    'End With
    Application.DisplayAlerts = True

End Sub

Converting the excel sheet to
</code>```

I am getting error while using above code to convert excel sheet

getting symbols(???) instead of Arabic letters in processed excel file

Can anyone help me here

Body:
Private Sub Convert()

Dim Workbook_Folder As String
Dim CWS As Worksheet

Workbook_Folder = Application.ActiveWorkbook.Path

    Application.DisplayAlerts = False
'ActiveWorkbook.WebOptions.Encoding = msoEncodingUTF-8-sig

ActiveWorkbook.SaveAs Filename:=Workbook_Folder & "\" & "Othaim_EPOS.csv", encoding="utf-8-sig"

    'Worksheets("Sheet1").Copy '  Forks a copy of the sheet in a new, active WB
    'With ActiveWorkbook
        '.SaveAs Filename:=Workbook_Folder & "\" & "Othaim_EPOS.csv", FileFormat:=xlUnicodeText, CreateBackup:=False
        '.Close False
    'End With
    Application.DisplayAlerts = True

End Sub

Converting the excel sheet to

I am getting error while using above code to convert excel sheet

getting symbols(???) instead of Arabic letters in processed excel file

Can anyone help me here


问:
Get confirmation_code from API written on Django-rest-framework
How to implement this logic without resorting to Djoser? I've been working on it for quite some time and I don't even know where to start....

The logic is the following:

The user sends a POST request with the email and username parameters to the /api/auth/signup/ endpoint.

The service sends an email with a confirmation code (confirmation_code) to the specified email address.

The user sends a POST request with the username and confirmation_code parameters to the /api/auth/token/ endpoint, in response to the request he receives a token (JWT token).

As a result, the user receives a token and can work with the project's API by sending this token with each request.

I have a generator for this token and have the standard Django mail backend connected.

```<code>from django.contrib.auth.tokens import PasswordResetTokenGenerator

import six

class ConfirmationCodeGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.is_active)
        )

confirmation_token = ConfirmationCodeGenerator()
</code>```

Body:
How to implement this logic without resorting to Djoser? I've been working on it for quite some time and I don't even know where to start....

The logic is the following:

The user sends a POST request with the email and username parameters to the /api/auth/signup/ endpoint.

The service sends an email with a confirmation code (confirmation_code) to the specified email address.

The user sends a POST request with the username and confirmation_code parameters to the /api/auth/token/ endpoint, in response to the request he receives a token (JWT token).

As a result, the user receives a token and can work with the project's API by sending this token with each request.

I have a generator for this token and have the standard Django mail backend connected.

from django.contrib.auth.tokens import PasswordResetTokenGenerator

import six

class ConfirmationCodeGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.is_active)
        )

confirmation_token = ConfirmationCodeGenerator()


问:
Load balancing Harbor Repo is not working when path_beg is having multiple paths
I have configured my harbor docker registry using HA Proxy. Here is my HA Proxy configuration.

```<code>frontend ashok_registry
  bind 0.0.0.0:8080
  use_backend maven-repo if { path_beg -i /repository }
  use_backend harbor-repo if { path_beg -i /v2/dev-images/ }

backend maven-repo
  server maven-repo mvn01-ashok-dev.net:443 ssl verify none check inter 5s

backend harbor-repo
  server harbor-repo hub.ashok.com:443 ssl verify none check inter 5s
</code>```

Here whenever i used multiple paths (/v2/dev-images) in path_beg. I am unable to pull the docker image. Getting following error

```<code>$ docker pull localhost:8080/dev-images/myapp/myapp-image:1.1.0
Error response from daemon: unauthorized: authorize header needed to send HEAD to repository: authorize header needed to send HEAD to repository
</code>```

Here is my HAProxy server logs

```<code>Dec 28 12:39:42 hydlpt391 haproxy[40706]: 127.0.0.1:53422 [28/Dec/2022:12:39:42.908] ashok_registry ashok_registry/<NOSRV> -1/-1/-1/-1/0 400 0 - - PR-- 1/1/0/0/0 0/0 "<BADREQ>"
Dec 28 12:39:42 hydlpt391 haproxy[40706]: 127.0.0.1:53436 [28/Dec/2022:12:39:42.909] ashok_registry ashok_registry/<NOSRV> -1/-1/-1/-1/0 503 216 - - SC-- 1/1/0/0/0 0/0 "GET /v2/ HTTP/1.1"
Dec 28 12:39:43 hydlpt391 haproxy[40706]: 127.0.0.1:53448 [28/Dec/2022:12:39:42.914] ashok_registry harbor-repo/harbor-repo 0/0/756/309/1065 401 480 - - ---- 1/1/0/0/0 0/0 "HEAD /v2/dev-images/myapp/myapp-image/manifests/1.1.0 HTTP/1.1"
Dec 28 12:39:44 hydlpt391 haproxy[40706]: 127.0.0.1:53452 [28/Dec/2022:12:39:43.981] ashok_registry harbor-repo/harbor-repo 0/0/758/251/1009 401 632 - - ---- 1/1/0/0/0 0/0 "GET /v2/dev-images/myapp/myapp-image/manifests/1.1.0 HTTP/1.1"
</code>```

If i remove multiple paths in the path_beg then iam able to pull the image through HAProxy

```<code>frontend ashok_registry
  bind 0.0.0.0:8080
  use_backend maven-repo if { path_beg -i /repository }
  use_backend harbor-repo if { path_beg -i /v2/ }

backend maven-repo
  server maven-repo mvn01-ashok-dev.net:443 ssl verify none check inter 5s

backend harbor-repo
  server harbor-repo hub.ashok.com:443 ssl verify none check inter 5s
</code>```

And pull command usage

```<code>docker pull localhost:8080/dev-images/myapp/myapp-image:1.1.0
1.0.0: Pulling from dev-images/myapp/myapp-image
213ec9aee27d: Already exists
24b464698217: Pull complete
4f4fb700ef54: Pull complete
b4c5e6d1ca25: Pull complete
4c437a1beb75: Pull complete
357d1bd31d98: Pull complete
72cf3d73d8a4: Pull complete
6476114140cd: Pull complete
f1f11b5c7106: Pull complete
</code>```

Here I need /v2/dev-images/ in bath_beg because i have multiple /v2/ paths in multiple urls. How can i solve this issue?

Body:
I have configured my harbor docker registry using HA Proxy. Here is my HA Proxy configuration.

frontend ashok_registry
  bind 0.0.0.0:8080
  use_backend maven-repo if { path_beg -i /repository }
  use_backend harbor-repo if { path_beg -i /v2/dev-images/ }

backend maven-repo
  server maven-repo mvn01-ashok-dev.net:443 ssl verify none check inter 5s

backend harbor-repo
  server harbor-repo hub.ashok.com:443 ssl verify none check inter 5s

Here whenever i used multiple paths (/v2/dev-images) in path_beg. I am unable to pull the docker image. Getting following error

$ docker pull localhost:8080/dev-images/myapp/myapp-image:1.1.0
Error response from daemon: unauthorized: authorize header needed to send HEAD to repository: authorize header needed to send HEAD to repository

Here is my HAProxy server logs

Dec 28 12:39:42 hydlpt391 haproxy[40706]: 127.0.0.1:53422 [28/Dec/2022:12:39:42.908] ashok_registry ashok_registry/<NOSRV> -1/-1/-1/-1/0 400 0 - - PR-- 1/1/0/0/0 0/0 "<BADREQ>"
Dec 28 12:39:42 hydlpt391 haproxy[40706]: 127.0.0.1:53436 [28/Dec/2022:12:39:42.909] ashok_registry ashok_registry/<NOSRV> -1/-1/-1/-1/0 503 216 - - SC-- 1/1/0/0/0 0/0 "GET /v2/ HTTP/1.1"
Dec 28 12:39:43 hydlpt391 haproxy[40706]: 127.0.0.1:53448 [28/Dec/2022:12:39:42.914] ashok_registry harbor-repo/harbor-repo 0/0/756/309/1065 401 480 - - ---- 1/1/0/0/0 0/0 "HEAD /v2/dev-images/myapp/myapp-image/manifests/1.1.0 HTTP/1.1"
Dec 28 12:39:44 hydlpt391 haproxy[40706]: 127.0.0.1:53452 [28/Dec/2022:12:39:43.981] ashok_registry harbor-repo/harbor-repo 0/0/758/251/1009 401 632 - - ---- 1/1/0/0/0 0/0 "GET /v2/dev-images/myapp/myapp-image/manifests/1.1.0 HTTP/1.1"

If i remove multiple paths in the path_beg then iam able to pull the image through HAProxy

frontend ashok_registry
  bind 0.0.0.0:8080
  use_backend maven-repo if { path_beg -i /repository }
  use_backend harbor-repo if { path_beg -i /v2/ }

backend maven-repo
  server maven-repo mvn01-ashok-dev.net:443 ssl verify none check inter 5s

backend harbor-repo
  server harbor-repo hub.ashok.com:443 ssl verify none check inter 5s

And pull command usage

docker pull localhost:8080/dev-images/myapp/myapp-image:1.1.0
1.0.0: Pulling from dev-images/myapp/myapp-image
213ec9aee27d: Already exists
24b464698217: Pull complete
4f4fb700ef54: Pull complete
b4c5e6d1ca25: Pull complete
4c437a1beb75: Pull complete
357d1bd31d98: Pull complete
72cf3d73d8a4: Pull complete
6476114140cd: Pull complete
f1f11b5c7106: Pull complete

Here I need /v2/dev-images/ in bath_beg because i have multiple /v2/ paths in multiple urls. How can i solve this issue?


问:
How do I re-render google map when props change
I have an application in which I am using google maps. In the map component, I am drawing shapes and using coordinates and components passed by props to render the map and shapes on the map.

However, I want such that when the zones and coordinates change, the map should re-render. with the updated area map and shape.

When I add the zones and coordinates as array dependecies for the useEffect hook, I can see that the component re-render by logging to the console, but the google map does not.

Please, how do I go about this?

Has anyone implemented this before?

Do I have to call the "handleApiLoaded" function again?

My code is shown below.

```<code>import GoogleMapReact from "google-map-react";
import useHeightPort from "../../Hooks/useHeightport";
import "../../assets/css/Map.css";
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import CreateSelect from "./CreateSelect";

import ZoneInfoWindow from "./ZoneInfoWindow";

import {
  createInfoWindow,
  drawPolygon,
  drawCircle,
  fitMapBounds,
  deepClone,
} from "./helpers"; /* I am using helper functions to tidy up things, not necessarily
integral to the apps functionality */

function Map({
  propZones,
  propCoords,
  propParticipants,
  showPLI
}) {

  let participants = deepClone(propParticipants); // get all from a single object here
  let [zones, setZones] = useState(deepClone(propZones));
  let [coords, setCoords] = useState(deepClone(propCoords));
  const [createDropdown, setCreateDropdown] = useState(<></>);

  const { Height } = useHeightPort();
  const calculatedHeight = Number(Height) - 289;

  const defaultProps = {
    center: { lat: 0, lng: 0 },
    zoom: 0,
  };

  let globalMap, globalMaps;
  let shapeObjs = [];
  let activeZoneId = false;

  const [markers, setMarkers] = useState([]);

  useEffect(() => {
    setZones(deepClone(propZones));
    setCoords(deepClone(propCoords));

    console.log("Something changed");
  }, [propCoords, propZones /* zoneGroup_id, reshow */]);

    const handleApiLoaded = (map, maps) => {
    globalMap = map;
    globalMaps = maps;

    zones.forEach((zone, i) => {
      // Draw Shape
      let { shape, lat, lng } = drawShape(zone, coords[i]);

      // Add InfoWindow to Polygon
      let infoWindow = createIW(zone, lat, lng, shape);
      shape.addInfoWindow(infoWindow);
      shape.zone_id = zone.zone_id;

      shapeObjs.push(shape);
    });

    // Add Participants to Map
    if (participants) {
      let icon;
      let newMarkers = [];

      participants.forEach((p, i) => {
        icon = {
          url: p.image,
          //size: new maps.Size(40, 40),
          size: new mapds.Size(40, 40),
        };
        // let marker = new maps.Marker({
        let marker = new maps.Marker({
          position: { lat: p.lat, lng: p.lng },
          //map,
          map,
          icon,
          visible: showPLI,
          optimized: false,
        });

        // Create InfoWindow
        let pliInfoWindow = createPLIIW(marker, "Impossible", p);

        newMarkers.push({ marker, infoWindow: pliInfoWindow });
      });
      setMarkers(newMarkers);
    }

    fitMapBounds(maps, map, zones, coords, shapeObjs);

    setCreateDropdown(<CreateSelect drawNewShape={drawNewShape} />); // To create a new shap when the api is fully loaded
  };

  // Draw Shape
  function drawShape(zone, coord) {
    const shape =
      zone.shapeType === "polygon"
        ? drawPolygon(
            zone.id,
            globalMaps,
            globalMap,
            coord,
            zone.style,
            updateZoneCoordinates
          )
        : drawCircle(
            zone.id,
            globalMaps,
            globalMap,
            coord,
            zone.style,
            updateZoneCoordinates
          );

    let { lat, lng } =
      zone.shapeType === "polygon"
        ? coord[0]
        : { lat: coord.lat, lng: coord.lng };

    return { shape, lat, lng };
  }

  // Create InfoWindow
  function createIW(zone, lat, lng, shape) {
    // Create InfoWindow
    let infoDetails = {
      loc: zone.location,
      lat,
      lng,
    };
    let infoDiv = document.createElement("div");
    let infoContent = ReactDOM.render(
      ZoneInfoWindow(zone.id, zone.title, infoDetails),
      infoDiv
    );

    return createInfoWindow(infoContent, zone.id, globalMaps, {
      parent: shape,
      delete: deleteZone,
      edit: editZoneWithForm,
    });
  }

  // Draw new shape
  const drawNewShape = (type) => {
    let newZone = {
      id: zones.length + 1,
      title: "New Zone",
      location: "Atlanta, Georgia",
      shapeType: type,
      style: {
        strokeColor: "#0072ff",
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: "#FFFFFF",
        fillOpacity: 0.4,
      },
    };
    let newCoord = drawDefaultShape(type);

    let { shape, lat, lng } = drawShape(newZone, newCoord);
    let infoWindow = createIW(newZone, lat, lng, shape);
    shape.addInfoWindow(infoWindow);

    shape.obj.setEditable(true);

    zones.push(newZone);
    coords.push(newCoord);
    shapeObjs.push(shape);

    if (activeZoneId !== false && activeZoneId !== newZone.id) {
      let activeZone = zones.find((z) => z.id === activeZoneId);
      shapeObjs[zones.indexOf(activeZone)].obj.setEditable(false);
    }

    activeZoneId = newZone.id;

    editZoneWithForm(newZone.id);

  };

  return (
    <div className="map-container" style={{ height: calculatedHeight + 159 }}>
      <div className="map-components" style={{ height: calculatedHeight - 70 }}>
        <div className="map-create-zone-container">{createDropdown}</div>

        <GoogleMapReact
          bootstrapURLKeys={{ key: "GOOGLE_API_KEY" }} // This will be turned to an Environment variable when we push live
          defaultCenter={defaultProps.center}
          defaultZoom={defaultProps.zoom}
          yesIWantToUseGoogleMapApiInternals
          /* onGoogleApiLoaded={({ map, maps }) =>
            handleApiLoaded.current(map, maps)
          } */
          onGoogleApiLoaded={({map, maps}) => handleApiLoaded(map, maps)}
        ></GoogleMapReact>
      </div>
    </div>
  );
}

export default Map;

</code>```

Body:
I have an application in which I am using google maps. In the map component, I am drawing shapes and using coordinates and components passed by props to render the map and shapes on the map.

However, I want such that when the zones and coordinates change, the map should re-render. with the updated area map and shape.

When I add the zones and coordinates as array dependecies for the useEffect hook, I can see that the component re-render by logging to the console, but the google map does not.

Please, how do I go about this?

Has anyone implemented this before?

Do I have to call the "handleApiLoaded" function again?

My code is shown below.

import GoogleMapReact from "google-map-react";
import useHeightPort from "../../Hooks/useHeightport";
import "../../assets/css/Map.css";
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import CreateSelect from "./CreateSelect";

import ZoneInfoWindow from "./ZoneInfoWindow";

import {
  createInfoWindow,
  drawPolygon,
  drawCircle,
  fitMapBounds,
  deepClone,
} from "./helpers"; /* I am using helper functions to tidy up things, not necessarily
integral to the apps functionality */

function Map({
  propZones,
  propCoords,
  propParticipants,
  showPLI
}) {

  let participants = deepClone(propParticipants); // get all from a single object here
  let [zones, setZones] = useState(deepClone(propZones));
  let [coords, setCoords] = useState(deepClone(propCoords));
  const [createDropdown, setCreateDropdown] = useState(<></>);

  const { Height } = useHeightPort();
  const calculatedHeight = Number(Height) - 289;

  const defaultProps = {
    center: { lat: 0, lng: 0 },
    zoom: 0,
  };

  let globalMap, globalMaps;
  let shapeObjs = [];
  let activeZoneId = false;

  const [markers, setMarkers] = useState([]);

  useEffect(() => {
    setZones(deepClone(propZones));
    setCoords(deepClone(propCoords));

    console.log("Something changed");
  }, [propCoords, propZones /* zoneGroup_id, reshow */]);

    const handleApiLoaded = (map, maps) => {
    globalMap = map;
    globalMaps = maps;

    zones.forEach((zone, i) => {
      // Draw Shape
      let { shape, lat, lng } = drawShape(zone, coords[i]);

      // Add InfoWindow to Polygon
      let infoWindow = createIW(zone, lat, lng, shape);
      shape.addInfoWindow(infoWindow);
      shape.zone_id = zone.zone_id;

      shapeObjs.push(shape);
    });

    // Add Participants to Map
    if (participants) {
      let icon;
      let newMarkers = [];

      participants.forEach((p, i) => {
        icon = {
          url: p.image,
          //size: new maps.Size(40, 40),
          size: new mapds.Size(40, 40),
        };
        // let marker = new maps.Marker({
        let marker = new maps.Marker({
          position: { lat: p.lat, lng: p.lng },
          //map,
          map,
          icon,
          visible: showPLI,
          optimized: false,
        });

        // Create InfoWindow
        let pliInfoWindow = createPLIIW(marker, "Impossible", p);

        newMarkers.push({ marker, infoWindow: pliInfoWindow });
      });
      setMarkers(newMarkers);
    }

    fitMapBounds(maps, map, zones, coords, shapeObjs);

    setCreateDropdown(<CreateSelect drawNewShape={drawNewShape} />); // To create a new shap when the api is fully loaded
  };

  // Draw Shape
  function drawShape(zone, coord) {
    const shape =
      zone.shapeType === "polygon"
        ? drawPolygon(
            zone.id,
            globalMaps,
            globalMap,
            coord,
            zone.style,
            updateZoneCoordinates
          )
        : drawCircle(
            zone.id,
            globalMaps,
            globalMap,
            coord,
            zone.style,
            updateZoneCoordinates
          );

    let { lat, lng } =
      zone.shapeType === "polygon"
        ? coord[0]
        : { lat: coord.lat, lng: coord.lng };

    return { shape, lat, lng };
  }

  // Create InfoWindow
  function createIW(zone, lat, lng, shape) {
    // Create InfoWindow
    let infoDetails = {
      loc: zone.location,
      lat,
      lng,
    };
    let infoDiv = document.createElement("div");
    let infoContent = ReactDOM.render(
      ZoneInfoWindow(zone.id, zone.title, infoDetails),
      infoDiv
    );

    return createInfoWindow(infoContent, zone.id, globalMaps, {
      parent: shape,
      delete: deleteZone,
      edit: editZoneWithForm,
    });
  }

  // Draw new shape
  const drawNewShape = (type) => {
    let newZone = {
      id: zones.length + 1,
      title: "New Zone",
      location: "Atlanta, Georgia",
      shapeType: type,
      style: {
        strokeColor: "#0072ff",
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: "#FFFFFF",
        fillOpacity: 0.4,
      },
    };
    let newCoord = drawDefaultShape(type);

    let { shape, lat, lng } = drawShape(newZone, newCoord);
    let infoWindow = createIW(newZone, lat, lng, shape);
    shape.addInfoWindow(infoWindow);

    shape.obj.setEditable(true);

    zones.push(newZone);
    coords.push(newCoord);
    shapeObjs.push(shape);

    if (activeZoneId !== false && activeZoneId !== newZone.id) {
      let activeZone = zones.find((z) => z.id === activeZoneId);
      shapeObjs[zones.indexOf(activeZone)].obj.setEditable(false);
    }

    activeZoneId = newZone.id;

    editZoneWithForm(newZone.id);

  };

  return (

{createDropdown}

        <GoogleMapReact
          bootstrapURLKeys={{ key: "GOOGLE_API_KEY" }} // This will be turned to an Environment variable when we push live
          defaultCenter={defaultProps.center}
          defaultZoom={defaultProps.zoom}
          yesIWantToUseGoogleMapApiInternals
          /* onGoogleApiLoaded={({ map, maps }) =>
            handleApiLoaded.current(map, maps)
          } */
          onGoogleApiLoaded={({map, maps}) => handleApiLoaded(map, maps)}
        ></GoogleMapReact>

  );
}

export default Map;


问:
How to get folder path from file path with CMD and change for new similar path?
I see this question How to get folder path from file path with CMD

and try resolve my problem without success.

I need move files from origem to destination similar path using CMD

my source with subfolder "origem"

```<code>c:\temp\origem\subfolderA\file1.pdf
c:\temp\origem\subfolderA\file2.pdf
c:\temp\origem\subfolderA\file3.pdf
c:\temp\origem\subfolderB\file1.pdf
</code>```

I need move files to diferent (similar) path with changing subfolder "origem" to "destination"

```<code>c:\temp\destination\subfolderA\file1.pdf
c:\temp\destination\subfolderA\file2.pdf
c:\temp\destination\subfolderA\file3.pdf
c:\temp\destination\subfolderB\file1.pdf
</code>```

If use above code

```<code>FOR /R c:\temp\origem %F IN (*.pdf) DO move "%~dpfF" "%~dpF"
</code>```

On "%~dpF" the parameter p I don't know change to destination

Body:
I see this question How to get folder path from file path with CMD

and try resolve my problem without success.

I need move files from origem to destination similar path using CMD

my source with subfolder "origem"

c:\temp\origem\subfolderA\file1.pdf
c:\temp\origem\subfolderA\file2.pdf
c:\temp\origem\subfolderA\file3.pdf
c:\temp\origem\subfolderB\file1.pdf

I need move files to diferent (similar) path with changing subfolder "origem" to "destination"

c:\temp\destination\subfolderA\file1.pdf
c:\temp\destination\subfolderA\file2.pdf
c:\temp\destination\subfolderA\file3.pdf
c:\temp\destination\subfolderB\file1.pdf

If use above code

FOR /R c:\temp\origem %F IN (*.pdf) DO move "%~dpfF" "%~dpF"

On "%~dpF" the parameter p I don't know change to destination


问:
HPM Error occurred while proxying request from win desktop to service running on wsl
I have the following error
<e> [webpack-dev-server] [HPM] Error occurred while proxying request localhost:8080/cpg/api/upload-code to http://localhost:5500/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)

when trying to call from gui to service running on wsl2

Curl works ok

C:\Program Files\Far Manager>curl -X "POST"   "http://localhost:5500/cpg/api/upload-code"                                                                     {"timestamp":"2022-12-28T06:38:11.314+00:00","path":"/cpg/api/upload-code","status":400,"error":"Bad Request","requestId":"38669ffa-23"}

Swagger call also works on on desktop

When i run the same service on desktop it works

This is our proxy configuration https://github.com/saveourtool/save-cloud/blob/master/save-frontend/webpack.config.d/dev-server.js

How to fix this?


问:
How to test a redirecting function using phpunit if it is getting exited
I have a function to redirect the user to a particular url which calls wp_redirect() function and then on return forcefully exits the function. I have added the code below

Plugin Function

protected function redirectUser($order)
{
    $redirectUrl = $this->get_return_url($order);

    wp_redirect($redirectUrl);

    exit;
}
```
<p>Test Function I wrote:</p>
<pre class="lang-php prettyprint-override"><code>public function testRedirectUser()
{
    $order = wc_create_order();

    $url = 'http://www.example.com';

    $this->instance->shouldReceive('get_return_url')
        ->with($order)
        ->andReturn($url);

    $this->instance->redirectUser($order)
        ->assertRedirect();
}
</code>```

Error faced:

```<code>1) Test_OrderMethods::testRedirectUser
Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/wordpress/wp-content/plugins/xyz_woocommerce/tests/phpunit/includes/bootstrap.php:265)
</code>```

Body:
I have a function to redirect the user to a particular url which calls wp_redirect() function and then on return forcefully exits the function. I have added the code below

Plugin Function

protected function redirectUser($order)
{
    $redirectUrl = $this->get_return_url($order);

    wp_redirect($redirectUrl);

    exit;
}

Test Function I wrote:

public function testRedirectUser()
{
    $order = wc_create_order();

    $url = 'http://www.example.com';

    $this->instance->shouldReceive('get_return_url')
        ->with($order)
        ->andReturn($url);

    $this->instance->redirectUser($order)
        ->assertRedirect();
}

Error faced:

1) Test_OrderMethods::testRedirectUser
Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/wordpress/wp-content/plugins/xyz_woocommerce/tests/phpunit/includes/bootstrap.php:265)


问:
Page 404 on reloading Vue.js app running in Tomcat
Our webapp has its backend running on Java Spring and front end on Vue.js. Both are hosted in Tomcat (webapps folder). The backend is inside 'ROOT' folder, and front end is inside 'front' folder inside Webapps dir.

As vue front end is SPA, when we reload the app, we get a 404 as the server isn't able to find appropriate location from the reload URL. What settings should I change in Tomcat so that the reload works? Thanks in advance.


问:
How do I secure firestore database for my React Native app?
I have a simple React Native app that I'm building with Expo, using Firestore as it's database. There's no user registration, nor are there any user writes/updates to the database -  it's simply displaying information to anyone who installs the app.

I want to protect my database from abuse. Initially I was going to set up an express server to serve the API key, but I've read on other posts that this is basically redundant.
So my intention now is to configure App Check so that only my app can access the database.

Here's where the confusion comes in - I registered my app on Firebase as a web app, and now when I try to set up App Check, it only offers reCAPTCHA as way of securing my project. My understanding that this will only secure web pages, and not android/iOS apps.
So how do I set up a cross-platform app on firebase so that it can be secured across all platforms?
As a side note - I set up my project as a web app because that's what I thought I was supposed to do when trying to build a cross-platform app with Expo.


问:
Problem with converting Promise in useReducer - typescript(react JS)
Convert Promise to data
I am trying to convert my use state to use reducer.
an async function is calling to fetch data and I'm not abale to use it in the reducer
here is part of the code:

```<code> switch (action.type) {
      case "load":

        const data = loadTodos()
        state = { ...state, todos: [...data] };
        return state;
}}

async function loadTodos() {
    return await todoService.getTodo();

  }
</code>```

I tried to solve the problem in this way :

```<code>var myState = []
loadTodos().then((data) => {
          myState = [...data];
        });
        console.log(myState);
</code>```

`
myState is correct inside .then scope but outside is empty array.

Body:
Convert Promise to data
I am trying to convert my use state to use reducer.
an async function is calling to fetch data and I'm not abale to use it in the reducer
here is part of the code:

 switch (action.type) {
      case "load":

        const data = loadTodos()
        state = { ...state, todos: [...data] };
        return state;
}}

async function loadTodos() {
    return await todoService.getTodo();

  }

I tried to solve the problem in this way :

var myState = []
loadTodos().then((data) => {
          myState = [...data];
        });
        console.log(myState);

`
myState is correct inside .then scope but outside is empty array.


问:
JSmpeg is not playing audio from websocket stream
I am trying to stream RTSP to web browser using ffmpeg through web socket relay written in node js taken from https://github.com/phoboslab/jsmpeg , and on the browser i am using JSMpeg to display the RTSP stream, the video is playing fine, but audio is not playing,

The ffmpeg command:

```<code>ffmpeg -rtsp_transport tcp -i rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4
       -f mpegts -c:v mpeg1video -c:a mp2 http://127.0.0.1:8081/stream_from_ffmpeg/<my_secret>
</code>```

The node js web socket relay:

```<code>// Use the websocket-relay to serve a raw MPEG-TS over WebSockets. You can use
// ffmpeg to feed the relay. ffmpeg -> websocket-relay -> browser
// Example:
// node websocket-relay yoursecret 8081 8082
// ffmpeg -i <some input> -f mpegts http://localhost:8081/yoursecret

var fs = require('fs'),
    http = require('http'),
    WebSocket = require('ws');

if (process.argv.length < 3) {
    console.log(
        'Usage: \n' +
        'node websocket-relay.js <secret> [<stream-port> <websocket-port>]'
    );
    process.exit();
}

var STREAM_SECRET = process.argv[2],
    STREAM_PORT = process.argv[3] || 8081,
    WEBSOCKET_PORT = process.argv[4] || 8082,
    RECORD_STREAM = false;

// Websocket Server
var socketServer = new WebSocket.Server({port: WEBSOCKET_PORT, perMessageDeflate: false});
socketServer.connectionCount = 0;
socketServer.on('connection', function(socket, upgradeReq) {
    socketServer.connectionCount++;
    console.log(
        'New WebSocket Connection: ',
        (upgradeReq || socket.upgradeReq).socket.remoteAddress,
        (upgradeReq || socket.upgradeReq).headers['user-agent'],
        '('+socketServer.connectionCount+' total)'
    );
    socket.on('close', function(code, message){
        socketServer.connectionCount--;
        console.log(
            'Disconnected WebSocket ('+socketServer.connectionCount+' total)'
        );
    });
});
socketServer.broadcast = function(data) {
    socketServer.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
};

// HTTP Server to accept incoming MPEG-TS Stream from ffmpeg
var streamServer = http.createServer( function(request, response) {
    var params = request.url.substr(1).split('/');

    if (params[0] !== STREAM_SECRET) {
        console.log(
            'Failed Stream Connection: '+ request.socket.remoteAddress + ':' +
            request.socket.remotePort + ' - wrong secret.'
        );
        response.end();
    }

    response.connection.setTimeout(0);
    console.log(
        'Stream Connected: ' +
        request.socket.remoteAddress + ':' +
        request.socket.remotePort
    );
    request.on('data', function(data){
        socketServer.broadcast(data);
        if (request.socket.recording) {
            request.socket.recording.write(data);
        }
    });
    request.on('end',function(){
        console.log('close');
        if (request.socket.recording) {
            request.socket.recording.close();
        }
    });

    // Record the stream to a local file?
    if (RECORD_STREAM) {
        var path = 'recordings/' + Date.now() + '.ts';
        request.socket.recording = fs.createWriteStream(path);
    }
})
// Keep the socket open for streaming
streamServer.headersTimeout = 0;
streamServer.listen(STREAM_PORT);

console.log('Listening for incoming MPEG-TS Stream on http://127.0.0.1:'+STREAM_PORT+'/<secret>');
console.log('Awaiting WebSocket connections on ws://127.0.0.1:'+WEBSOCKET_PORT+'/');
</code>```

The front end code

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="./jsmpeg.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <canvas id="video-canvas"></canvas>
  </body>
  <script>
    let url;
    let player;
    let canvas = document.getElementById("video-canvas");
    let ipAddr = "127.0.0.1:8082";
    window.onload = async() => {
      url = `ws://${ipAddr}`;
      player = new JSMpeg.Player(url, { canvas: canvas, });
    };

  </script>
</html>

</code>```

The above code works fine and plays the video, but no audio is playing
Things I tried:

Changed the audio context state inside the player object from suspended to running

```<code>player.audioOut.context.onstatechange = async () => {
    console.log("Event triggered by audio");

    if (player.audioOut.context === "suspended") {
        await player.audioOut.context.resume();
    }
}
</code>```

Body:
I am trying to stream RTSP to web browser using ffmpeg through web socket relay written in node js taken from https://github.com/phoboslab/jsmpeg , and on the browser i am using JSMpeg to display the RTSP stream, the video is playing fine, but audio is not playing,

The ffmpeg command:

ffmpeg -rtsp_transport tcp -i rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4
       -f mpegts -c:v mpeg1video -c:a mp2 http://127.0.0.1:8081/stream_from_ffmpeg/<my_secret>

The node js web socket relay:

// Use the websocket-relay to serve a raw MPEG-TS over WebSockets. You can use
// ffmpeg to feed the relay. ffmpeg -> websocket-relay -> browser
// Example:
// node websocket-relay yoursecret 8081 8082
// ffmpeg -i <some input> -f mpegts http://localhost:8081/yoursecret

var fs = require('fs'),
    http = require('http'),
    WebSocket = require('ws');

if (process.argv.length < 3) {
    console.log(
        'Usage: \n' +
        'node websocket-relay.js <secret> [<stream-port> <websocket-port>]'
    );
    process.exit();
}

var STREAM_SECRET = process.argv[2],
    STREAM_PORT = process.argv[3] || 8081,
    WEBSOCKET_PORT = process.argv[4] || 8082,
    RECORD_STREAM = false;

// Websocket Server
var socketServer = new WebSocket.Server({port: WEBSOCKET_PORT, perMessageDeflate: false});
socketServer.connectionCount = 0;
socketServer.on('connection', function(socket, upgradeReq) {
    socketServer.connectionCount++;
    console.log(
        'New WebSocket Connection: ',
        (upgradeReq || socket.upgradeReq).socket.remoteAddress,
        (upgradeReq || socket.upgradeReq).headers['user-agent'],
        '('+socketServer.connectionCount+' total)'
    );
    socket.on('close', function(code, message){
        socketServer.connectionCount--;
        console.log(
            'Disconnected WebSocket ('+socketServer.connectionCount+' total)'
        );
    });
});
socketServer.broadcast = function(data) {
    socketServer.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
};

// HTTP Server to accept incoming MPEG-TS Stream from ffmpeg
var streamServer = http.createServer( function(request, response) {
    var params = request.url.substr(1).split('/');

    if (params[0] !== STREAM_SECRET) {
        console.log(
            'Failed Stream Connection: '+ request.socket.remoteAddress + ':' +
            request.socket.remotePort + ' - wrong secret.'
        );
        response.end();
    }

    response.connection.setTimeout(0);
    console.log(
        'Stream Connected: ' +
        request.socket.remoteAddress + ':' +
        request.socket.remotePort
    );
    request.on('data', function(data){
        socketServer.broadcast(data);
        if (request.socket.recording) {
            request.socket.recording.write(data);
        }
    });
    request.on('end',function(){
        console.log('close');
        if (request.socket.recording) {
            request.socket.recording.close();
        }
    });

    // Record the stream to a local file?
    if (RECORD_STREAM) {
        var path = 'recordings/' + Date.now() + '.ts';
        request.socket.recording = fs.createWriteStream(path);
    }
})
// Keep the socket open for streaming
streamServer.headersTimeout = 0;
streamServer.listen(STREAM_PORT);

console.log('Listening for incoming MPEG-TS Stream on http://127.0.0.1:'+STREAM_PORT+'/<secret>');
console.log('Awaiting WebSocket connections on ws://127.0.0.1:'+WEBSOCKET_PORT+'/');

The front end code

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Document</title>

    <canvas id="video-canvas"></canvas>

The above code works fine and plays the video, but no audio is playing
Things I tried:

Changed the audio context state inside the player object from suspended to running

player.audioOut.context.onstatechange = async () => {
    console.log("Event triggered by audio");

    if (player.audioOut.context === "suspended") {
        await player.audioOut.context.resume();
    }
}


问:
building the CAdES around a PKCS#1 signature in java
I'm new to PKCS and, I have a PKCS1 signature which it is a signature of a file, I want to do the whole CAdES creation around it in java with the BouncyCastle library(if it's possible), how i can do this?

Noting that: the sign process is a remote job, after doing the authentication process with a card, i will send a request to a server to sign a file and as an answer I will receive only a byte[] of signature, which its a pkcs#1 signature.

im expect to create a pkcs7 and save it in a file


问:
CSV data per line in a row into PDF's
Anyone know how do i create a multiple pdfs that having a data per row in csv, I'm having this idea to create a receipt of pdf per clients but the data of clients is inside of csv per row. anyone have a idea? thank you so much for your reply.

data in csv per row into pdf's for clients receipt.

Title: CSV data per line in a row into PDF's


问:
API Call every time navigating to the Specific fragment - All lifecycle will be recall again
In my app there is a screen called home screen, that call some api's when app open, but if user navigate through the home screen to the details screen and coming back from details screen to home screen it will called all api's again, There is any way to handle calling api again again everytime user navigate to the homescreen.</p>