问:
helm trigger pod restart on parent-chart configmap change
I'm facing the problem that we use an umbrella helm chart to deploy our services but our services are contained in subcharts. But there are some global configmaps that multiple services are using which are deployed by the umbrella chart. So a simplified structure looks like this:

```<code>├── Chart.yaml
├── templates
│   ├──  global-config.yaml
├── charts
│   ├── subchart1
│   │   ├── Chart.yaml
│   │   ├──    templates
│   │   │   ├──      deployment1.yaml
│   ├──  subchart2
│   │   ├──    Chart.yaml
│   │   ├──    templates
│   │   │   ├──      deployment2.yaml
 ...
</code>```

I what I need is to put a checksum of global-config.yaml in deployment1.yaml and deployment2.yaml as annotation like in https://helm.sh/docs/howto/charts_tips_and_tricks/#automatically-roll-deployments

The problem is that I can define a template like this in the umbrella chart:

```<code>{{- define "configmap.checksum" }}{{ include (print $.Template.BasePath "/global-config.yaml") . | sha256sum }}{{ end }}
</code>```

and then use {{ include "configmap.checksum" . }} in the deployment yamls as templates are global. But $.Template.BasePath is parsed when the include happens so it actually points to the template directory of the subchart where it is included. I have played around with '..' and the Files. and with passing another context in the template and also in the include like passing the global context $ but none of them were successful as I ways always locked in the specific subchart at rendering time.

Is there a solution to this or a different approach to solve this? Or is this something that cannot be done in helm? But I'm grateful for any solution

答:
I found a workaround that requires you to refactor the contents of your global ConfigMap into a template in the umbrellas chart. You won't be able to use regular values from the umbrella chart in your ConfigMap, otherwise you'll get an error when trying to render the template in a subchart; you'll have to use global values instead.

```<code>{{/*
Create the contents of the global-config ConfigMap
*/}}
{{- define "my-umbrella-chart.global-config-contents" -}}
spring.activemq.user={{ .Values.global.activeMqUsername | quote }}
spring.activemq.password={{ .Values.global.activeMqPassword | quote }}
jms.destinations.itemCreationQueue={{ .Release.Namespace }}-itemCreationQueue
{{- end }}
</code>```

kind: ConfigMap
apiVersion: v1
metadata:
  name: global-config
data:
  {{- include "my-umbrella-chart.global-config-contents" . | nindent 2 }}
```
<p>Then you add a checksum of <code>my-umbrella-chart.global-config-contents</code> in <code>deployment1.yaml</code> and <code>deployment2.yaml</code> as an annotation like so:</p>
<pre class="lang-yaml prettyprint-override"><code>annotations:
  # Automatically roll deployment when the configmap contents changes
  checksum/global-config: {{ include "my-umbrella-chart.global-config-contents" . | sha256sum }}
</code>```

Body:
I'm facing the problem that we use an umbrella helm chart to deploy our services but our services are contained in subcharts. But there are some global configmaps that multiple services are using which are deployed by the umbrella chart. So a simplified structure looks like this:

├── Chart.yaml
├── templates
│   ├──  global-config.yaml
├── charts
│   ├── subchart1
│   │   ├── Chart.yaml
│   │   ├──    templates
│   │   │   ├──      deployment1.yaml
│   ├──  subchart2
│   │   ├──    Chart.yaml
│   │   ├──    templates
│   │   │   ├──      deployment2.yaml
 ...

I what I need is to put a checksum of global-config.yaml in deployment1.yaml and deployment2.yaml as annotation like in https://helm.sh/docs/howto/charts_tips_and_tricks/#automatically-roll-deployments

The problem is that I can define a template like this in the umbrella chart:

{{- define "configmap.checksum" }}{{ include (print $.Template.BasePath "/global-config.yaml") . | sha256sum }}{{ end }}

and then use {{ include "configmap.checksum" . }} in the deployment yamls as templates are global. But $.Template.BasePath is parsed when the include happens so it actually points to the template directory of the subchart where it is included. I have played around with '..' and the Files. and with passing another context in the template and also in the include like passing the global context $ but none of them were successful as I ways always locked in the specific subchart at rendering time.

Is there a solution to this or a different approach to solve this? Or is this something that cannot be done in helm? But I'm grateful for any solution

Body:
I found a workaround that requires you to refactor the contents of your global ConfigMap into a template in the umbrellas chart. You won't be able to use regular values from the umbrella chart in your ConfigMap, otherwise you'll get an error when trying to render the template in a subchart; you'll have to use global values instead.

{{/*
Create the contents of the global-config ConfigMap
*/}}
{{- define "my-umbrella-chart.global-config-contents" -}}
spring.activemq.user={{ .Values.global.activeMqUsername | quote }}
spring.activemq.password={{ .Values.global.activeMqPassword | quote }}
jms.destinations.itemCreationQueue={{ .Release.Namespace }}-itemCreationQueue
{{- end }}

kind: ConfigMap
apiVersion: v1
metadata:
  name: global-config
data:
  {{- include "my-umbrella-chart.global-config-contents" . | nindent 2 }}

Then you add a checksum of my-umbrella-chart.global-config-contents in deployment1.yaml and deployment2.yaml as an annotation like so:

annotations:
  # Automatically roll deployment when the configmap contents changes
  checksum/global-config: {{ include "my-umbrella-chart.global-config-contents" . | sha256sum }}


来源: stackexchange

问:
How to grep all files that have a keyword and files should be created today
Have a directory with files. how to grep all files with a particular keyword and files should be created today.

tried this :

```<code>
grep -r -n "pass" *.json

</code>```

this gives the line number and only searches json file but how to add pipe to search for only files that are created today

答:
Use the find command as the source of the list of files to search.

```<code>grep -n "pass" $(find . -daystart -ctime 0 -name '*.json')
</code>```

-ctime says "creation date should have been 0 days ago", and -daystart says to base it on the beginning of the day for "days ago", not "24 hours ago" ago.

ContentLicense: CC BY-SA 4.0

Body:
Have a directory with files. how to grep all files with a particular keyword and files should be created today.

tried this :

grep -r -n "pass" *.json

this gives the line number and only searches json file but how to add pipe to search for only files that are created today

Body:
Use the find command as the source of the list of files to search.

grep -n "pass" $(find . -daystart -ctime 0 -name '*.json')

-ctime says "creation date should have been 0 days ago", and -daystart says to base it on the beginning of the day for "days ago", not "24 hours ago" ago.


问:
"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm
I am trying to plot a simple graph using pyplot, e.g.:

```<code>import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()
</code>```

but the figure does not appear and I get the following message:

```<code>UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
</code>```

I found and tried some advice to re-configure the "backend" mentioned in that warning, like so:

```<code>import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
</code>```

but this gives me an error message:

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

I assumed that I had to install this module separately, but pip install tkinter does not work:

```<code>Collecting tkinter
  Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter
</code>```

How can I make Matplotlib display the graph?

See also: Why does tkinter (or turtle) seem to be missing or broken? Shouldn't it be part of the standard library? . This question is not a duplicate, because the answers discuss other backends besides the Tkinter one.

Also see _tkinter.TclError: no display name and no $DISPLAY environment variable for issues with attempts to use Matplotlib remotely.

答:
On WSL with X server

Make sure that your X server work. Matplotlib indicate this error if he can't connect to the X display.

Windows Firewall configuration

Pay attention to the windows firewall ! I changed from WSL Debian to Ubuntu and didn't remember about the firewall rule.
I use this post to configure the windows firewall rule to make the X server work. This method avoid too permisive rule that able anyone to use your X server.

It said :

If you already had installed an X11 server, Windows may have created firewall rules that will mess with the above configuration. Search for them and delete them in "Windows Defender Firewall with Advanced Security."

You will now need to configure Windows Firewall to permit connections from WSL2 to the X11 display server. You will install the display server in the next step. We do this step first to avoid Windows Firewall from auto-creating an insecure firewall rule when you run the X11 display server. Many guides on X11 forwarding and WSL2 make this firewall rule too permissive, allowing connections from any computer to your computer. This means someone could theoretically, if they are on your same network, start sending graphical display information to your computer.

To avoid this, we will make Windows Firewall only accept internet traffic from the WSL2 instance.

To set this up, you can copy the below to a script and run it from within WSL2:

```<code>#!/bin/sh
LINUX_IP=$(ip addr | awk '/inet / && !/127.0.0.1/ {split($2,a,"/"); print a[1]}')
WINDOWS_IP=$(ip route | awk '/^default/ {print $3}')
# Elevate to administrator status then run netsh to add firewall rule
powershell.exe -Command "Start-Process netsh.exe -ArgumentList \"advfirewall firewall add rule name=X11-Forwarding dir=in action=allow program=%ProgramFiles%\VcXsrv\vcxsrv.exe localip=$WINDOWS_IP remoteip=$LINUX_IP localport=6000 protocol=tcp\" -Verb RunAs"
</code>```

Manual method :

Alternatively, you can manually add the rule through a GUI by doing the following:

Open "Windows Defender Firewall with Advanced Security"

Click add new rule brings up the New Rule Wizard (next to navigate between each section):

Rule type: Custom

Program: "This program path:" %ProgramFiles%\VcXsrv\vcxsrv.exe

Protocol and ports

Protocol type: TCP

Local port: 6000

Remote port: any

Scope

Local IP address: Obtain the IP address to put in by running the below command in WSL2
ip route | awk '/^default/ {print $3}'

remote IP addresses

Obtain IP address to enter by running the below in WSL2
ip addr | awk '/inet / && !/127.0.0.1/ {split($2,a,"/"); print a[1]}'

Action: "Allow the connection

Profile: Selection Domain, Private, and Public

Name: "X11 forwarding"

Body:
I am trying to plot a simple graph using pyplot, e.g.:

import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()

but the figure does not appear and I get the following message:

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

I found and tried some advice to re-configure the "backend" mentioned in that warning, like so:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

but this gives me an error message:

ModuleNotFoundError: No module named 'tkinter'

I assumed that I had to install this module separately, but pip install tkinter does not work:

Collecting tkinter
  Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter

How can I make Matplotlib display the graph?

See also: Why does tkinter (or turtle) seem to be missing or broken? Shouldn't it be part of the standard library? . This question is not a duplicate, because the answers discuss other backends besides the Tkinter one.

Also see _tkinter.TclError: no display name and no $DISPLAY environment variable for issues with attempts to use Matplotlib remotely.

Body:
On WSL with X server

Make sure that your X server work. Matplotlib indicate this error if he can't connect to the X display.

Windows Firewall configuration

Pay attention to the windows firewall ! I changed from WSL Debian to Ubuntu and didn't remember about the firewall rule.
I use this post to configure the windows firewall rule to make the X server work. This method avoid too permisive rule that able anyone to use your X server.

It said :

If you already had installed an X11 server, Windows may have created firewall rules that will mess with the above configuration. Search for them and delete them in "Windows Defender Firewall with Advanced Security."

You will now need to configure Windows Firewall to permit connections from WSL2 to the X11 display server. You will install the display server in the next step. We do this step first to avoid Windows Firewall from auto-creating an insecure firewall rule when you run the X11 display server. Many guides on X11 forwarding and WSL2 make this firewall rule too permissive, allowing connections from any computer to your computer. This means someone could theoretically, if they are on your same network, start sending graphical display information to your computer.

To avoid this, we will make Windows Firewall only accept internet traffic from the WSL2 instance.

To set this up, you can copy the below to a script and run it from within WSL2:

#!/bin/sh
LINUX_IP=$(ip addr | awk '/inet / && !/127.0.0.1/ {split($2,a,"/"); print a[1]}')
WINDOWS_IP=$(ip route | awk '/^default/ {print $3}')
# Elevate to administrator status then run netsh to add firewall rule
powershell.exe -Command "Start-Process netsh.exe -ArgumentList \"advfirewall firewall add rule name=X11-Forwarding dir=in action=allow program=%ProgramFiles%\VcXsrv\vcxsrv.exe localip=$WINDOWS_IP remoteip=$LINUX_IP localport=6000 protocol=tcp\" -Verb RunAs"

Manual method :

Alternatively, you can manually add the rule through a GUI by doing the following:

Open "Windows Defender Firewall with Advanced Security"

Click add new rule brings up the New Rule Wizard (next to navigate between each section):

Rule type: Custom

Program: "This program path:" %ProgramFiles%\VcXsrv\vcxsrv.exe

Protocol and ports

Protocol type: TCP

Local port: 6000

Remote port: any

Scope

Local IP address: Obtain the IP address to put in by running the below command in WSL2
ip route | awk '/^default/ {print $3}'

remote IP addresses

Obtain IP address to enter by running the below in WSL2
ip addr | awk '/inet / && !/127.0.0.1/ {split($2,a,"/"); print a[1]}'

Action: "Allow the connection

Profile: Selection Domain, Private, and Public

Name: "X11 forwarding"


问:
In Python Plotly, annotation is always on the top-left of a target point. How to annotate under a target point?
In Python, Plotly annotates always on the top-left of a target point (see the below line). However, I would like to annotate on the bottom-center of a point.

Please help with this. Thank you in advance for any comment.

```<code>import plotly.graph_objs as go
import plotly.io as pio
pio.renderers.default = 'browser'

x = list(range(1, 10))
y = list(range(21, 30))

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y))

fig.add_annotation(x=x[4], y=y[4], arrowsize=2, text='Alway on the top-left')

pio.show(fig)
</code>```

答:
You can use the parameters ax and ay to control the direction of the arrow (and the text will be positioned accordingly).

For example:

```<code>import plotly.graph_objs as go
import plotly.io as pio
pio.renderers.default = 'browser'

x = list(range(1, 10))
y = list(range(21, 30))

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y))

fig.add_annotation(x=x[4], y=y[4], arrowsize=2, text='text underneath', ax=10, ay=30)

pio.show(fig)
</code>```

Body:
In Python, Plotly annotates always on the top-left of a target point (see the below line). However, I would like to annotate on the bottom-center of a point.

Please help with this. Thank you in advance for any comment.

import plotly.graph_objs as go
import plotly.io as pio
pio.renderers.default = 'browser'

x = list(range(1, 10))
y = list(range(21, 30))

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y))

fig.add_annotation(x=x[4], y=y[4], arrowsize=2, text='Alway on the top-left')

pio.show(fig)

Body:
You can use the parameters ax and ay to control the direction of the arrow (and the text will be positioned accordingly).

For example:

import plotly.graph_objs as go
import plotly.io as pio
pio.renderers.default = 'browser'

x = list(range(1, 10))
y = list(range(21, 30))

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y))

fig.add_annotation(x=x[4], y=y[4], arrowsize=2, text='text underneath', ax=10, ay=30)

pio.show(fig)


问:
css nth-child selector doesn't work with styled mui component
I have a styled component like this:

```<code>const FormBox = styled(Box)(({ theme }) => ({
  width: "47vw",
  height: "25vh",
  backgroundColor: theme.palette.grey[100],
  borderRadius: theme.shape.borderRadius,
  marginLeft: "auto",
  marginRight: "auto",
  marginTop: theme.spacing(5),
  display: "flex",
  justifyContent: "space-between",
  flexWrap: "wrap",
  padding: theme.spacing(2),
  columnGap: theme.spacing(5),
  "&>*": { flex: "0 1 auto" },
  "&:nth-child(4)": { flex: "1 1 200px", backgroundColor: "red" }, //?????????????
}));
</code>```

in the last line of code I targeted the 4th child(the button component in the bellow code) and I want to apply some CSS on it but it doesn't work.

and inside this styled component there are four child as bellow:

```<code><FormBox component="form" noValidate autoComplete="off">
      <TextField label="Title">{title}</TextField>
      <TextField label="Amount">{amount}</TextField>
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <DatePicker
          label="Date"
          onChange={(newValue) => {
            setDate(newValue);
          }}
          renderInput={(params) => <TextField {...params} />}
          sx={{ width: 50 }}
        />
      </LocalizationProvider>
      <Button variant="contained" sx={{height: 50}}>Add</Button>
    </FormBox>
</code>```

答:
Please try with &>*:nth-child(4) instead of &:nth-child(4).

You can make sense from this link.
https://www.codegrepper.com/code-examples/css/css+selector+last+element

Body:
I have a styled component like this:

const FormBox = styled(Box)(({ theme }) => ({
  width: "47vw",
  height: "25vh",
  backgroundColor: theme.palette.grey[100],
  borderRadius: theme.shape.borderRadius,
  marginLeft: "auto",
  marginRight: "auto",
  marginTop: theme.spacing(5),
  display: "flex",
  justifyContent: "space-between",
  flexWrap: "wrap",
  padding: theme.spacing(2),
  columnGap: theme.spacing(5),
  "&>*": { flex: "0 1 auto" },
  "&:nth-child(4)": { flex: "1 1 200px", backgroundColor: "red" }, //?????????????
}));

in the last line of code I targeted the 4th child(the button component in the bellow code) and I want to apply some CSS on it but it doesn't work.

and inside this styled component there are four child as bellow:

<FormBox component="form" noValidate autoComplete="off">
      <TextField label="Title">{title}</TextField>
      <TextField label="Amount">{amount}</TextField>
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <DatePicker
          label="Date"
          onChange={(newValue) => {
            setDate(newValue);
          }}
          renderInput={(params) => <TextField {...params} />}
          sx={{ width: 50 }}
        />
      </LocalizationProvider>
      <Button variant="contained" sx={{height: 50}}>Add</Button>
    </FormBox>


问:
Display all data of all tables
I want to display all data in my Database without writing a select for each table - how can I do this?

I do not want to do this:

```<code>select * from Customer
select * from Employee
select .............
</code>```

I am using TSQL with MSSQL Server.

答:
```<code>DECLARE @sqlText VARCHAR(MAX)
SET @sqlText = ''
SELECT @sqlText = @sqlText + ' SELECT * FROM ' + QUOTENAME(name) + CHAR(13) FROM sys.tables
EXEC(@sqlText)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Display all data of all tables

Body:
I want to display all data in my Database without writing a select for each table - how can I do this?

I do not want to do this:

select * from Customer
select * from Employee
select .............

I am using TSQL with MSSQL Server.


问:
How to limit a full join by date
Our database is on SQL Server 2014. I had the exact same issue as SQL join table to itself to get data for previous year, and was so happy to find the answer. So I setup my query:

```<code>select distinct
    coalesce (a.year, b.year+1) [Year]
  , coalesce(a.Month, b.Month) [Month]
  , coalesce(a.account, b.account) [Account]
  , case when a.sales > 0
        then a.sales
        else 0 end [Sales MTD]
  , case when b.sales > 0
        then b.sales
        else 0 end [Sales Previous Year]
  , (case when b.sales!= 0
        then cast((case when a.sales > 0
                then a.sales
                else 0 end-b.sales)/b.sales*100 as decimal(10,1))
        else 0 end) [% Difference]
  , sum(a.sales) over (Partition by a.account, a.year order by a.month) [Account Sales YTD]
from yourtable a
      full join yourtable b
            on  a.account = b.account
            and a.month = b.month
            and a.year = b.year+1
</code>```

The output is giving me results for months in 2022 that haven't happened yet (and starting 2023 too). https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=9a2c29f1af08f525a1acee16b0efa2fd

I tried adding and b.[year]+1<=year(getdate()) to my join filters, but that doesn't seem to affect output at all. I also tried writing a where clause, that ended up with a case that made my head spin.

How can I prevent future dates from showing up in the end result?
Bonus question: Can I make my YTD calculation accept a 0 as a value for any lines added due to sales history?

答: if I've understood correctly, you need a left outer join, as you care when you have records in one table but not both.</p>

Title: How to limit a full join by date

Body:
Our database is on SQL Server 2014. I had the exact same issue as SQL join table to itself to get data for previous year, and was so happy to find the answer. So I setup my query:

select distinct
    coalesce (a.year, b.year+1) [Year]
  , coalesce(a.Month, b.Month) [Month]
  , coalesce(a.account, b.account) [Account]
  , case when a.sales > 0
        then a.sales
        else 0 end [Sales MTD]
  , case when b.sales > 0
        then b.sales
        else 0 end [Sales Previous Year]
  , (case when b.sales!= 0
        then cast((case when a.sales > 0
                then a.sales
                else 0 end-b.sales)/b.sales*100 as decimal(10,1))
        else 0 end) [% Difference]
  , sum(a.sales) over (Partition by a.account, a.year order by a.month) [Account Sales YTD]
from yourtable a
      full join yourtable b
            on  a.account = b.account
            and a.month = b.month
            and a.year = b.year+1

The output is giving me results for months in 2022 that haven't happened yet (and starting 2023 too). https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=9a2c29f1af08f525a1acee16b0efa2fd

I tried adding and b.[year]+1<=year(getdate()) to my join filters, but that doesn't seem to affect output at all. I also tried writing a where clause, that ended up with a case that made my head spin.

How can I prevent future dates from showing up in the end result?
Bonus question: Can I make my YTD calculation accept a 0 as a value for any lines added due to sales history?


问:
I got one button here which is submit, and i wanna remind the user to choose an answer with toast so where can i add it?
R.id.btn_submit ->{

if(mSelectedOptionPosition == 0){

mCurrentQuestion++

when{

mCurrentPosition <= mQuestionsList!!.size ->{

setQuestion()

}else ->{

Toast.makeText(this,

"You have successfully completed the quiz",

Toast.LENGTH_SHORT).show()

}

}

}else-> {

val question = mQuestionsList?.get(mCurrentPosition-1)

if (question!!.correctAnswer != mSelectedOptionPosition){

answerView(mSelectedOptionPosition, R.drawable.wrong_option_border_bg)

}

answerView(question.correctAnswer, R.drawable.correct_option_border_bg)

if(mCurrentPosition == mQuestionsList!!.size) {

btn_submit.text = "FINISH"

}else{

btn_submit.text = "Go to next question"

}

}

答:
When do you want to show toast ,you didn't specify clearly.
If you want the user to at least choose an option then simply set a check in the btn_submit clickListener that whether any option is chosen or not ,if not then you can show your toast.

Or you can simply show the toast in

```<code>    R.id.btn_submit ->{

    if(mSelectedOption == null)
    {
      showToast("your message")
    }
    else{

        if(mSelectedOptionPosition == 0){.....
    .
    .
    .
    .
    }
</code>```

this if block and check for it at the first when the block starts assuming if the mSelectedOption is null then no option is selected or else do the rest of the checking..

Body:
When do you want to show toast ,you didn't specify clearly.
If you want the user to at least choose an option then simply set a check in the btn_submit clickListener that whether any option is chosen or not ,if not then you can show your toast.

Or you can simply show the toast in

    R.id.btn_submit ->{

    if(mSelectedOption == null)
    {
      showToast("your message")
    }
    else{

        if(mSelectedOptionPosition == 0){.....
    .
    .
    .
    .
    }

this if block and check for it at the first when the block starts assuming if the mSelectedOption is null then no option is selected or else do the rest of the checking..


问:
How do you control variables in a python script using a separate python script?
I have a main python code with variables that I wish to control from a separate python script. I get a name error message and I am unsure how to resolve this. Has anyone encountered a similar challenge? How can I control the variable n from a separate python script?

```<code>from main import *
npart = 5

NameError                                 Traceback (most recent call last)
Input In [12], in <module>
----> 1 from main import *
      2 npart = 5

File ~/main.py:91, in <module>
     88 latmin = 45.977778
     89 latmax = 45.931389
---> 91 npart = n  # number of particles to be released
     92 for i in range(n):
     93     lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)

NameError: name 'n' is not defined
</code>```

The main code that I am trying to control looks like this.
main.py. Here I type in 5 so the code will run without error. I would like to call it a variable n here. In the separate code define n = 5 and reproduce the results.

```<code>import random
x = []
y = []

lonmin = -63.226111
lonmax = -63.229722
latmin = 45.977778
latmax = 45.931389

npart = 5  # number of particles to be released
for i in range(5):
    lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)
    x.append(lon)
    lat = latmin + random.uniform(0, 1)*(latmax-latmin)
    y.append(lat)

print(x, y)
</code>```

答:
If I understand what you're trying to do correctly, the error appears to be in your main.py file, you don't define the variable n.
You need to add n = 10, or whatever, to that file.

Update

I think what you want to do is import a function from main.py, rather than a variable. So it would look something like this:

in main.py:

```<code>def makeCalculations(n):
    x = []
    y = []
    for i in range(n):
        lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)
        lat = latmin + random.uniform(0, 1)*(latmax-latmin)
        x.append(lon)
        y.append(lat)
    return x,y
</code>```

in other python file:

```<code>from main import *
n = 5
x,y = makeCalculations(n)
</code>```

In general, it's a bad idea to use import * in your scripts, because it can lead to different things having the same name, causing confusing errors. To be safer I think you would be better off saying what you want to import from main.py explicitly:

```<code>from main import latmin, latmax #and any other variable you want
from main import makeCalculations #and any other function you want
</code>```

Body:
I have a main python code with variables that I wish to control from a separate python script. I get a name error message and I am unsure how to resolve this. Has anyone encountered a similar challenge? How can I control the variable n from a separate python script?

from main import *
npart = 5

NameError                                 Traceback (most recent call last)
Input In [12], in <module>
----> 1 from main import *
      2 npart = 5

File ~/main.py:91, in <module>
     88 latmin = 45.977778
     89 latmax = 45.931389
---> 91 npart = n  # number of particles to be released
     92 for i in range(n):
     93     lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)

NameError: name 'n' is not defined

The main code that I am trying to control looks like this.
main.py. Here I type in 5 so the code will run without error. I would like to call it a variable n here. In the separate code define n = 5 and reproduce the results.

import random
x = []
y = []

lonmin = -63.226111
lonmax = -63.229722
latmin = 45.977778
latmax = 45.931389

npart = 5  # number of particles to be released
for i in range(5):
    lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)
    x.append(lon)
    lat = latmin + random.uniform(0, 1)*(latmax-latmin)
    y.append(lat)

print(x, y)

Body:
If I understand what you're trying to do correctly, the error appears to be in your main.py file, you don't define the variable n.
You need to add n = 10, or whatever, to that file.

Update

I think what you want to do is import a function from main.py, rather than a variable. So it would look something like this:

in main.py:

def makeCalculations(n):
    x = []
    y = []
    for i in range(n):
        lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)
        lat = latmin + random.uniform(0, 1)*(latmax-latmin)
        x.append(lon)
        y.append(lat)
    return x,y

in other python file:

from main import *
n = 5
x,y = makeCalculations(n)

In general, it's a bad idea to use import * in your scripts, because it can lead to different things having the same name, causing confusing errors. To be safer I think you would be better off saying what you want to import from main.py explicitly:

from main import latmin, latmax #and any other variable you want
from main import makeCalculations #and any other function you want


问:
Directory Structure for MVC
I'm trying to clean up the framework I've been working on. Right now, the site consists of the following directories:

```<code>Models
Views
Controllers
Helpers (Miscellaneous functions)
Libraries (Universal classes, like library and session management)
Images
Style
</code>```

Any time a page is called, the router script looks up the associated controller, so thesite.com/login would instantiate Login_Controller at '/controllers/login.php' The problem I'm facing is, the router script itself feels like a type of controller, as does view.php, which handles formatting data to be handled by the appropriate view. But these aren't quite like page controllers, since they control the MVC itself. I'm still somewhat new to this architecture, and I'm curious how someone with more experience would organize this.

Could I classify the router and view controllers as libraries, or would it be better to create a subdirectory inside /controllers called 'pages', or any other ideas? Thanks so much.

答:
I could not edit @kta's answer because the edit queue is full, but that link may suffer from link rot soon. The Zend Framework website is going away and being replaced by the Laminas Project. Here is a summary of the original link:

The following describes the use cases for each directory as listed.

application/: This directory contains your application. It will house the MVC system, as well as configurations, services used, and your bootstrap file.

configs/: The application-wide configuration directory.

controllers/, models/, and views/: These directories serve as the default controller, model or view directories. Having these three directories inside the application directory provides the best layout for starting a simple project as well as starting a modular project that has global controllers/models/views.

controllers/helpers/: These directories will contain action helpers. Action helpers will be namespaced either as "Controller_Helper_" for the default module or "_Controller_Helper" in other modules.

layouts/: This layout directory is for MVC-based layouts. Since Zend_Layout is capable of MVC- and non-MVC-based layouts, the location of this directory reflects that layouts are not on a 1-to-1 relationship with controllers and are independent of templates within views/.

modules/: Modules allow a developer to group a set of related controllers into a logically organized group. The structure under the modules directory would resemble the structure under the application directory.

services/: This directory is for your application specific web-service files that are provided by your application, or for implementing a » Service Layer for your models.

Bootstrap.php: This file is the entry point for your application, and should implement Zend_Application_Bootstrap_Bootstrapper. The purpose for this file is to bootstrap the application and make components available to the application by initializing them.

data/: This directory provides a place to store application data that is volatile and possibly temporary. The disturbance of data in this directory might cause the application to fail. Also, the information in this directory may or may not be committed to a subversion repository. Examples of things in this directory are session files, cache files, sqlite databases, logs and indexes.

docs/: This directory contains documentation, either generated or directly authored.

library/: This directory is for common libraries on which the application depends, and should be on the PHP include_path. Developers should place their application's library code under this directory in a unique namespace, following the guidelines established in the PHP manual's » Userland Naming Guide, as well as those established by Zend itself. This directory may also include Zend Framework itself; if so, you would house it in library/Zend/.

public/: This directory contains all public files for your application. index.php sets up and invokes Zend_Application, which in turn invokes the application/Bootstrap.php file, resulting in dispatching the front controller. The web root of your web server would typically be set to this directory.

scripts/: This directory contains maintenance and/or build scripts. Such scripts might include command line, cron, or phing build scripts that are not executed at runtime but are part of the correct functioning of the application.

temp/: The temp/ folder is set aside for transient application data. This information would not typically be committed to the applications svn repository. If data under the temp/ directory were deleted, the application should be able to continue running with a possible decrease in performance until data is once again restored or recached.

tests/: This directory contains application tests. These could be hand-written, PHPUnit tests, Selenium-RC based tests or based on some other testing framework. By default, library code can be tested by mimicing the directory structure of your library/ directory. Additionally, functional tests for your application could be written mimicing the application/ directory structure (including the application subdirectory).

Title: Directory Structure for MVC

Body:
I'm trying to clean up the framework I've been working on. Right now, the site consists of the following directories:

Models
Views
Controllers
Helpers (Miscellaneous functions)
Libraries (Universal classes, like library and session management)
Images
Style

Any time a page is called, the router script looks up the associated controller, so thesite.com/login would instantiate Login_Controller at '/controllers/login.php' The problem I'm facing is, the router script itself feels like a type of controller, as does view.php, which handles formatting data to be handled by the appropriate view. But these aren't quite like page controllers, since they control the MVC itself. I'm still somewhat new to this architecture, and I'm curious how someone with more experience would organize this.

Could I classify the router and view controllers as libraries, or would it be better to create a subdirectory inside /controllers called 'pages', or any other ideas? Thanks so much.


问:
functional test for JavaScript
I really need your assistance.

I am developing a project and most of the code is written on JS (backbone.js and jquery).
Could you please recommend me a tool/framework for functional testing?

I don't think that qunit or Jasmine meet the requirements of functional testing.
I would like something like cucumber for Rails but which could handle a lot of JavaScript.

答:
If you consider using a framework for it, try JavascriptMVC:

http://javascriptmvc.com/

It does:

Unit testing

Functional testing

Code cleaning

Code generating

Dependency management

And uses jQuery as a backbone. It's typically useful for middle to large JavaScript projects.

Title: functional test for JavaScript


问:
add coloured dot in new column using dplyr
I want to add a colored dot in a new column based on the value of another column.

I have:

```<code>data <-
  tibble(
    one = rep("placeholder text",5),
    one_text = 0:4
  )
</code>```

and can create a new column with a coloured dot using:

```<code>black_dot <- "\U2B24"

data %>%
      flextable %>%
      compose( j = "one",
              value = as_paragraph(
                                  as_chunk(black_dot, props = fp_text(color = "red")
                                           )
                                ),
              part = "body")
</code>```

I want to pass in the values from column one_text, and have the corresponding colour coded circles in the final frame based on this logic

```<code>colour_choice = function(x){
  if (x == 0) {
    "green"
  } else if ( x >= 3) {
    "red"
  } else {
    "orange"
  }
}
</code>```

when I try:

```<code>data %>%
  flextable %>%
  compose( j = "one",
          value = as_paragraph(
                              as_chunk(black_dot, props = fp_text(color = colour_choice( ~ .one_text))
                                       )
                            ),
          part = "body")
</code>```

I get:

Is there a way to make it so that the cirlces are coloured accordingly?

packages

```<code>library(officedown)
library(knitr)
library(tidyverse)
library(flextable)
library(officer)
</code>```

答:
You can achieve this by vectorizing your colour_choice function:

```<code>colour_choice <- Vectorize(colour_choice)

data %>%
  flextable %>%
  compose( j = "one",
           value = as_paragraph(
             as_chunk(black_dot, props = fp_text(color = colour_choice(one_text))
             )
           ),
           part = "body")
</code>```

which yields

Body:
I want to add a colored dot in a new column based on the value of another column.

I have:

data <-
  tibble(
    one = rep("placeholder text",5),
    one_text = 0:4
  )

and can create a new column with a coloured dot using:

black_dot <- "\U2B24"

data %>%
      flextable %>%
      compose( j = "one",
              value = as_paragraph(
                                  as_chunk(black_dot, props = fp_text(color = "red")
                                           )
                                ),
              part = "body")

I want to pass in the values from column one_text, and have the corresponding colour coded circles in the final frame based on this logic

colour_choice = function(x){
  if (x == 0) {
    "green"
  } else if ( x >= 3) {
    "red"
  } else {
    "orange"
  }
}

when I try:

data %>%
  flextable %>%
  compose( j = "one",
          value = as_paragraph(
                              as_chunk(black_dot, props = fp_text(color = colour_choice( ~ .one_text))
                                       )
                            ),
          part = "body")

I get:

Is there a way to make it so that the cirlces are coloured accordingly?

packages

library(officedown)
library(knitr)
library(tidyverse)
library(flextable)
library(officer)

Body:
You can achieve this by vectorizing your colour_choice function:

colour_choice <- Vectorize(colour_choice)

data %>%
  flextable %>%
  compose( j = "one",
           value = as_paragraph(
             as_chunk(black_dot, props = fp_text(color = colour_choice(one_text))
             )
           ),
           part = "body")

which yields


问:
Multiple instance of producers sharing the same producer name
I have a REST API that pushes the inflow request to a Apache Pulsar topic. The producer has a name (say, "api-integration-producer"). As I run multiple instances of this service (typically in Kubernetes), the service fails to start, complaining, the producer with the name ("api-integration-producer") is already registered with the Pulsar broker.

So, this means, I cannot run multiple instances of the service with the producer that produces to the same topic, or, with a producer that that shares the same name. However, I have solved this problem by generating a random producer name (append a uuid to "api-integration-producer").

Does this have an impact on the exactly-once scenario? What is the right way to name & run the Pulsar producers?

答:
Random producer name is fine for most cases.

Something to think about:   https://www.splunk.com/en_us/blog/it/effectively-once-semantics-in-apache-pulsar.html

You have to choose access mode.

Are you using a partitioned or non-partitioned topic?

https://pulsar.apache.org/docs/en/concepts-messaging/#access-mode

https://github.com/apache/pulsar/wiki/PIP-68:-Exclusive-Producer


问:
jenkinsfile - How do I access custom properties in my pom.xml?
Let's say I have a custom property in my pom.xml set like this:

```<code><properties>
 <app>com.myProject.app</app>
</properties>
</code>```

How can I access it in my jenkinsfile?

This:

```<code>def pom = readMavenPom file: 'pom.xml'
def appName = pom.app
</code>```

returns

```<code>org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field org.apache.maven.model.Model app
</code>```

Thanks in advance!

答:
jenkins pipeline add this stage.
more see</p>
```<code>    stage('info')
    {
        steps
        {
            script
            {
                def version = sh script: 'mvn help:evaluate -Dexpression=project.version -q -DforceStdout', returnStdout: true
                def artifactId = sh script: 'mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout', returnStdout: true

            }

        }
    }
</code>```

Body:
Let's say I have a custom property in my pom.xml set like this:

<properties>
 <app>com.myProject.app</app>
</properties>

How can I access it in my jenkinsfile?

This:

def pom = readMavenPom file: 'pom.xml'
def appName = pom.app

returns

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field org.apache.maven.model.Model app

Thanks in advance!

Body:
jenkins pipeline add this stage.
more see

    stage('info')
    {
        steps
        {
            script
            {
                def version = sh script: 'mvn help:evaluate -Dexpression=project.version -q -DforceStdout', returnStdout: true
                def artifactId = sh script: 'mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout', returnStdout: true

            }

        }
    }


问:
Optimize R data.table code of a function inside an R package
I am trying to optimize a function that lives inside an R package that leverages on {data.table} code.

Motivation for question

I do not use {data.table} very often, although I do spend a significant amount of time reading the documentation when I am at it. Yet, I always struggle with {data.table}'s syntax, particularly when I have to deal with NSE. I did read Programming on data.table
, and other vignettes.

I am confident that for an experienced {data.table} user the code that follows next can be straightforwardly optimized, made more terse, and readable, by making a better use of idiomatic {data.table} code. But I do not know how. Hence my question. I will be specific about the places in the code where I think there might be another way of writing it (I hope you don't judge this as an open-ended question about optimization).

Conceptual problem

I have this function find_overlap() (full code down below) that takes a data frame df (millions of rows), two numerical intervals/ranges (time_range and speed_range), and a set of column names to be operated on (time_col, speed_col, lon_col, lat_col). All these columns indicated by these names are of type numeric.

Essentially, for each observation i of the data frame df, i.e.., a point in space and time, I would like to iterate over a subset of other points also in df and find the closest point to i. The subset is defined by two conditions:

Points (observations) must fall in a time range (time_range, a two-element vector with lower and upper bounds). This is a relative time range, not an absolute one. The actual absolute range is calculated by adding the time of observation i --- saved in variables t_lower and t_upper.

Points (observations) must fall in a speed range.

At the end I want to return the data frame (a data table really) updated, i.e., including two extra columns:

arg_min_dist: an index of the found closest observation/point, or NA if none found

min_dist: the distance

{data.table} optimization questions

At the beginning of the function, I create an index column in dt[['..id..']] <- seq.int(nrow(dt)). The objective is to have a way of keeping track of the identity of the observation corresponding to the closest point, so that I can return it in arg_min_dist. This feels not ideal, I suspect there might be a way of extracting a row id without having to explicitly create the row index myself, i.e. along the lines of dplyr::row_number().

The column whose name is in time_col will correspond to a column with timings, namely a simple numeric variable (it is not a date or time object), and the data frame will be sorted by this column. I am adding a key based on this column in data.table::setkeyv(dt, c(time_col)). Is this advantageous or by being already sorted the data table at this point am I incurring in an expensive operation with no added benefit?

Next, I am having an explicit for loop, where for each observation i, I subset the data table and find the closest point. I am guessing there might be a way of instructing {data.table} to do it instead, which will be faster and akin to {data.table}'s parallelization based on threads.

The sub-setting itself in:

```<code>      dt_subset <-
        dt[dt[[time_col]] >= t_lower[i] &
             dt[[time_col]] < t_upper[i] &
             dt[[speed_col]] >= speed_range[1] &
             dt[[speed_col]] < speed_range[2], c('..id..', lon_col, lat_col), with = FALSE]
</code>```

raises a few questions.

Are dt[[time_col]] and dt[[speed_col]] generating a copy of each of those columns, and not working by reference? Also, I wonder if swapping >= and < with {data table}'s %between% would be faster.

Then the part where I actually calculate the distance between points with the function spDistsN1(), and find the minimum distance, probably all that could be fit into a single function that would return only the two columns of interest arg_min_dist and min_dist. I know that {data.table}'s j argument accepts expressions, not only column selection.

```<code>      if (nrow(dt_subset) > 0) {
        distances <- spDistsN1(pt_x = dt[[lon_col]][i],
                               pt_y = dt[[lat_col]][i],
                               pts_x = dt_subset[[lon_col]],
                               pts_y = dt_subset[[lat_col]],
                               longlat = TRUE)

        iii <- which.min(distances)
        if (length(iii) > 0) {
          arg_min_dist[i] <- dt_subset[iii, '..id..']
          min_dist[i] <- distances[iii]
        }
      }
</code>```

Having such j expression would also save me from performing that cbind() at the end.

Note about MWE

I am not including a MWE because the function spDistsN1() is compiled. If you find it really necessary I can adapt the code at that point so that it runs, but I believe my questions are well illustrated with the code as is.

find_overlap()

```<code>find_overlap <-
  function(df,
           time_range,
           speed_range,
           time_col = 'DATE',
           speed_col = 'SPE',
           lon_col = 'LON',
           lat_col = 'LAT') {

    n_row <- nrow(df)
    # dt <- setup_dt(df, time_col = time_col)
    dt <- data.table::as.data.table(df)
    dt[['..id..']] <- seq.int(nrow(dt))
    data.table::setkeyv(dt, c(time_col))

    t_lower <- as.data.frame(dt[ , time_col, with = FALSE])[, 1] + time_range[1]
    t_upper <- as.data.frame(dt[ , time_col, with = FALSE])[, 1] + time_range[2]

    arg_min_dist <- rep(NA_integer_, length = n_row)
    min_dist <- rep(NA_real_, length = n_row)

    for (i in seq_len(n_row)) {

      dt_subset <-
        dt[dt[[time_col]] >= t_lower[i] &
             dt[[time_col]] < t_upper[i] &
             dt[[speed_col]] >= speed_range[1] &
             dt[[speed_col]] < speed_range[2], c('..id..', lon_col, lat_col), with = FALSE]

      if (nrow(dt_subset) > 0) {
        distances <- spDistsN1(pt_x = dt[[lon_col]][i],
                               pt_y = dt[[lat_col]][i],
                               pts_x = dt_subset[[lon_col]],
                               pts_y = dt_subset[[lat_col]],
                               longlat = TRUE)

        iii <- which.min(distances)
        if (length(iii) > 0) {
          arg_min_dist[i] <- dt_subset[iii, '..id..']
          min_dist[i] <- distances[iii]
        }
      }
    }

    return(cbind(dt, arg_min_dist, min_dist))

  }
</code>```

答:
This may help you.

I define a data.table as below, which may or may not be close to the structure that you have

```<code>dt=data.table(
  DATE=sample(seq(as.IDate('2020-01-01'), as.IDate("2022-12-31"), length.out=10000), 1000),
  SPE = sample(seq(1,50, length.out=10000), 1000),
  LAT = sample(seq(-100,100, length.out=10000), 1000),
  LON = sample(seq(-100,100, length.out=10000), 1000)
)
</code>```

I define a function that is similar to yours, but tries to address your questions re (2)(3)(4), above. Note that for illustrative purposes, I'm treating the LAT, LON values like simple points in the coordinate plane (see my simple distance calculation)

```<code>find_overlap <-function(
  df, time_range,speed_range,time_col = DATE,speed_col = SPE,x = LAT,y = LON) {

  ixcol = paste0("i.", substitute(x))
  iycol = paste0("i.", substitute(y))

  # create the id and the lower and upper bounds
  eval(substitute(
    df[,`:=`(
      id=.I,
      tlower=time_col+time_range[1],tupper=time_col+time_range[2],
      slower=speed_col+speed_range[1],supper=speed_col+speed_range[2])]
  ))

  # merge df on itself, using no-equi join and rename cols as needed
  sdf =eval(substitute(
    df[df, on=.(
      time_col>=tlower,time_col<=tupper,
      speed_col>=slower,speed_col<=supper
    )][, .(time_col, speed_col, x, y, id,close_id = i.id,close_x = get(ixcol),close_y = get(iycol))]
  ))

  # get the distance
  eval(substitute(
    sdf[,distance:=sqrt((x-close_x)^2  + (y-close_y)^2)]
  ))

  # get the datatable with the closest id
  sdf <- sdf[order(id,distance)][id!=close_id][,.SD[1], by=id][,.(id,closest = close_id, distance)]

  # merge back on original
  sdf[df[,.(id)], on=.(id)]
}
</code>```

Example usage - here, time_range and speed_range are given in relative terms. I.e. we are restricting points that are within +- 3 days and +- 4 speed units

```<code>find_overlap(dt, c(-3,3), c(-4,4))
</code>```

Output:

```<code>        id closest   distance
   1:    1      NA         NA
   2:    2     437  20.212474
   3:    3     911   6.023127
   4:    4     307  36.567841
   5:    5     438 181.974809
  ---
 996:  996     483 162.941772
 997:  997     956 154.148418
 998:  998     707  78.425606
 999:  999      14  76.611228
1000: 1000     725  91.395353
</code>```

Body:
I am trying to optimize a function that lives inside an R package that leverages on {data.table} code.

Motivation for question

I do not use {data.table} very often, although I do spend a significant amount of time reading the documentation when I am at it. Yet, I always struggle with {data.table}'s syntax, particularly when I have to deal with NSE. I did read Programming on data.table
, and other vignettes.

I am confident that for an experienced {data.table} user the code that follows next can be straightforwardly optimized, made more terse, and readable, by making a better use of idiomatic {data.table} code. But I do not know how. Hence my question. I will be specific about the places in the code where I think there might be another way of writing it (I hope you don't judge this as an open-ended question about optimization).

Conceptual problem

I have this function find_overlap() (full code down below) that takes a data frame df (millions of rows), two numerical intervals/ranges (time_range and speed_range), and a set of column names to be operated on (time_col, speed_col, lon_col, lat_col). All these columns indicated by these names are of type numeric.

Essentially, for each observation i of the data frame df, i.e.., a point in space and time, I would like to iterate over a subset of other points also in df and find the closest point to i. The subset is defined by two conditions:

Points (observations) must fall in a time range (time_range, a two-element vector with lower and upper bounds). This is a relative time range, not an absolute one. The actual absolute range is calculated by adding the time of observation i --- saved in variables t_lower and t_upper.

Points (observations) must fall in a speed range.

At the end I want to return the data frame (a data table really) updated, i.e., including two extra columns:

arg_min_dist: an index of the found closest observation/point, or NA if none found

min_dist: the distance

{data.table} optimization questions

At the beginning of the function, I create an index column in dt[['..id..']] <- seq.int(nrow(dt)). The objective is to have a way of keeping track of the identity of the observation corresponding to the closest point, so that I can return it in arg_min_dist. This feels not ideal, I suspect there might be a way of extracting a row id without having to explicitly create the row index myself, i.e. along the lines of dplyr::row_number().

The column whose name is in time_col will correspond to a column with timings, namely a simple numeric variable (it is not a date or time object), and the data frame will be sorted by this column. I am adding a key based on this column in data.table::setkeyv(dt, c(time_col)). Is this advantageous or by being already sorted the data table at this point am I incurring in an expensive operation with no added benefit?

Next, I am having an explicit for loop, where for each observation i, I subset the data table and find the closest point. I am guessing there might be a way of instructing {data.table} to do it instead, which will be faster and akin to {data.table}'s parallelization based on threads.

The sub-setting itself in:

      dt_subset <-
        dt[dt[[time_col]] >= t_lower[i] &
             dt[[time_col]] < t_upper[i] &
             dt[[speed_col]] >= speed_range[1] &
             dt[[speed_col]] < speed_range[2], c('..id..', lon_col, lat_col), with = FALSE]

raises a few questions.

Are dt[[time_col]] and dt[[speed_col]] generating a copy of each of those columns, and not working by reference? Also, I wonder if swapping >= and < with {data table}'s %between% would be faster.

Then the part where I actually calculate the distance between points with the function spDistsN1(), and find the minimum distance, probably all that could be fit into a single function that would return only the two columns of interest arg_min_dist and min_dist. I know that {data.table}'s j argument accepts expressions, not only column selection.

      if (nrow(dt_subset) > 0) {
        distances <- spDistsN1(pt_x = dt[[lon_col]][i],
                               pt_y = dt[[lat_col]][i],
                               pts_x = dt_subset[[lon_col]],
                               pts_y = dt_subset[[lat_col]],
                               longlat = TRUE)

        iii <- which.min(distances)
        if (length(iii) > 0) {
          arg_min_dist[i] <- dt_subset[iii, '..id..']
          min_dist[i] <- distances[iii]
        }
      }

Having such j expression would also save me from performing that cbind() at the end.

Note about MWE

I am not including a MWE because the function spDistsN1() is compiled. If you find it really necessary I can adapt the code at that point so that it runs, but I believe my questions are well illustrated with the code as is.

find_overlap()

find_overlap <-
  function(df,
           time_range,
           speed_range,
           time_col = 'DATE',
           speed_col = 'SPE',
           lon_col = 'LON',
           lat_col = 'LAT') {

    n_row <- nrow(df)
    # dt <- setup_dt(df, time_col = time_col)
    dt <- data.table::as.data.table(df)
    dt[['..id..']] <- seq.int(nrow(dt))
    data.table::setkeyv(dt, c(time_col))

    t_lower <- as.data.frame(dt[ , time_col, with = FALSE])[, 1] + time_range[1]
    t_upper <- as.data.frame(dt[ , time_col, with = FALSE])[, 1] + time_range[2]

    arg_min_dist <- rep(NA_integer_, length = n_row)
    min_dist <- rep(NA_real_, length = n_row)

    for (i in seq_len(n_row)) {

      dt_subset <-
        dt[dt[[time_col]] >= t_lower[i] &
             dt[[time_col]] < t_upper[i] &
             dt[[speed_col]] >= speed_range[1] &
             dt[[speed_col]] < speed_range[2], c('..id..', lon_col, lat_col), with = FALSE]

      if (nrow(dt_subset) > 0) {
        distances <- spDistsN1(pt_x = dt[[lon_col]][i],
                               pt_y = dt[[lat_col]][i],
                               pts_x = dt_subset[[lon_col]],
                               pts_y = dt_subset[[lat_col]],
                               longlat = TRUE)

        iii <- which.min(distances)
        if (length(iii) > 0) {
          arg_min_dist[i] <- dt_subset[iii, '..id..']
          min_dist[i] <- distances[iii]
        }
      }
    }

    return(cbind(dt, arg_min_dist, min_dist))

  }

Body:
This may help you.

I define a data.table as below, which may or may not be close to the structure that you have

dt=data.table(
  DATE=sample(seq(as.IDate('2020-01-01'), as.IDate("2022-12-31"), length.out=10000), 1000),
  SPE = sample(seq(1,50, length.out=10000), 1000),
  LAT = sample(seq(-100,100, length.out=10000), 1000),
  LON = sample(seq(-100,100, length.out=10000), 1000)
)

I define a function that is similar to yours, but tries to address your questions re (2)(3)(4), above. Note that for illustrative purposes, I'm treating the LAT, LON values like simple points in the coordinate plane (see my simple distance calculation)

find_overlap <-function(
  df, time_range,speed_range,time_col = DATE,speed_col = SPE,x = LAT,y = LON) {

  ixcol = paste0("i.", substitute(x))
  iycol = paste0("i.", substitute(y))

  # create the id and the lower and upper bounds
  eval(substitute(
    df[,`:=`(
      id=.I,
      tlower=time_col+time_range[1],tupper=time_col+time_range[2],
      slower=speed_col+speed_range[1],supper=speed_col+speed_range[2])]
  ))

  # merge df on itself, using no-equi join and rename cols as needed
  sdf =eval(substitute(
    df[df, on=.(
      time_col>=tlower,time_col<=tupper,
      speed_col>=slower,speed_col<=supper
    )][, .(time_col, speed_col, x, y, id,close_id = i.id,close_x = get(ixcol),close_y = get(iycol))]
  ))

  # get the distance
  eval(substitute(
    sdf[,distance:=sqrt((x-close_x)^2  + (y-close_y)^2)]
  ))

  # get the datatable with the closest id
  sdf <- sdf[order(id,distance)][id!=close_id][,.SD[1], by=id][,.(id,closest = close_id, distance)]

  # merge back on original
  sdf[df[,.(id)], on=.(id)]
}

Example usage - here, time_range and speed_range are given in relative terms. I.e. we are restricting points that are within +- 3 days and +- 4 speed units

find_overlap(dt, c(-3,3), c(-4,4))

Output:

        id closest   distance
   1:    1      NA         NA
   2:    2     437  20.212474
   3:    3     911   6.023127
   4:    4     307  36.567841
   5:    5     438 181.974809
  ---
 996:  996     483 162.941772
 997:  997     956 154.148418
 998:  998     707  78.425606
 999:  999      14  76.611228
1000: 1000     725  91.395353


问:
ROR: NoMethodError in Home#index
I'm learning Ruby on Rails and as part of practise I'm building a Bug Tracker System, which has a Manager, Developer and QA.

I want to display all the projects the Manager has created on his Home Screen. These proejcts are present in a table projects.

In my manager_controller, I have this code:

```<code>class ManagerController < ApplicationController
  def index
    @projects = Project.all
  end

  def create
  end
end
</code>```

And this is my index.html.erb in views/manager:

```<code><div class="container">
  <h1>Manager's Feed</h1>
  <p>Hello <%=current_user.username%></p>

  <%= link_to "Create Project", new_project_path, :class => "btn btn-success"%>

  <table id='employee-table' class="table table-hover">
    <thead  class="thead-light">
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th colspan="2"></th>
      </tr>
    </thead>

    <tbody>
      <% @projects.each do |project| %>
        <tr>
          <td><%= project.id %></td>
          <td><%= project.title %></td>
        </tr>
      <% end %>
    </tbody>
  </table>

  <div>
    <%= link_to "Logout", destroy_user_session_path, :method => :delete %>
  </div>
</div>
</code>```

But this is giving me following error:

I'm unable to see why @projects is Null as I had defined it in my controller. Can anyone help me in fixing this problem?

Update 1
My routes.rb file:

```<code>Rails.application.routes.draw do
  get 'project/show'
  resources 'project'
  resources 'manager'
  resources 'developer'
  resources 'qa'

  devise_for :users
  get 'home/index'
  root to: "home#index"
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
</code>```

HomeController:

```<code>class HomeController < ApplicationController
  before_action :authenticate_user!

  def index
    @projects = Project.all
    if current_user.manager?
      render '../views/manager/index.html.erb'
    end
    if current_user.developer?
      render '../views/developer/index.html.erb'
    end
    if current_user.quality_assurance?
      render '../views/qa/index.html.erb'
    end
  end
end
</code>```

答:
On you stack you can read at the bottom app/controllers/home_controller.rb

You're initialising @projects on managers_controller.rb.

Use this on the correct controller.

class HomeController < ApplicationController
  def index
    @projects = Project.all
  end
end

```
<p>Your default route is defined by <code>root to: "home#index"</code> with leads to the <code>HomeController#index</code>. Over there, you're using <code>render</code> which simply "display" the content. I would suggest to use <code>redirect_to</code> to redirect the flow to the correct controller with something like:</p>
```class HomeController < ApplicationController
  before_action :authenticate_user!

  def index
    @projects = Project.all
    if current_user.manager?
      redirect_to managers_path
    end
    if current_user.developer?
      redirect_to developers_path
    end
    if current_user.quality_assurance?
      redirect_to qas_path
    end
  end
end
```

You can find all *_paths values I used running rails routes.

Title: ROR: NoMethodError in Home#index

Body:
I'm learning Ruby on Rails and as part of practise I'm building a Bug Tracker System, which has a Manager, Developer and QA.

I want to display all the projects the Manager has created on his Home Screen. These proejcts are present in a table projects.

In my manager_controller, I have this code:

class ManagerController < ApplicationController
  def index
    @projects = Project.all
  end

  def create
  end
end

And this is my index.html.erb in views/manager:

Manager's Feed

Hello <%=current_user.username%>

  <%= link_to "Create Project", new_project_path, :class => "btn btn-success"%>

        ID
        Title

      <% @projects.each do |project| %>

          <%= project.id %>
          <%= project.title %>

      <% end %>

    <%= link_to "Logout", destroy_user_session_path, :method => :delete %>

But this is giving me following error:

I'm unable to see why @projects is Null as I had defined it in my controller. Can anyone help me in fixing this problem?

Update 1
My routes.rb file:

Rails.application.routes.draw do
  get 'project/show'
  resources 'project'
  resources 'manager'
  resources 'developer'
  resources 'qa'

  devise_for :users
  get 'home/index'
  root to: "home#index"
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

HomeController:

class HomeController < ApplicationController
  before_action :authenticate_user!

  def index
    @projects = Project.all
    if current_user.manager?
      render '../views/manager/index.html.erb'
    end
    if current_user.developer?
      render '../views/developer/index.html.erb'
    end
    if current_user.quality_assurance?
      render '../views/qa/index.html.erb'
    end
  end
end

Body:
On you stack you can read at the bottom app/controllers/home_controller.rb

You're initialising @projects on managers_controller.rb.

Use this on the correct controller.

class HomeController < ApplicationController
  def index
    @projects = Project.all
  end
end

Your default route is defined by root to: "home#index" with leads to the HomeController#index. Over there, you're using render which simply "display" the content. I would suggest to use redirect_to to redirect the flow to the correct controller with something like:

class HomeController < ApplicationController
  before_action :authenticate_user!

  def index
    @projects = Project.all
    if current_user.manager?
      redirect_to managers_path
    end
    if current_user.developer?
      redirect_to developers_path
    end
    if current_user.quality_assurance?
      redirect_to qas_path
    end
  end
end

You can find all *_paths values I used running rails routes.


问:
How to open A-Frame inspector programmatically when the page loads
I need to open the inspector automatically when the page loads.</p>

答:
You can invoke the openInspector function manually after a-scene loads:

```<code>var sceneEl = document.querySelector('a-scene');
  sceneEl.addEventListener('loaded', function () {
    sceneEl.components.inspector.openInspector();
 });
</code>```

Working example:

https://glitch.com/edit/#!/brawny-candle-shrine?path=index.html%3A17%3A50

Body:
You can invoke the openInspector function manually after a-scene loads:

var sceneEl = document.querySelector('a-scene');
  sceneEl.addEventListener('loaded', function () {
    sceneEl.components.inspector.openInspector();
 });

Working example:

https://glitch.com/edit/#!/brawny-candle-shrine?path=index.html%3A17%3A50


问:
React NextJS page navigation with tabs - display not updating correctly
I'm attempting to navigate between pages using tabs:

```<code>import * as React from 'react'
import Box from '@mui/material/Box'
import Tabs from '@mui/material/Tabs'
import Tab from '@mui/material/Tab'
import {useState, useEffect} from 'react'
import { useRouter } from 'next/router'

const LinkTab = (props) =>
{
  const router = useRouter()

  const handleTabChange = (e) =>
  {
    e.preventDefault()
    router.push(e.target.href)
  }

  return (
    <Tab
      component = 'a'
      onClick = {e => handleTabChange(e)}
      {...props} />
  )
}

const NavTabs = () =>
{
  const pages = ['/', '/two', '/three']
  const [value, setValue]  =  useState(0)

  const handleChange  =  (e, v)  =>
  {
    setValue(v)
  }

  return (
    <Box sx = {{width: '100%'}}>
      <Tabs value = {value} onChange = {(e, v) => handleChange(e, v)} centered>
        <LinkTab label = 'Page One' href = {pages[0]} />
        <LinkTab label = 'Page Two' href = {pages[1]} />
        <LinkTab label = 'Page Three' href = {pages[2]} />
      </Tabs>
    </Box>
  );
}

export default NavTabs
</code>```

This works in terms of navigation - clicking a tab takes you to the expected page.

But the selected tab doesn't update correctly on the actual display.

Related error message (doesn't cause a crash but shows in console):

next-dev.js?3515:32 MUI: The value provided to the Tabs component is invalid.
The Tab with this value ("0") is not part of the document layout.
Make sure the tab item is present in the document or that it's not display: none.

When the site first loads, Page One is the home page and is also correctly shown as selected. If I click on Page Two I navigate there right away, but I have to click on it again to actually have the tab display update to show that page as selected. And then if I click on Page Three, I'll again navigate there correctly, but the display will go back to showing Page One as selected.

I think this has something to do with when/where I call e.preventDefault() and the fact that state is being initiated with 0 for the first page. But I'm new to React, so I'm not exactly sure what I've done wrong.

The code above is modified from the MUI example found here. Implementing the example code exactly as is correctly updates the display, but doesn't actually navigate, so I had to make some changes to use the router.

The NavTabs component is part of an AppBar component.

答:
One thing missing in your code is the fact that you are always setting your value as 0 initially. Whereas it should be dependent on the page you are at

Modify your NavTabs component like this:

```<code>const router = useRouter();
  const [value, setValue] = useState(pages.indexOf(router.route));
</code>```

router will give you the route and you can use it. The above example is basic and does not account for cases when pages does not include your route.

Body:
I'm attempting to navigate between pages using tabs:

import * as React from 'react'
import Box from '@mui/material/Box'
import Tabs from '@mui/material/Tabs'
import Tab from '@mui/material/Tab'
import {useState, useEffect} from 'react'
import { useRouter } from 'next/router'

const LinkTab = (props) =>
{
  const router = useRouter()

  const handleTabChange = (e) =>
  {
    e.preventDefault()
    router.push(e.target.href)
  }

  return (
    <Tab
      component = 'a'
      onClick = {e => handleTabChange(e)}
      {...props} />
  )
}

const NavTabs = () =>
{
  const pages = ['/', '/two', '/three']
  const [value, setValue]  =  useState(0)

  const handleChange  =  (e, v)  =>
  {
    setValue(v)
  }

  return (
    <Box sx = {{width: '100%'}}>
      <Tabs value = {value} onChange = {(e, v) => handleChange(e, v)} centered>
        <LinkTab label = 'Page One' href = {pages[0]} />
        <LinkTab label = 'Page Two' href = {pages[1]} />
        <LinkTab label = 'Page Three' href = {pages[2]} />
      </Tabs>
    </Box>
  );
}

export default NavTabs

This works in terms of navigation - clicking a tab takes you to the expected page.

But the selected tab doesn't update correctly on the actual display.

Related error message (doesn't cause a crash but shows in console):

next-dev.js?3515:32 MUI: The value provided to the Tabs component is invalid.
The Tab with this value ("0") is not part of the document layout.
Make sure the tab item is present in the document or that it's not display: none.

When the site first loads, Page One is the home page and is also correctly shown as selected. If I click on Page Two I navigate there right away, but I have to click on it again to actually have the tab display update to show that page as selected. And then if I click on Page Three, I'll again navigate there correctly, but the display will go back to showing Page One as selected.

I think this has something to do with when/where I call e.preventDefault() and the fact that state is being initiated with 0 for the first page. But I'm new to React, so I'm not exactly sure what I've done wrong.

The code above is modified from the MUI example found here. Implementing the example code exactly as is correctly updates the display, but doesn't actually navigate, so I had to make some changes to use the router.

The NavTabs component is part of an AppBar component.

Body:
One thing missing in your code is the fact that you are always setting your value as 0 initially. Whereas it should be dependent on the page you are at

Modify your NavTabs component like this:

const router = useRouter();
  const [value, setValue] = useState(pages.indexOf(router.route));

router will give you the route and you can use it. The above example is basic and does not account for cases when pages does not include your route.


问:
on-prem server and connect the node with the integration runtime in Azure
I wanted to pull the data from my on-prem server ( hive or oracle ) to Azure data factory. Whereas i am facing issues can you help me in this?

I am asking this on the basis of enterprise issue. I wanted my integration Runtime to be in Onprem server , currently we are installing it in our own laptops and if our laptop is shut down then obviously IR is stopped and data won't be loaded this can't be feasible in production.

Do anybody know that what is meant installing IR in my on prem server? that means in my hive server?

Your help will be really appreciated.

答:
Your SHIR server does not have to be on the same server as your data source. But it should be close to it. Same region or same data center.

You need a server that is always powered and running. Refer to the documentation.

If you want high availability you should refer to this link.

If you want DR, you will need another SHIR on a DR server in your secondary region.

You can also install the SHIR onto a VM running on the cloud. But your Onprem network needs to be connect to the Cloud VNET using Express route or a VPN.

Laptops is fine for testing but as you said, not for production.

Your IT team should also take care of the patching and updates/maintenance of the new server whether it is on prem or on cloud.


答:
Narrow the list of relevant rows prior to doing the full join.

```<code>with A as (
    select *
    from tableA
    where ...
), B as (
    select *
    from tableB
    where ...
)
select * from A full outer join B on ...
</code>```

You could also just do this inline:

```<code>select *
from
    (select * from tableA where ...) as A
    full outer join
    (select * from tableB where ...) as B
</code>```

EDIT: If you "pre-filter" the data within relevant dates you don't need to do the awkward coalesced checks later:

```<code>with A as (
    select year, month, account, sales
    from yourtable
    -- if there's no future data then this whole cte may be unnecessary
    where year < year(getdate())
       or year = year(getdate()) and month <= month(getdate())
), B as (
    select year + 1 as year, month, account, sales
    from yourtable
    where year < year(getdate()) - 1
       or year = year(getdate()) - 1 and month <= month(getdate())
)
select
    coalesce(a.year, b.year) [Year]
  , coalesce(a.Month, b.Month) [Month]
  , coalesce(a.account, b.account) [Account]
  , sum(a.sales) over (Partition by a.account, a.year order by a.month) [Account Sales YTD]
from A full outer join B
    on  a.account = b.account
    and a.month = b.month
    and a.year = b.year
order by 1, 2
</code>```

https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=26c30b190d475d8679f2253a3c428f1f

Title: How to limit a full join by date

Body:
Narrow the list of relevant rows prior to doing the full join.

with A as (
    select *
    from tableA
    where ...
), B as (
    select *
    from tableB
    where ...
)
select * from A full outer join B on ...

You could also just do this inline:

select *
from
    (select * from tableA where ...) as A
    full outer join
    (select * from tableB where ...) as B

EDIT: If you "pre-filter" the data within relevant dates you don't need to do the awkward coalesced checks later:

with A as (
    select year, month, account, sales
    from yourtable
    -- if there's no future data then this whole cte may be unnecessary
    where year < year(getdate())
       or year = year(getdate()) and month <= month(getdate())
), B as (
    select year + 1 as year, month, account, sales
    from yourtable
    where year < year(getdate()) - 1
       or year = year(getdate()) - 1 and month <= month(getdate())
)
select
    coalesce(a.year, b.year) [Year]
  , coalesce(a.Month, b.Month) [Month]
  , coalesce(a.account, b.account) [Account]
  , sum(a.sales) over (Partition by a.account, a.year order by a.month) [Account Sales YTD]
from A full outer join B
    on  a.account = b.account
    and a.month = b.month
    and a.year = b.year
order by 1, 2

https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=26c30b190d475d8679f2253a3c428f1f


问:
Parents and siblings in query in XCTest (UI testing)
In other languages is possible to make such query:

```<code>class:B text:"text_I_looking_for" sibling class:C
</code>```

or

```<code>class:B text:"text_I_looking_for" parent class:A child class:C
</code>```

How to perform such query in XCTest? I need find element to
1. Check if it's present
2. Click it.

PS I know XCTest has simply syntax, but in some cases it's not enough solution. Maybe it's possible to use NSPredicate syntax?

答:
.containingType was obsoleted in Swift 3. You can use .containing instead (I'm on Xcode 13):</p>
```<code>XCUIApplication().otherElements.containing(.image, identifier: "circle").staticTexts["3"]
</code>```

Body:
In other languages is possible to make such query:

class:B text:"text_I_looking_for" sibling class:C

or

class:B text:"text_I_looking_for" parent class:A child class:C

How to perform such query in XCTest? I need find element to
1. Check if it's present
2. Click it.

PS I know XCTest has simply syntax, but in some cases it's not enough solution. Maybe it's possible to use NSPredicate syntax?

Body:
.containingType was obsoleted in Swift 3. You can use .containing instead (I'm on Xcode 13):

XCUIApplication().otherElements.containing(.image, identifier: "circle").staticTexts["3"]


问:
Periodically Refresh a Database in Laravel for Dev/Staging Server
I have a system built in Laravel 8, hosted by DigitalOcean and deployed using GitLab and Forge. I have three branches, dev/staging/master that are linked to various domains, separately controlled by Forge.

For the dev site, I want to reset the database regularly to the raw seed value. I could just run a CRON job on the server of course, but is there a best practise way of doing this, or some inbuilt Laravel functionality, that I can or should use?

答: Cron is still well suited for this job. Nothing wrong it. You could put it in Laravel's schedule if you wish, which is still run by cron :)</p>


问:
How to find any 10% drop for a certain period?
This task is overwhelming for me.
I have a db with :

```<code>subject  date value
A        UNIX  6
B        UNIX  2
D        UNIX  4
A        UNIX  7
B        UNIX  9
</code>```

Where each subject is a different time series with all dates of the year and values. (so each subject contain all unix dates)

I need to find for subject A and C, when did they dropped 10% in value.
or:

during 2020 find when A or C fall 10% in value

I would usually use lag with a window like:

```<code>LAG(value,5) OVER (PARTITION BY name ORDER BY date_num)
</code>```

but this will help to find a slop based on a certain window.

I need to find the 10% slop on any possible window between certain dates, and get the first time we have a 10% drop (in case it kept falling to 20%).

答:
```<code>select yt2.subject, min(yt2.date)
from yourtable yt1
join yourtable yt2
on yt1.subject = yt2.subject and
   yt1.date < yt2.date and
   0.9 * yt1.value >= yt2.value
left join yourtable nonexistent
on yt1.subject = nonexistent.subject and
   yt1.date < nonexistent.date and
   nonexistent.date < yt2.date
where yt1.subject in ('A', 'C') and
      nonexistent.subject is null
group by y2.subject;
</code>```

Explanation:

we join yt1 and yt2 to have pairs of the same subject where 10% of the value dropped

we also join a hypothetical record, called nonexistent that has the same subject and whose date is between the date of yt1 and yt2, to see whether there is any change between the two

in the where clause we ensure that nonexistent is nonexistent indeed

we also ensure that the subject is in the set we are interested about

we group by y2.subject to get the separate values and aggregate in the select clause accordingly

Body:
This task is overwhelming for me.
I have a db with :

subject  date value
A        UNIX  6
B        UNIX  2
D        UNIX  4
A        UNIX  7
B        UNIX  9

Where each subject is a different time series with all dates of the year and values. (so each subject contain all unix dates)

I need to find for subject A and C, when did they dropped 10% in value.
or:

during 2020 find when A or C fall 10% in value

I would usually use lag with a window like:

LAG(value,5) OVER (PARTITION BY name ORDER BY date_num)

but this will help to find a slop based on a certain window.

I need to find the 10% slop on any possible window between certain dates, and get the first time we have a 10% drop (in case it kept falling to 20%).

Body:
select yt2.subject, min(yt2.date)
from yourtable yt1
join yourtable yt2
on yt1.subject = yt2.subject and
   yt1.date < yt2.date and
   0.9 * yt1.value >= yt2.value
left join yourtable nonexistent
on yt1.subject = nonexistent.subject and
   yt1.date < nonexistent.date and
   nonexistent.date < yt2.date
where yt1.subject in ('A', 'C') and
      nonexistent.subject is null
group by y2.subject;

Explanation:

we join yt1 and yt2 to have pairs of the same subject where 10% of the value dropped

we also join a hypothetical record, called nonexistent that has the same subject and whose date is between the date of yt1 and yt2, to see whether there is any change between the two

in the where clause we ensure that nonexistent is nonexistent indeed

we also ensure that the subject is in the set we are interested about

we group by y2.subject to get the separate values and aggregate in the select clause accordingly


问:
Create multiple database instances via Firebase CLI
I am looking into automating the deployment of a project that is made up of multiple functions that are triggers on multiple realtime database instances.

Using firebase deploy allows you to deploy both functions and database rules.
I have also created targets so i can deploy different rules for different database instances.

The only missing part of my automation is actually creating those different database instances via the Firebase CLI tool; Since deploying a trigger function to a specific database that doesn't exist will fail. Ideally i would like to make sure to create those database instances if they don't exist and then continue my deployment.

Is there a way to create different database instances via the CLI ?

答:
You can Create realtime database instance by firebase CLI using the below command

firebase database:instances:create -P <alias_or_project_id> <DBinstanceName>

This Command work fine if you have paid plan.

For Free Plan it throw error:- FirebaseError: HTTP Error: 400, Precondition check failed.

Note : <DBinstanceName> should be alpha-numeric with hyphens.


问:
Problem in getting all urls in a page using regex ?
I have a webpage source code stored in $page and I need to extract all urls from it

the problem that some urls which are not in  tag, but in javascript codes.

for example, I have this source code that I want to extract all urls from

```<code>    Click <a style="vertical-align:middle;cursor:pointer;text-decoration:underline;color:red;" onClick="return downme('http://www.AAAAA.com/atnbc1i7b/part1.html')">

            Here</a> to go to download page

<a href="http://www.UUUU.com/register">Hi all</a>
</code>```

and I use this regex code

```<code>$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
    if(preg_match_all("/$regexp/siU", $page, $matches, PREG_SET_ORDER))
               {
                 foreach($matches as $match)
                   {
                      print_r($match)
                   }

               }
</code>```

the output will print to me just

```<code>http://www.UUUU.com/register
</code>```

but the other link

```<code>http://www.AAAAA.com/atnbc1i7b/part1.htm
</code>```

will not appear !!

Help please

thanks

答:
Instead of matching on the , try just matching on the URL:

```<code>$regexp = "(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
</code>```

I haven't tested this out due to a current lack of facilities, but if you run your file through it, it should match anything that resembles a URL, whether it's in a href, an onclick, or just in the text.

EDIT: found a better regex at href="http://daringfireball.net/2010/07/improved_regex_for_matching_urls" rel="nofollow">http://daringfireball.net/2010/07/improved_regex_for_matching_urls

Body:
I have a webpage source code stored in $page and I need to extract all urls from it

the problem that some urls which are not in  tag, but in javascript codes.

for example, I have this source code that I want to extract all urls from

    Click

            Here to go to download page

Hi all

and I use this regex code

$regexp = "]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
    if(preg_match_all("/$regexp/siU", $page, $matches, PREG_SET_ORDER))
               {
                 foreach($matches as $match)
                   {
                      print_r($match)
                   }

               }

the output will print to me just

http://www.UUUU.com/register

but the other link

http://www.AAAAA.com/atnbc1i7b/part1.htm

will not appear !!

Help please

thanks

Body:
Instead of matching on the <a href, try just matching on the URL:

$regexp = "(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"

I haven't tested this out due to a current lack of facilities, but if you run your file through it, it should match anything that resembles a URL, whether it's in a href, an onclick, or just in the text.

EDIT: found a better regex at http://daringfireball.net/2010/07/improved_regex_for_matching_urls


问:
How do I make my bulma progress bar not go over the whole screen?
This is my current code:

<progress class="progress is-warning" value="25" max="100">25%</progress>

I would want the progress bar to be shorter, meaning it not being as wide.

答:
This is hard to answer without knowing more about your layout. Bulma is an opinionated CSS framework whose simplicity comes from not piling on custom CSS for each component. So, add a max-width manually will work, but that's not the first tool I would advise reaching for with Bulma.

Do you want to put something else on the same line as the progress bar? If so, it might be better to put that thing and the progress bar in columns of the appropriate width. Or maybe tiles fit your layout needs better.

Do you want to center your progress bar on the screen, but have it stay to a reasonable width on larger screens? That's what a container is designed for.

And if you do end up wanting to use max-width (which again, consider using one of the options Bulma already provides), I would suggest adding a general decorator class like is-max-width-large or some such, and add that to your progress bar, rather than adding CSS specifically for progress bars, which conflicts with the rest of how Bulma works, and will make things more difficult to maintain.


问:
Your project requires a newer version of the Kotlin Gradle plugin. (Android Studio)
I've just updated my flutter project packages to be null-safety compliant and now Android Studio wants me to update my project to use the latest version of Kotling Gradle Plugin. Can't see where to change this though. I have tried to change "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" into "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.10" but this has no effect.

My build.grade-file looks like this:

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 31

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "*********"
        minSdkVersion 30
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Build output:

```<code>BUILD FAILED in 8s
[!] Your project requires a newer version of the Kotlin Gradle plugin.
    Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then update project/android/build.gradle:
    ext.kotlin_version = '<latest-version>'
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

答:
I Update Flutter to 2.10.1
and I found All My Project Has Same Error
in app /build.gradl
you change to ext.kotlin_version = '1.6.10'

Body:
I've just updated my flutter project packages to be null-safety compliant and now Android Studio wants me to update my project to use the latest version of Kotling Gradle Plugin. Can't see where to change this though. I have tried to change "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" into "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.10" but this has no effect.

My build.grade-file looks like this:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 31

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "*********"
        minSdkVersion 30
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
}
apply plugin: 'com.google.gms.google-services'

Build output:

BUILD FAILED in 8s
[!] Your project requires a newer version of the Kotlin Gradle plugin.
    Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then update project/android/build.gradle:
    ext.kotlin_version = '<latest-version>'
Exception: Gradle task assembleDebug failed with exit code 1


问:
Cannot connect to MySQL docker container from container with Django app
When I try to connect from a docker container running my Django app to a container running MySQL, I get the following error:

```<code>django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '172.17.0.2' (111)")
</code>```

Here's how I'm running the MySQL container:

```<code>$ docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=testdb -e MYSQL_ROOT_HOST=172.17.0.2 -d mysql/mysql-server:5.7
</code>```

If I don't specify MYSQL_ROOT_HOST, I get this error when I try to connect from the container with the Django app:

```<code>django.db.utils.OperationalError: (1130, "Host '172.17.0.3' is not allowed to connect to this MySQL server")
</code>```

Here are my Django settings:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'testdb',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': '172.17.0.2',
        'PORT': '',
    }
}
</code>```

I've verified the MySQL container is using IP 172.17.0.2:

```<code>$ docker inspect mysql |grep -i ipaddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",
</code>```

答:
Not sure if this will be helpful but I had a similar issue and got it to work by adding MYSQL_ROOT_HOST=%
This is what my docker-compose looks like for the db:

mysql:
  platform: linux/x86_64
  image: mysql
  environment:
    - MYSQL_ROOT_HOST=%
    - MYSQL_ROOT_PASSWORD=foobar123
    - MYSQL_USER=test_user
    - MYSQL_PASSWORD=foobar123
  volumes:
    - ./init:/docker-entrypoint-initdb.d
  ports:
    - 3306:3306
  container_name: "mysql"
```

Source documentation: https://dev.mysql.com/doc/refman/8.0/en/docker-mysql-more-topics.html#docker_var_mysql-root-host

Body:
When I try to connect from a docker container running my Django app to a container running MySQL, I get the following error:

django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '172.17.0.2' (111)")

Here's how I'm running the MySQL container:

$ docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=testdb -e MYSQL_ROOT_HOST=172.17.0.2 -d mysql/mysql-server:5.7

If I don't specify MYSQL_ROOT_HOST, I get this error when I try to connect from the container with the Django app:

django.db.utils.OperationalError: (1130, "Host '172.17.0.3' is not allowed to connect to this MySQL server")

Here are my Django settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'testdb',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': '172.17.0.2',
        'PORT': '',
    }
}

I've verified the MySQL container is using IP 172.17.0.2:

$ docker inspect mysql |grep -i ipaddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

Body:
Not sure if this will be helpful but I had a similar issue and got it to work by adding MYSQL_ROOT_HOST=%
This is what my docker-compose looks like for the db:

mysql:
  platform: linux/x86_64
  image: mysql
  environment:
    - MYSQL_ROOT_HOST=%
    - MYSQL_ROOT_PASSWORD=foobar123
    - MYSQL_USER=test_user
    - MYSQL_PASSWORD=foobar123
  volumes:
    - ./init:/docker-entrypoint-initdb.d
  ports:
    - 3306:3306
  container_name: "mysql"

Source documentation: https://dev.mysql.com/doc/refman/8.0/en/docker-mysql-more-topics.html#docker_var_mysql-root-host