问:
append to pickle file [python opencv face recognition]
I would like to combine two pickle files into a new onethat both come from face recognition. I have a main actors.pkl file that one holds a lot of actors, now I would like to update this file but not using the imageset update methode. So I am creating a new picklefile actorupdate.pkl in this set are the registered faces not in actors.pkl

I am able to open / read both files and they both work perfect (recognition wise) so how would I be able to join both files into a new one (or append actorupdate.pkl to actors.pkl)

```<code>import pickle

data = pickle.loads(open("encodings/actors.pkl", "rb").read())
data2 = pickle.loads(open("encodings/actorupdate.pkl", "rb").read())

verify dataset (names):
data['names'] = ['ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', ........
data2['names'] = ['Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot']
</code>```

trying to use this methode:

```<code>filename="picklefile"
with open(filename, 'wb') as fp:
   pickle.dump(data ,fp)
   pickle.dump(data2 ,fp)
</code>```

but in that case it writes a new file to my disk but the information from data2 is not there, it became just a copy of data and I would like to use the file directly not create a new pickle file on my disk.

答:
I found the following worked (had to loop over the contents of the data2):

```<code>data1 = pickle.load(open('encodings/actors.pkl', 'rb'))
data2 = pickle.loads(open("encodings/actorupdate.pkl", "rb").read())

new_encodings = data1['encodings']
new_names = data1['names']

for encode in data2['encodings']:
    new_encodings.append(encode)

for name in data2['names']:
    new_names.append(name)

data = {"encodings": new_encodings, "names": new_names}
with open(data1 , 'wb') as fp:
    pickle.dump(data, fp)
</code>```

data now holds both pickle files and allows to detect the faces from both pickle files, the file data1 itself is overwritten with the updated dataset (data2) on disk.

Body:
I would like to combine two pickle files into a new onethat both come from face recognition. I have a main actors.pkl file that one holds a lot of actors, now I would like to update this file but not using the imageset update methode. So I am creating a new picklefile actorupdate.pkl in this set are the registered faces not in actors.pkl

I am able to open / read both files and they both work perfect (recognition wise) so how would I be able to join both files into a new one (or append actorupdate.pkl to actors.pkl)

import pickle

data = pickle.loads(open("encodings/actors.pkl", "rb").read())
data2 = pickle.loads(open("encodings/actorupdate.pkl", "rb").read())

verify dataset (names):
data['names'] = ['ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', ........
data2['names'] = ['Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot']

trying to use this methode:

filename="picklefile"
with open(filename, 'wb') as fp:
   pickle.dump(data ,fp)
   pickle.dump(data2 ,fp)

but in that case it writes a new file to my disk but the information from data2 is not there, it became just a copy of data and I would like to use the file directly not create a new pickle file on my disk.

Body:
I found the following worked (had to loop over the contents of the data2):

data1 = pickle.load(open('encodings/actors.pkl', 'rb'))
data2 = pickle.loads(open("encodings/actorupdate.pkl", "rb").read())

new_encodings = data1['encodings']
new_names = data1['names']

for encode in data2['encodings']:
    new_encodings.append(encode)

for name in data2['names']:
    new_names.append(name)

data = {"encodings": new_encodings, "names": new_names}
with open(data1 , 'wb') as fp:
    pickle.dump(data, fp)

data now holds both pickle files and allows to detect the faces from both pickle files, the file data1 itself is overwritten with the updated dataset (data2) on disk.


来源: stackexchange

问:
Vaadin Flow DateTimePicker dirty inside CRUD
I am adding a com.vaadin.flow.component.datetimepicker.DateTimePicker to a com.vaadin.flow.component.crud.Crud. This appears to always mark the CRUD dirty. I noticed that things are all good when using a com.vaadin.flow.component.datepicker.DatePicker. This problem only shows for DateTimePicker. How should I cope with this?

```<code>DateTimePicker dtp = new DateTimePicker("When");
dtp.setStep(Duration.ofMillis(1));
// ...
binder.bind(dtp, new ValueProvider<MyEvent, LocalDateTime>() {
    @Override
    public LocalDateTime apply(final MyEvent source) {
        return source.getWhen();
    }
}, ...
</code>```

So, DateTimePicker with millis step, provided with a LocalDateTime value.

Later Edit:
I have looked further into the DateTimePicker.setPresentationValue(LocalDateTime) implementation and found that some JavaScript is being executed:

```<code>datePicker.getElement().executeJs("this.dispatchEvent(new CustomEvent('change', { bubbles: true }));");
</code>```

Could this be it? Unfortunately, I am not familiar to Vaadin's internals, so unsure why is that required there.

答: Please see https://github.com/vaadin/flow-components/issues/1043 . You should be able to change your project's pom.xml to pick-up the v 14.7.1 version of the timepicker flow component with the appropriate fix.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am adding a com.vaadin.flow.component.datetimepicker.DateTimePicker to a com.vaadin.flow.component.crud.Crud. This appears to always mark the CRUD dirty. I noticed that things are all good when using a com.vaadin.flow.component.datepicker.DatePicker. This problem only shows for DateTimePicker. How should I cope with this?

DateTimePicker dtp = new DateTimePicker("When");
dtp.setStep(Duration.ofMillis(1));
// ...
binder.bind(dtp, new ValueProvider<MyEvent, LocalDateTime>() {
    @Override
    public LocalDateTime apply(final MyEvent source) {
        return source.getWhen();
    }
}, ...

So, DateTimePicker with millis step, provided with a LocalDateTime value.

Later Edit:
I have looked further into the DateTimePicker.setPresentationValue(LocalDateTime) implementation and found that some JavaScript is being executed:

datePicker.getElement().executeJs("this.dispatchEvent(new CustomEvent('change', { bubbles: true }));");

Could this be it? Unfortunately, I am not familiar to Vaadin's internals, so unsure why is that required there.


问:
symbolic solution of linear equations using Sympy
Basically I have [5x5][5x1]=[0] and would like to have the symbolic expression of the solution.

Here is my code.

```<code>from sympy import symbols, solve
gm1, gm2, gm4                   = symbols(['gm1', 'gm2', 'gm4'])
gds1, gds2, gds3, gds4, gds5    = symbols(['gds1', 'gds2', 'gds3', 'gds4', 'gds5'])
s                               = symbols(['s'])
Cd, CF , Cin, Ct                = symbols(['Cd', 'CF', 'Cin', 'Ct'])
K                               = symbols(['K'])
vb, vc, ve, vout, iin           = symbols(['vb', 'vc', 've', 'vout', 'iin'])

sol = solve([-(gds1+gds3+(s*Cd))*vb + (gm1+gds1)*ve + -gm1*vout, \
          -gm4*vb + (gds4-gds2-(s*Cin)-(s*CF))*vc + (gds2+gm2)*ve + s*CF*vout + iin, \
        gds1*vb + gds2*vc + (-(s*Ct)-gds5-gds1-gm1-gm2-gds2)*ve + gm1*vout, \
        K*vc + vout], [vout])
print(sol)
</code>```

but, I got this error

```<code>TypeError: can't multiply sequence by non-int of type 'Symbol'
</code>```

From here, symbolic multiplication seems working just fine.

I am not sure whether I describe my problem in a way that does not comply with Sympy or something else.

What did I miss here?

答:
When you pass a list to symbols you get a list back. You can unpack that like [s] = symbols(['s']) or you can just pass a string of space or comma separated strings like x, y = symbols('x y') or x, y = symbols(','.join(['x', 'y']).

If you select manual=True you will get a solution vout=K*vc which sets the 4th equation to 0. But that was almost obvious, right? And you didn't need the other 3 equations to tell you that. So go ahead and pick up to 3 other variables for which you want to solve. There are lots of possibilities:

```<code>>>> from sympy.functions.combinatorial.numbers import nC
>>> allsym = Tuple(*eqs).free_symbols
>>> nfree = len(allsym) - 1  # always take vout
>>> print(nC(nfree, 3))  # want 3 others
816
</code>```

For example, selecting (vout, gds4, gm1, gds5) gives a solution of

```<code>[{gds4: (CF*K*s*vc + CF*s*vc + Cin*s*vc + gds2*vc -
         gds2*ve - gm2*ve + gm4*vb - iin)/vc,
  gm1: (Cd*s*vb + gds1*vb - gds1*ve + gds3*vb)/(K*vc + ve),
  gds5: -(Cd*s*vb + Ct*s*ve - gds2*vc + gds2*ve + gds3*vb + gm2*ve)/ve,
  vout: -K*vc}]
</code>```

Body:
Basically I have [5x5][5x1]=[0] and would like to have the symbolic expression of the solution.

Here is my code.

from sympy import symbols, solve
gm1, gm2, gm4                   = symbols(['gm1', 'gm2', 'gm4'])
gds1, gds2, gds3, gds4, gds5    = symbols(['gds1', 'gds2', 'gds3', 'gds4', 'gds5'])
s                               = symbols(['s'])
Cd, CF , Cin, Ct                = symbols(['Cd', 'CF', 'Cin', 'Ct'])
K                               = symbols(['K'])
vb, vc, ve, vout, iin           = symbols(['vb', 'vc', 've', 'vout', 'iin'])

sol = solve([-(gds1+gds3+(s*Cd))*vb + (gm1+gds1)*ve + -gm1*vout, \
          -gm4*vb + (gds4-gds2-(s*Cin)-(s*CF))*vc + (gds2+gm2)*ve + s*CF*vout + iin, \
        gds1*vb + gds2*vc + (-(s*Ct)-gds5-gds1-gm1-gm2-gds2)*ve + gm1*vout, \
        K*vc + vout], [vout])
print(sol)

but, I got this error

TypeError: can't multiply sequence by non-int of type 'Symbol'

From here, symbolic multiplication seems working just fine.

I am not sure whether I describe my problem in a way that does not comply with Sympy or something else.

What did I miss here?

Body:
When you pass a list to symbols you get a list back. You can unpack that like [s] = symbols(['s']) or you can just pass a string of space or comma separated strings like x, y = symbols('x y') or x, y = symbols(','.join(['x', 'y']).

If you select manual=True you will get a solution vout=K*vc which sets the 4th equation to 0. But that was almost obvious, right? And you didn't need the other 3 equations to tell you that. So go ahead and pick up to 3 other variables for which you want to solve. There are lots of possibilities:

>>> from sympy.functions.combinatorial.numbers import nC
>>> allsym = Tuple(*eqs).free_symbols
>>> nfree = len(allsym) - 1  # always take vout
>>> print(nC(nfree, 3))  # want 3 others
816

For example, selecting (vout, gds4, gm1, gds5) gives a solution of

[{gds4: (CF*K*s*vc + CF*s*vc + Cin*s*vc + gds2*vc -
         gds2*ve - gm2*ve + gm4*vb - iin)/vc,
  gm1: (Cd*s*vb + gds1*vb - gds1*ve + gds3*vb)/(K*vc + ve),
  gds5: -(Cd*s*vb + Ct*s*ve - gds2*vc + gds2*ve + gds3*vb + gm2*ve)/ve,
  vout: -K*vc}]


问:
Return percent or minimum count of total result set
Below is a sample result set. Report requirements to include

5% or minimum of 5 records for each month. whichever is greater

Return at least 1 record for each User

Include any record where IsNew or IsRequired = 1

I know I can use

```<code>SELECT TOP 5% *
FROM [SampleTable]
</code>```

to get a percentage but clueless how to include requirements and what to do if 5% is less than 5 records. Apologies if this is vague. I can add more context if needed.

SampleTable

RecordIdent
ReportMonth
OpenDate
User
Location
IsNew
IsRequired

1
12/31/2021
12/5/2021
7
1
0
0

2
12/31/2021
12/05/2021
7
5
1
1

3
12/31/2021
12/07/2021
12
5
0
1

4
12/31/2021
12/09/2021
12
5
0
0

5
12/31/2021
12/11/2021
7
5
1
0

11
01/31/2022
01/02/2022
25
5
0
0

12
01/31/2022
01/03/2022
7
5
1
1

13
01/31/2022
01/11/2022
7
5
0
1

答:
This might get you your desired results</p>
```<code>declare @rowCount int
select @rowCount=count(*) from SOF where IsNew =1 or IsRequired = 1
If(@rowCount>100)
begin
select top(5) PERCENT *,ROW_NUMBER() OVER(PARTITION BY [user] order by [user]) as rowNum from SOF where IsNew = 1 or IsRequired = 1 order by rowNum
end
else
begin
select top(5) *,ROW_NUMBER() OVER(PARTITION BY [user] order by [user]) as rowNum from SOF where IsNew = 1 or IsRequired = 1 order by rowNum
end
</code>```

Body:
Below is a sample result set. Report requirements to include

5% or minimum of 5 records for each month. whichever is greater

Return at least 1 record for each User

Include any record where IsNew or IsRequired = 1

I know I can use

SELECT TOP 5% *
FROM [SampleTable]

to get a percentage but clueless how to include requirements and what to do if 5% is less than 5 records. Apologies if this is vague. I can add more context if needed.

SampleTable

RecordIdent
ReportMonth
OpenDate
User
Location
IsNew
IsRequired

1
12/31/2021
12/5/2021
7
1
0
0

2
12/31/2021
12/05/2021
7
5
1
1

3
12/31/2021
12/07/2021
12
5
0
1

4
12/31/2021
12/09/2021
12
5
0
0

5
12/31/2021
12/11/2021
7
5
1
0

11
01/31/2022
01/02/2022
25
5
0
0

12
01/31/2022
01/03/2022
7
5
1
1

13
01/31/2022
01/11/2022
7
5
0
1

Body:
This might get you your desired results

declare @rowCount int
select @rowCount=count(*) from SOF where IsNew =1 or IsRequired = 1
If(@rowCount>100)
begin
select top(5) PERCENT *,ROW_NUMBER() OVER(PARTITION BY [user] order by [user]) as rowNum from SOF where IsNew = 1 or IsRequired = 1 order by rowNum
end
else
begin
select top(5) *,ROW_NUMBER() OVER(PARTITION BY [user] order by [user]) as rowNum from SOF where IsNew = 1 or IsRequired = 1 order by rowNum
end


问:
What modules/tools are available for drawing a graph from text/csv file in Perl or PHP?
I have to draw a graph in Perl or PHP. Can you show me any sample code to read from the text or CSV file and plot a graph or chart of pie?

Data would be like this sample in a CSV or text file:

```<code>01/01/2010  0
01/02/2010  1
01/03/2010  2
01/04/2010  3
</code>```

Another set of data in text file for chart

```<code>Column A 20
Column B 10
Column C 02
</code>```

I want to display the value for each column in my pie chart.

答:
I have been using PHPExcel for over a year now; I think it's one of the best PHP Excel tools out there (it does CSVs too).  You can import the CSV file, generate a graph, and export it in just a few lines of code.

http://phpexcel.codeplex.com/

ContentLicense: CC BY-SA 3.0

Body:
I have to draw a graph in Perl or PHP. Can you show me any sample code to read from the text or CSV file and plot a graph or chart of pie?

Data would be like this sample in a CSV or text file:

01/01/2010  0
01/02/2010  1
01/03/2010  2
01/04/2010  3

Another set of data in text file for chart

Column A 20
Column B 10
Column C 02

I want to display the value for each column in my pie chart.


问:
smart way to generate unique random number
i want to generate a sequence of unique random numbers in the range of 00000001 to 99999999.

So the first one might be 00001010, the second 40002928 etc.

The easy way is to generate a random number and store it in the database, and every next time do it again and check in the database if the number already exists and if so, generate a new one, check it again, etc.
But that doesn't look right, i could be regenerating a number maybe 100 times if the number of generated items gets large.

Is there a smarter way?

EDIT
as allways i forgot to say WHY i wanted this, and it will probably make things clearer and maybe get an alternative, and it is:
we want to generate an ordernumber for a booking, so we could just use 000001, 000002 etc. But we don't want to give the competitors a clue of how much orders are created (because it's not a high volume market, and we don't want them to know if we are on order 30 after 2 months or at order 100. So we want to have an order number which is random (yet unique)

答:
You can genearate number like below if you are ok with consumption of memory.</p>
```<code>import java.util.ArrayList;
import java.util.Collections;

public class UniqueRandomNumbers {

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i=1; i<11; i++) {
            list.add(i);
        }
        Collections.shuffle(list);
        for (int i=0; i<11; i++) {
            System.out.println(list.get(i));
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can genearate number like below if you are ok with consumption of memory.

import java.util.ArrayList;
import java.util.Collections;

public class UniqueRandomNumbers {

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i=1; i<11; i++) {
            list.add(i);
        }
        Collections.shuffle(list);
        for (int i=0; i<11; i++) {
            System.out.println(list.get(i));
        }
    }
}


问:
Using compression with EJS template engine
I am trying to optimise my site and one of the suggestions I keep getting is to compress response.
I have nodejs app that uses EJS template engine for SSR and can't seem to make it work, and can't find relevant info in docs.

When I send my response back 'normally' ( res.send(something);) it is being compressed.
While when I do ejs.renderFile(...) it doesn't have 'Content-Encoding: gzip' header.

I imported 'compression' module and set app to use it as per docs.

答:
You can always use</p>
```<code>res.render(path,data,(error, html) =>{
 if(error)
   ...
 res.send(html)
})
</code>```

Body:
You can always use

res.render(path,data,(error, html) =>{
 if(error)
   ...
 res.send(html)
})


问:
FlutterMap LateInitializationError State Management
I'm trying to make a Flutter app, using Riverpod for state management and FlutterMaps. I have set up notifiers for pages, and am also using a (State)NotifierProvider for the map page. I am building a search function, which goes to a search page which displays a list with search results. When one of these results (in a list) is clicked, I update the notifier of the  map page. However, here comes the tricky part: I want to update the map according to the LatLng of the search result (center it).

My implementation of the Notifier contains:
late MapController? _mapController;

My map page is loaded in and gets the mapController from the Notifier: mapController: notifier.getMapController()

Using Riverpod state management, this all should work, however I get the following Error:

```<code>LateError (LateInitializationError: Field '_state@1225051772' has already been initialized.)
</code>```

This Error is within the MapController itself (which is part of the FlutterMaps package), so I do not want to touch that. Does anyone have any idea how to tackle this?

答:
you should remove the late keyword or you should intialise it in the initState
method.</p>

Body:
I'm trying to make a Flutter app, using Riverpod for state management and FlutterMaps. I have set up notifiers for pages, and am also using a (State)NotifierProvider for the map page. I am building a search function, which goes to a search page which displays a list with search results. When one of these results (in a list) is clicked, I update the notifier of the  map page. However, here comes the tricky part: I want to update the map according to the LatLng of the search result (center it).

My implementation of the Notifier contains:
late MapController? _mapController;

My map page is loaded in and gets the mapController from the Notifier: mapController: notifier.getMapController()

Using Riverpod state management, this all should work, however I get the following Error:

LateError (LateInitializationError: Field '_state@1225051772' has already been initialized.)

This Error is within the MapController itself (which is part of the FlutterMaps package), so I do not want to touch that. Does anyone have any idea how to tackle this?


问:
Custom Contact Form on a Drupal CCK Node
What would be the best way to construct a contact form in Drupal 6 for each node of a particular type? I have some CCK nodes of type "profile" which have email address as a field. I want to have a view for each node with a contact form that users can fill out and send with their own email address as a return address (so that further contact is being done offsite).

Basically I just want that initial email contact to be done through my site, and when the recipient replies it just goes to the address that the sender entered when they filled out the contact form.

You might be asking yourself why I don't use the personal contact form that comes baked into Drupal. The issue is that the way my institution deploys their Drupal instances to use the local Kerberos logins, the user accounts it creates in Drupal do not have email addresses. They just get a basic skeleton account with username. I don't really want to force users to go through another hoop of editing their user account info, because they most likely just won't do it.

答:
There is nothing to do particularly with node itself, all you need for this - is form with fields (from, to, subject, message) and custom submit handler for this form.
you can implement all this in custom module using forms API to create form and write custom submit for it. And in this submit you need to send email via drupal_mail() - take a look at this, it is provides examples as well. That topic can help you with forms.

Then, if you need to place this form within a node, you can do the following:
via hook_nodeapi, on "view" operation, add form you've created before, you can check for particular node_type and use existing field values (you mentioned cck field with email) to pre-fill form. So that every time user views node, he sees this form.

as logical continue of your task, I suggest it makes sense to take a look at menu system and create local task (tab) for the node, where you'll display email form.

In general, that's all. There are of course other ways of implementing this, however I think this one is the easiest for understanding.

Regards, Slava


问:
How to pass multi-argument templates to macros?
Say I have a macro like this:

```<code>#define SET_TYPE_NAME(TYPE, NAME) \
    template<typename T>          \
    std::string name();           \
                                  \
    template<>                    \
    std::string name<TYPE>() {    \
        return NAME;              \
    }
</code>```

This won't work if I pass it a template that has more than one parameter, because the comma in the <int, int> is interpreted as separating the macro arguments, not the template arguments.

```<code>SET_TYPE_NAME(std::map<int, int>, "TheMap")
// Error: macro expects two arguments, three given
</code>```

This problem seems to be solved by doing this:

```<code>SET_TYPE_NAME((std::map<int, int>), "TheMap")
</code>```

But now another problem arises, one that I really did not expect:

```<code> template<>
 std::string name<(std::map<int, int>)>()
 // template argument 1 is invalid
</code>```

It seems that the extra parentheses make the template argument invalid. Is there any way around this?

答:
I know this is an old question. Though this comes in top results on a Google search and nobody has yet mentioned an even more simple solution by defining a macro for the comma:</p>
```<code>#define COMMA ,
SET_TYPE_NAME(std::map<int COMMA int>, "TheMap")
</code>```

Body:
Say I have a macro like this:

#define SET_TYPE_NAME(TYPE, NAME) \
    template<typename T>          \
    std::string name();           \
                                  \
    template<>                    \
    std::string name<TYPE>() {    \
        return NAME;              \
    }

This won't work if I pass it a template that has more than one parameter, because the comma in the <int, int> is interpreted as separating the macro arguments, not the template arguments.

SET_TYPE_NAME(std::map<int, int>, "TheMap")
// Error: macro expects two arguments, three given

This problem seems to be solved by doing this:

SET_TYPE_NAME((std::map<int, int>), "TheMap")

But now another problem arises, one that I really did not expect:

 template<>
 std::string name<(std::map<int, int>)>()
 // template argument 1 is invalid

It seems that the extra parentheses make the template argument invalid. Is there any way around this?

Body:
I know this is an old question. Though this comes in top results on a Google search and nobody has yet mentioned an even more simple solution by defining a macro for the comma:

#define COMMA ,
SET_TYPE_NAME(std::map<int COMMA int>, "TheMap")


问:
Sample from ragged tensor
I have a raggedTensor of row_lens going from 1 to up to 10k. I would like to select elements randomly from it with an upper limit on the number per row in a scalable way. Like in this example:

```<code>vect = [[1,2,3],[4,5][6],[7,8,9,10,11,12,13]]
limit = 3
sample(vect, limit)
</code>```

->  output: [[1,2,3],[4,5],[6],[7,9,11]]

My idea was to select * in case len_row < limit and randomly in the other case. I wonder if this can be done with less than batch_size complexity with some tensorflow operations?

答:
You can try using tf.map_fn in graph mode:

import tensorflow as tf

vect = tf.ragged.constant([[1,2,3],[4,5],[6],[7,8,9,10,11,12,13]])

@tf.function
def sample(x, samples=3):
  length = tf.shape(x)[0]
  x = tf.cond(tf.less_equal(length, samples), lambda: x, lambda: tf.gather(x, tf.random.shuffle(tf.range(length))[:samples]))
  return x

c = tf.map_fn(sample, vect)
```
```<tf.RaggedTensor [[1, 2, 3], [4, 5], [6], [12, 7, 9]]>
```

Note that tf.vectorized_map would probably be faster, but there is a current bug regarding this function and ragged tensors. The use of tf.while_loop is also an option.

Title: Sample from ragged tensor

Body:
I have a raggedTensor of row_lens going from 1 to up to 10k. I would like to select elements randomly from it with an upper limit on the number per row in a scalable way. Like in this example:

vect = [[1,2,3],[4,5][6],[7,8,9,10,11,12,13]]
limit = 3
sample(vect, limit)

->  output: [[1,2,3],[4,5],[6],[7,9,11]]

My idea was to select * in case len_row < limit and randomly in the other case. I wonder if this can be done with less than batch_size complexity with some tensorflow operations?

Body:
You can try using tf.map_fn in graph mode:

import tensorflow as tf

vect = tf.ragged.constant([[1,2,3],[4,5],[6],[7,8,9,10,11,12,13]])

@tf.function
def sample(x, samples=3):
  length = tf.shape(x)[0]
  x = tf.cond(tf.less_equal(length, samples), lambda: x, lambda: tf.gather(x, tf.random.shuffle(tf.range(length))[:samples]))
  return x

c = tf.map_fn(sample, vect)

<tf.RaggedTensor [[1, 2, 3], [4, 5], [6], [12, 7, 9]]>

Note that tf.vectorized_map would probably be faster, but there is a current bug regarding this function and ragged tensors. The use of tf.while_loop is also an option.


问:
react native expo prebuild error `UMCore` depended upon by `EXFont`
I am working on a React Native Project based on a bare workflow, and my project is not working on Xcode.
I use expo modules but when i want to setup my ios project by the command "expo prebuild" i get the following error:

⚠  Something went wrong running pod install in the ios directory.
Command pod repo update failed.
└─ Cause: Couldn't install: EXFont » UMCore. Ensure the CocoaPod "UMCore" is installed in your project, then run npx pod-install to try again.

It seems Cocoapods did not install this file.. but i have no idea how to do it.

And When i launch the command "pod install" i get :
"[!] Unable to find a specification for UMCore depended upon by EXFont"

I followed this guide from Expo : https://github.com/expo/fyi/blob/main/expo-modules-migration.md
It works fine on my Android Project.

I got the latest version of Expo and CocoaPods and my Xcode version is 13.0.

Any idea ? I did not found a lot of topics on this subject, and none solve this error...

答:
I had similar errors after updating the expo.
In my case it was:

[!] Unable to find a specification for UMCore depended upon by EXSecureStore

[!] Unable to find a specification for UMCore depended upon by EXLinearGradient

Solution

```<code>expo install expo-secure-store
expo install expo-linear-gradient
cd ios
pod install --repo-update --clean-install
</code>```

To solve your issue, I think you need to do:

```<code>expo install expo-font
cd ios
pod install # or `pod install --repo-update --clean-install`
</code>```

Body:
I had similar errors after updating the expo.
In my case it was:

[!] Unable to find a specification for UMCore depended upon by EXSecureStore

[!] Unable to find a specification for UMCore depended upon by EXLinearGradient

Solution

expo install expo-secure-store
expo install expo-linear-gradient
cd ios
pod install --repo-update --clean-install

To solve your issue, I think you need to do:

expo install expo-font
cd ios
pod install # or `pod install --repo-update --clean-install`


答:
I found a similiar error from here: https://blog.csdn.net/zgz9949/article/details/111641415

It gave out a solution: delete the folder /data/local/tmp/perfd. You can backup it if you are worried about the result.

Title: ANR - Cause: null pointer dereference

Body:
I am getting one ANR when app is ideal for some minutes in foreground mode. This screen is having text input box (signup process). here I am just filling whole form and keeping app in ideal state. then getting this ANR and app closes that screen and came back to previous screen.

2022-02-11 15:14:50.568 32014-32014/? A/DEBUG: Build fingerprint: 'HUAWEI/MAR-LX2/HWMAR:10/HUAWEIMAR-L22A/10.0.0.279C675:user/release-keys'
2022-02-11 15:14:50.568 32014-32014/? A/DEBUG: Revision: '0'
2022-02-11 15:14:50.568 32014-32014/? A/DEBUG: ABI: 'arm64'
2022-02-11 15:14:50.568 32014-32014/? A/DEBUG: Timestamp: 2022-02-11 17:44:50+0800
2022-02-11 15:14:50.568 32014-32014/? A/DEBUG: pid: 31015, tid: 31028, name: HeapTaskDaemon  >>> com.feo <<<
2022-02-11 15:14:50.568 32014-32014/? A/DEBUG: uid: 11298
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG: signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x10
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG: Cause: null pointer dereference
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     x0  00000071c16bd400  x1  00000071b5e13a98  x2  0000000000000008  x3  0000000070f38b10
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     x4  000000000000044c  x5  000000001338ca2c  x6  12c4274012c42f58  x7  0000000070f61c80
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     x8  0000000000000000  x9  cdaede85033c2750  x10 0000000052c00000  x11 0000000000000008
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     x12 000000000000000b  x13 000009fd00000071  x14 0006ae0246258983  x15 0000126e86b54941
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     x16 00000071c15fb000  x17 0000007242f42b40  x18 000000715d798000  x19 00000071b5e13a98
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     x20 0000000070f38b10  x21 0000000000000008  x22 00000000716ab790  x23 00000000716aa070
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     x24 0000000000000028  x25 0000000000002828  x26 00000071b5e15020  x27 0000000000001720
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     x28 00000000716aa088  x29 00000071b5e13a80
2022-02-11 15:14:50.569 32014-32014/? A/DEBUG:     sp  00000071b5e13a10  lr  00000071c1236f6c  pc  00000071c1236f48
2022-02-11 15:14:50.723 32014-32014/? A/DEBUG: backtrace:
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #00 pc 000000000022ff48  /apex/com.android.runtime/lib64/libart.so (_ZN3art6mirror6Object15VisitReferencesILb1ELNS_17VerifyObjectFlagsE0ELNS_17ReadBarrierOptionE1ENS_2gc9collector17ConcurrentCopying16RefFieldsVisitorILb0EEES9_EEvRKT2_RKT3_+2828) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #01 pc 000000000021fd10  /apex/com.android.runtime/lib64/libart.so (art::gc::collector::ConcurrentCopying::ImmuneSpaceScanObjVisitor::Callback(art::mirror::Object*, void*)+112) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #02 pc 000000000020e188  /apex/com.android.runtime/lib64/libart.so (art::gc::accounting::ModUnionTableReferenceCache::VisitObjects(void (*)(art::mirror::Object*, void*), void*)+292) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #03 pc 000000000021a9dc  /apex/com.android.runtime/lib64/libart.so (art::gc::collector::ConcurrentCopying::CopyingPhase()+1236) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #04 pc 00000000002188c4  /apex/com.android.runtime/lib64/libart.so (art::gc::collector::ConcurrentCopying::RunPhases()+1148) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #05 pc 0000000000236f48  /apex/com.android.runtime/lib64/libart.so (art::gc::collector::GarbageCollector::Run(art::gc::GcCause, bool)+288) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #06 pc 0000000000255fd4  /apex/com.android.runtime/lib64/libart.so (art::gc::Heap::CollectGarbageInternal(art::gc::collector::GcType, art::gc::GcCause, bool)+3196) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #07 pc 000000000026838c  /apex/com.android.runtime/lib64/libart.so (art::gc::Heap::ConcurrentGC(art::Thread*, art::gc::GcCause, bool)+124) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #08 pc 000000000026df58  /apex/com.android.runtime/lib64/libart.so (art::gc::Heap::ConcurrentGCTask::Run(art::Thread*)+36) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #09 pc 000000000029b2f8  /apex/com.android.runtime/lib64/libart.so (art::gc::TaskProcessor::RunAllTasks(art::Thread*)+64) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #10 pc 0000000000067aec  /system/framework/arm64/boot-core-libart.oat (art_jni_trampoline+124) (BuildId: cd6043ddfff407b4835c3e45be96dbab5a0b3a9b)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #11 pc 0000000000144334  /apex/com.android.runtime/lib64/libart.so (art_quick_invoke_stub+548) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #12 pc 00000000001531a4  /apex/com.android.runtime/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+252) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #13 pc 00000000002ee6d8  /apex/com.android.runtime/lib64/libart.so (art::interpreter::ArtInterpreterToCompiledCodeBridge(art::Thread*, art::ArtMethod*, art::ShadowFrame*, unsigned short, art::JValue*)+384) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #14 pc 00000000002e99a8  /apex/com.android.runtime/lib64/libart.so (bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*)+912) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #15 pc 00000000005bb284  /apex/com.android.runtime/lib64/libart.so (MterpInvokeVirtual+648) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #16 pc 000000000013e814  /apex/com.android.runtime/lib64/libart.so (mterp_op_invoke_virtual+20) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #17 pc 00000000001b47c2  /apex/com.android.runtime/javalib/core-libart.jar (java.lang.Daemons$HeapTaskDaemon.runInternal+38)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #18 pc 00000000005bb594  /apex/com.android.runtime/lib64/libart.so (MterpInvokeVirtual+1432) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #19 pc 000000000013e814  /apex/com.android.runtime/lib64/libart.so (mterp_op_invoke_virtual+20) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #20 pc 00000000001b3fa6  /apex/com.android.runtime/javalib/core-libart.jar (java.lang.Daemons$Daemon.run+50)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #21 pc 00000000005bcd94  /apex/com.android.runtime/lib64/libart.so (MterpInvokeInterface+1752) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #22 pc 000000000013ea14  /apex/com.android.runtime/lib64/libart.so (mterp_op_invoke_interface+20) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #23 pc 00000000000eabdc  /apex/com.android.runtime/javalib/core-oj.jar (java.lang.Thread.run+8)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #24 pc 00000000002bf314  /apex/com.android.runtime/lib64/libart.so (_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_6JValueEbb.llvm.17950311261770437987+240) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #25 pc 00000000005a6470  /apex/com.android.runtime/lib64/libart.so (artQuickToInterpreterBridge+1012) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #26 pc 000000000014d468  /apex/com.android.runtime/lib64/libart.so (art_quick_to_interpreter_bridge+88) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #27 pc 0000000000144334  /apex/com.android.runtime/lib64/libart.so (art_quick_invoke_stub+548) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #28 pc 00000000001531a4  /apex/com.android.runtime/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+252) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #29 pc 00000000004c6ec0  /apex/com.android.runtime/lib64/libart.so (art::(anonymous namespace)::InvokeWithArgArray(art::ScopedObjectAccessAlreadyRunnable const&, art::ArtMethod*, art::(anonymous namespace)::ArgArray*, art::JValue*, char const*)+104) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #30 pc 00000000004c7f54  /apex/com.android.runtime/lib64/libart.so (art::InvokeVirtualOrInterfaceWithJValues(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jmethodID*, jvalue const*)+416) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #31 pc 0000000000507f24  /apex/com.android.runtime/lib64/libart.so (art::Thread::CreateCallback(void*)+1176) (BuildId: 602edb11a79b9a18b1585382d06c7450)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #32 pc 00000000000ce1b0  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*)+36) (BuildId: 95e03d8a9f101c0f1d3d9458688aa085)
2022-02-11 15:14:50.724 32014-32014/? A/DEBUG:       #33 pc 0000000000070ba8  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+64) (BuildId: 95e03d8a9f101c0f1d3d9458688aa085)

Anyone having any idea what I need to check or monitor in app for this ? any code level changes I can make in this case ?

Thank you!


问:
How to use DropDownButton for dynamic list in flutter?
I am trying to implement dynamic dropdownButton in my app where the items of dropdown is going to come from the names of columns in my excel sheet. I am able to show all the columns of excel but I couldn't able to trace the index of column which the user is selecting from the dropdown.

I tried to make a map of dropdownitems like this in which the key is the index and value is the DropdownMenuItem like this :

```<code>late int selectedIndex;  //where I want to store the selected index
late String initialDropDownVal;
List<Map<int,DropdownMenuItem<String>>> dropdownItems = [];
</code>```

Then I added some values by iterating the columns of excel using a for loop :

```<code>excel = Excel.decodeBytes(bytes);
sheet = excel['Sheet1'];
for(int i = 1; i< sheet.maxCols; ++i){
   var cell = sheet.cell(CellIndex.indexByColumnRow(rowIndex: 0, columnIndex: i));
   String val = cell.value.toString();
   if(val=="null"){
        break;
   }else{
      if(i==1){
         initialDropDownVal = val;
      }
      var newItem = DropdownMenuItem(
         child: Text(val),
              value: val,
          );
       dropdownItems.add({i:newItem});
   }

}
</code>```

But I could not able to map the values in items attribute of DropdownButton, I tried to implement like this but this is throwing error

```<code>DropdownButton(
 value: selectedVal,
 icon: const Icon(Icons.keyboard_arrow_down),
 items: dropdownItems.map((int i,DropdownMenuItem<String> p) => p).toList(),
 onChanged: (String? value){
      setState(() {
            initialDropDownVal = value!;
       });
})
</code>```

And I am not sure how to change set the selectedIndex in onChanged function. Please help me in this. Thanks

答:
```<code>late int selectedIndex;  //where I want to store the selected index
late String initialDropDownVal;
List<DropdownMenuItem<String>> dropdownItems = [];

excel = Excel.decodeBytes(bytes);
sheet = excel['Sheet1'];
for(int i = 1; i< sheet.maxCols; ++i){
   var cell = sheet.cell(CellIndex.indexByColumnRow(rowIndex: 0, columnIndex: i));
   String val = cell.value.toString();
   if(val=="null"){
        break;
   }else{
      if(i==1){
         initialDropDownVal = val;
      }
      var newItem = DropdownMenuItem(
         child: Text(val),
              value: val,
          );
       dropdownItems.add(newItem);
   }

}

DropdownButton(
 value: selectedVal,
 icon: const Icon(Icons.keyboard_arrow_down),
 items: dropdownItems,
 onChanged: (String? value){
      setState(() {
            initialDropDownVal = value!;
selectedIndex=dropdownItems.indexWhere((i)=>i.value==value);
       });
})
</code>```

Body:
I am trying to implement dynamic dropdownButton in my app where the items of dropdown is going to come from the names of columns in my excel sheet. I am able to show all the columns of excel but I couldn't able to trace the index of column which the user is selecting from the dropdown.

I tried to make a map of dropdownitems like this in which the key is the index and value is the DropdownMenuItem like this :

late int selectedIndex;  //where I want to store the selected index
late String initialDropDownVal;
List<Map<int,DropdownMenuItem<String>>> dropdownItems = [];

Then I added some values by iterating the columns of excel using a for loop :

excel = Excel.decodeBytes(bytes);
sheet = excel['Sheet1'];
for(int i = 1; i< sheet.maxCols; ++i){
   var cell = sheet.cell(CellIndex.indexByColumnRow(rowIndex: 0, columnIndex: i));
   String val = cell.value.toString();
   if(val=="null"){
        break;
   }else{
      if(i==1){
         initialDropDownVal = val;
      }
      var newItem = DropdownMenuItem(
         child: Text(val),
              value: val,
          );
       dropdownItems.add({i:newItem});
   }

}

But I could not able to map the values in items attribute of DropdownButton, I tried to implement like this but this is throwing error

DropdownButton(
 value: selectedVal,
 icon: const Icon(Icons.keyboard_arrow_down),
 items: dropdownItems.map((int i,DropdownMenuItem<String> p) => p).toList(),
 onChanged: (String? value){
      setState(() {
            initialDropDownVal = value!;
       });
})

And I am not sure how to change set the selectedIndex in onChanged function. Please help me in this. Thanks


问:
Find specific values in a txt file and adding them up with python
I have a txt file which looks like that:

```<code>[Chapter.Title1]
Irrevelent=90 B
Volt=0.10 ienl
Watt=2 W
Ampere=3 A
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=999
Irrevelent=999

[Chapter.Title3]
Irrevelent=92 B
Volt=0.20 ienl
Watt=5 W
Ampere=6 A
Irrevelent=93 C
</code>```

What I want is that it catches "Title1" and the values "0,1", "2" and "3". Then adds them up (which would be 5.1).

I don't care about the lines with "irrevelent" at the beginning.

And then the same with the third block. Catching "Title3" and adding "0.2", "5" and "6".

The second block with "Title2" does not contain "Volt", Watt" and "Ampere" and is therefore not relevant.

Can anyone please help me out with this?

Thank you and cheers

答:
You can use regular expressions to get the values and the titles in lists, then use them.

```<code>txt = """[Chapter.Title1]
Irrevelent=90 B
Volt=1 V
Watt=2 W
Ampere=3 A
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=92 B
Volt=4 V
Watt=5 W
Ampere=6 A
Irrevelent=93 C"""
#that's just the text

import re

rx1=r'Chapter.(.*?)\]'
rxv1=r'Volt=(\d+)'
rxv2=r'Watt=(\d+)'
rxv3=r'Ampere=(\d+)'
res1 = re.findall(rx1, txt)
resv1 = re.findall(rxv1, txt)
resv2 = re.findall(rxv2, txt)
resv3 = re.findall(rxv3, txt)

print(res1)
print(resv1)
print(resv2)
print(resv3)
</code>```

Here you get the titles and the interesting values you want :

```<code>['Title1', 'Title2']
['1', '4']
['2', '5']
['3', '6']
</code>```

You can then use them as you want, for example :

```<code>for title_index in range(len(res1)):
  print(res1[title_index])
  value=int(resv1[title_index])+int(resv2[title_index])+int(resv3[title_index])
  #use float() instead of int() if you have non integer values
  print("the value is:", value)
</code>```

You get :

```<code>Title1
the value is: 6
Title2
the value is: 15
</code>```

Or you can store them in a dictionary or an other structure, for example :

```<code>#dict(zip(keys, values))
data= dict(zip(res1, [int(resv1[i])+int(resv2[i])+int(resv3[i]) for i in range(len(res1))] ))

print(data)
</code>```

You get :

```<code>{'Title1': 6, 'Title2': 15}

</code>```

Edit : added opening of the file

```<code>import re

with open('filename.txt', 'r') as file:
    txt = file.read()

rx1=r'Chapter.(.*?)\]'
rxv1=r'Volt=([0-9]+(?:\.[0-9]+)?)'
rxv2=r'Watt=([0-9]+(?:\.[0-9]+)?)'
rxv3=r'Ampere=([0-9]+(?:\.[0-9]+)?)'
res1 = re.findall(rx1, txt)
resv1 = re.findall(rxv1, txt)
resv2 = re.findall(rxv2, txt)
resv3 = re.findall(rxv3, txt)

data= dict(zip(res1, [float(resv1[i])+float(resv2[i])+float(resv3[i]) for i in range(len(res1))] ))

print(data)
</code>```

Edit 2 : ignoring missing values

```<code>import re

with open('filename.txt', 'r') as file:
    txt = file.read()

#divide the text into parts starting with "chapter"
substr = "Chapter"
chunks_idex = [_.start() for _ in re.finditer(substr, txt)]
chunks = [txt[chunks_idex[i]:chunks_idex[i+1]-1] for i in range(len(chunks_idex)-1)]
chunks.append(txt[chunks_idex[-1]:]) #add the last chunk
#print(chunks)

keys=[]
values=[]
rx1=r'Chapter.(.*?)\]'
rxv1=r'Volt=([0-9]+(?:\.[0-9]+)?)'
rxv2=r'Watt=([0-9]+(?:\.[0-9]+)?)'
rxv3=r'Ampere=([0-9]+(?:\.[0-9]+)?)'

for chunk in chunks:

  res1 = re.findall(rx1, chunk)
  resv1 = re.findall(rxv1, chunk)
  resv2 = re.findall(rxv2, chunk)
  resv3 = re.findall(rxv3, chunk)
  # check if we can find all of them by checking if the lists are not empty
  if res1 and resv1 and resv2 and resv3 :
    keys.append(res1[0])
    values.append(float(resv1[0])+float(resv2[0])+float(resv3[0]))

data= dict(zip(keys, values ))
print(data)
</code>```

Body:
I have a txt file which looks like that:

[Chapter.Title1]
Irrevelent=90 B
Volt=0.10 ienl
Watt=2 W
Ampere=3 A
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=999
Irrevelent=999

[Chapter.Title3]
Irrevelent=92 B
Volt=0.20 ienl
Watt=5 W
Ampere=6 A
Irrevelent=93 C

What I want is that it catches "Title1" and the values "0,1", "2" and "3". Then adds them up (which would be 5.1).

I don't care about the lines with "irrevelent" at the beginning.

And then the same with the third block. Catching "Title3" and adding "0.2", "5" and "6".

The second block with "Title2" does not contain "Volt", Watt" and "Ampere" and is therefore not relevant.

Can anyone please help me out with this?

Thank you and cheers

Body:
You can use regular expressions to get the values and the titles in lists, then use them.

txt = """[Chapter.Title1]
Irrevelent=90 B
Volt=1 V
Watt=2 W
Ampere=3 A
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=92 B
Volt=4 V
Watt=5 W
Ampere=6 A
Irrevelent=93 C"""
#that's just the text

import re

rx1=r'Chapter.(.*?)\]'
rxv1=r'Volt=(\d+)'
rxv2=r'Watt=(\d+)'
rxv3=r'Ampere=(\d+)'
res1 = re.findall(rx1, txt)
resv1 = re.findall(rxv1, txt)
resv2 = re.findall(rxv2, txt)
resv3 = re.findall(rxv3, txt)

print(res1)
print(resv1)
print(resv2)
print(resv3)

Here you get the titles and the interesting values you want :

['Title1', 'Title2']
['1', '4']
['2', '5']
['3', '6']

You can then use them as you want, for example :

for title_index in range(len(res1)):
  print(res1[title_index])
  value=int(resv1[title_index])+int(resv2[title_index])+int(resv3[title_index])
  #use float() instead of int() if you have non integer values
  print("the value is:", value)

You get :

Title1
the value is: 6
Title2
the value is: 15

Or you can store them in a dictionary or an other structure, for example :

#dict(zip(keys, values))
data= dict(zip(res1, [int(resv1[i])+int(resv2[i])+int(resv3[i]) for i in range(len(res1))] ))

print(data)

You get :

{'Title1': 6, 'Title2': 15}

Edit : added opening of the file

import re

with open('filename.txt', 'r') as file:
    txt = file.read()

rx1=r'Chapter.(.*?)\]'
rxv1=r'Volt=([0-9]+(?:\.[0-9]+)?)'
rxv2=r'Watt=([0-9]+(?:\.[0-9]+)?)'
rxv3=r'Ampere=([0-9]+(?:\.[0-9]+)?)'
res1 = re.findall(rx1, txt)
resv1 = re.findall(rxv1, txt)
resv2 = re.findall(rxv2, txt)
resv3 = re.findall(rxv3, txt)

data= dict(zip(res1, [float(resv1[i])+float(resv2[i])+float(resv3[i]) for i in range(len(res1))] ))

print(data)

Edit 2 : ignoring missing values

import re

with open('filename.txt', 'r') as file:
    txt = file.read()

#divide the text into parts starting with "chapter"
substr = "Chapter"
chunks_idex = [_.start() for _ in re.finditer(substr, txt)]
chunks = [txt[chunks_idex[i]:chunks_idex[i+1]-1] for i in range(len(chunks_idex)-1)]
chunks.append(txt[chunks_idex[-1]:]) #add the last chunk
#print(chunks)

keys=[]
values=[]
rx1=r'Chapter.(.*?)\]'
rxv1=r'Volt=([0-9]+(?:\.[0-9]+)?)'
rxv2=r'Watt=([0-9]+(?:\.[0-9]+)?)'
rxv3=r'Ampere=([0-9]+(?:\.[0-9]+)?)'

for chunk in chunks:

  res1 = re.findall(rx1, chunk)
  resv1 = re.findall(rxv1, chunk)
  resv2 = re.findall(rxv2, chunk)
  resv3 = re.findall(rxv3, chunk)
  # check if we can find all of them by checking if the lists are not empty
  if res1 and resv1 and resv2 and resv3 :
    keys.append(res1[0])
    values.append(float(resv1[0])+float(resv2[0])+float(resv3[0]))

data= dict(zip(keys, values ))
print(data)


问:
setInterval change background div
i have code

```<code>  function smena(){
     $('.wrapper').animate({opacity:0},2500,function(){
           setTimeout ($('.wrapper').animate({opacity:1},2500),5000)
      });
   }
   $(document).ready(function(){

       setInterval('smena();',10000);
  });
</code>```

why me animaation jump? i want just change bg for my div "wrapper".

答:
Basically you're not passing the functions around correctly for setTimeout.  You're actually passing the result of "$('.wrapper').animate({opacity:1},2500)" to the setTimeout, not the action itself.  This is probably what you want:</p>

```<code>  function smena(){
     $('.wrapper').animate({opacity:0},2500,function(){
           setTimeout (function() {
             $('.wrapper').animate({opacity:1},2500)
           },5000)
      });
  }
  $(document).ready(function() {
       setInterval(smena, 10000);
  });
</code>```

Title: setInterval change background div

Body:
i have code

  function smena(){
     $('.wrapper').animate({opacity:0},2500,function(){
           setTimeout ($('.wrapper').animate({opacity:1},2500),5000)
      });
   }
   $(document).ready(function(){

       setInterval('smena();',10000);
  });

why me animaation jump? i want just change bg for my div "wrapper".

Body:
Basically you're not passing the functions around correctly for setTimeout.  You're actually passing the result of "$('.wrapper').animate({opacity:1},2500)" to the setTimeout, not the action itself.  This is probably what you want:

  function smena(){
     $('.wrapper').animate({opacity:0},2500,function(){
           setTimeout (function() {
             $('.wrapper').animate({opacity:1},2500)
           },5000)
      });
  }
  $(document).ready(function() {
       setInterval(smena, 10000);
  });


问:
How do getters and setters work in Python?
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example

```<code>class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name

    def __str__(self):
        return 'Person[' + self._name + '] is ' + str(self._age)

p1 = Person("Sandeep", 49)
</code>```

I created an object p1 where I set the age 49. As I have made a set_age function so I expect we can change the age of p1 through set_age only, not through the routine way. But it is not happening, I am able to change the age of p1 through , for example, p1._age = 35 as well. Then, what is the advantage to make set_age function, if I am still able to access the attributes directly?

I think, I am missing something, please help.

答:
The reason to use a getter and setter, is if you want to do something more complex than just set and attribute with foo.bar. In your case, set_age has an

isinstance(new_age, int) & new_age>0 & new_age<120
```
<p>check, which is not possible to do with a raw attribute. (Side-note: you should use <code>and</code> instead of <code>&</code>.)</p>
<p>Yes, someone can still do <code>p1._age = -1</code>, and then their code won't work, but why would they? It just makes their code not work.</p>
<p>Your <code>get_name</code> function is less useful than the <code>age</code> one. It basically makes <code>name</code> read-only, which might or might not be useful.</p>
<p>When creating setters and getters in Python, it is usual to use the <code>@property</code> decorator. This means the functions can be called as if they were attributes, so instead of <code>p1.get_name()</code> you can just do <code>p1.name</code>. Similarly <code>p1.set_age(3)</code> becomes <code>p1.age = 3</code>.</p>
<p>You probably want to use the age setter in <code>__init__</code>, because then the age of the <code>Person</code> is validated when it is created.</p>
<p>Here is a version that makes these changes (and a couple of other readability improvements).</p>
<pre class="lang-py prettyprint-override"><code>class Person:
    def __init__(self, name, age):
        self._name = name
        self.age = age

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, new_age):
        if isinstance(new_age, int) and 0 < new_age < 120:
            self._age = new_age

    @property
    def name(self):
        return self._name

    def __str__(self):
        return f"Person[{self.name}] is {self.age}"

p1 = Person("Sandeep", 49)
</code>```

Body:
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name

    def __str__(self):
        return 'Person[' + self._name + '] is ' + str(self._age)

p1 = Person("Sandeep", 49)

I created an object p1 where I set the age 49. As I have made a set_age function so I expect we can change the age of p1 through set_age only, not through the routine way. But it is not happening, I am able to change the age of p1 through , for example, p1._age = 35 as well. Then, what is the advantage to make set_age function, if I am still able to access the attributes directly?

I think, I am missing something, please help.

Body:
The reason to use a getter and setter, is if you want to do something more complex than just set and attribute with foo.bar. In your case, set_age has an

isinstance(new_age, int) & new_age>0 & new_age<120

check, which is not possible to do with a raw attribute. (Side-note: you should use and instead of &.)

Yes, someone can still do p1._age = -1, and then their code won't work, but why would they? It just makes their code not work.

Your get_name function is less useful than the age one. It basically makes name read-only, which might or might not be useful.

When creating setters and getters in Python, it is usual to use the @property decorator. This means the functions can be called as if they were attributes, so instead of p1.get_name() you can just do p1.name. Similarly p1.set_age(3) becomes p1.age = 3.

You probably want to use the age setter in __init__, because then the age of the Person is validated when it is created.

Here is a version that makes these changes (and a couple of other readability improvements).

class Person:
    def __init__(self, name, age):
        self._name = name
        self.age = age

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, new_age):
        if isinstance(new_age, int) and 0 < new_age < 120:
            self._age = new_age

    @property
    def name(self):
        return self._name

    def __str__(self):
        return f"Person[{self.name}] is {self.age}"

p1 = Person("Sandeep", 49)


问:
MySQL - How can I group music together when the names are similar?
I would like to be able to return a single line when the name of some musics are the same or similar, as for example this case:
music with similar names

You can see that the names are the same with an extension like " - JP Ver." or something like that, I would like to be able to group them in one row with the first column incrementing the whole.

My current request to return these lines is as follows:

```<code>select count(id) number, name, sec_to_time(floor(sum(duration) / 1000)) time
from track
where user_id = 'value'
group by name, duration
order by number desc, time desc;
</code>```

I would like to get a result like this

Thank you for reading and responding! I wish you all a good day!

答:
Try:

```<code>SELECT COUNT(name) no,
       TRIM(SUBSTRING_INDEX(name, '-', 1)) namee
FROM track
GROUP BY namee
</code>```

Example: https://onecompiler.com/mysql/3xt3bfev6

Body:
I would like to be able to return a single line when the name of some musics are the same or similar, as for example this case:
music with similar names

You can see that the names are the same with an extension like " - JP Ver." or something like that, I would like to be able to group them in one row with the first column incrementing the whole.

My current request to return these lines is as follows:

select count(id) number, name, sec_to_time(floor(sum(duration) / 1000)) time
from track
where user_id = 'value'
group by name, duration
order by number desc, time desc;

I would like to get a result like this

Thank you for reading and responding! I wish you all a good day!

Body:
Try:

SELECT COUNT(name) no,
       TRIM(SUBSTRING_INDEX(name, '-', 1)) namee
FROM track
GROUP BY namee

Example: https://onecompiler.com/mysql/3xt3bfev6


问:
git clone all remote branches
I have a repository in github with X number of branches and a repository in a closed network.

I need to move all of the repository to the one on the closed network. How do I clone all the branches (not just the default master), so I could then push it to the closed-network one with all the branches existing.

Entering the repo binary is not the issue here.

I want the same result as if I cloned my repo and did git branch to each branch, so it would be initialized locally.

答:
Try this,

to get all branches from remote.

Bash script :

```<code>#!/bin/bash

for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
    git branch --track "${branch##*/}" "$branch"
done
</code>```

or

One line code :

git branch -a | grep -v HEAD | perl -ne 'chomp($_); s|^\*?\s*||; if (m|(.+)/(.+)| && not $d{$2}) {print qq(git branch --track $2 $1/$2\n)} else {$d{$_}=1}' | csh -xfs

Title: git clone all remote branches

Body:
Try this,

to get all branches from remote.

Bash script :

#!/bin/bash

for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
    git branch --track "${branch##*/}" "$branch"
done

or

One line code :

git branch -a | grep -v HEAD | perl -ne 'chomp($_); s|^\*?\s*||; if (m|(.+)/(.+)| && not $d{$2}) {print qq(git branch --track $2 $1/$2\n)} else {$d{$_}=1}' | csh -xfs


问:
NiFi permission denied while attaching Persistent volume
I've created a NiFi cluster on the AWS EKS. The initial deployment was working fine. Later I attached Persistent volume and persistent volume claim to the NiFi setup. After starting the NiFi, I'm getting this error:

```<code>ERROR in ch.qos.logback.core.rolling.RollingFileAppender[USER_FILE] - openFile(/opt/nifi/nifi-current/logs/nifi-user.log,true) call failed. java.io.FileNotFoundException: /opt/nifi/nifi-current/logs/nifi-user.log (Permission denied)
</code>```

As I'm not an expert in NiFi and Kubernetes, I couldn't identify the issue. It looks like a permission issue on NiFi. The NiFi version I'm using is NiFI 1.15.0.

What may be the possible root cause for this? Is that because NiFi is not using the root user or is that something else?

I'm sharing the full error here:

```<code>13:56:22,449 |-ERROR in ch.qos.logback.core.rolling.RollingFileAppender[USER_FILE] - openFile(/opt/nifi/nifi-current/logs/nifi-user.log,true) call failed. java.io.FileNotFoundException: /opt/nifi/nifi-current/logs/nifi-user.log (Permission denied)
    at java.io.FileNotFoundException: /opt/nifi/nifi-current/logs/nifi-user.log (Permission denied)
    at  at java.io.FileOutputStream.open0(Native Method)
    at  at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at  at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at  at ch.qos.logback.core.recovery.ResilientFileOutputStream.<init>(ResilientFileOutputStream.java:26)
    at  at ch.qos.logback.core.FileAppender.openFile(FileAppender.java:204)
    at  at ch.qos.logback.core.FileAppender.start(FileAppender.java:127)
    at  at ch.qos.logback.core.rolling.RollingFileAppender.start(RollingFileAppender.java:100)
    at  at ch.qos.logback.core.joran.action.AppenderAction.end(AppenderAction.java:90)
    at  at ch.qos.logback.core.joran.spi.Interpreter.callEndAction(Interpreter.java:309)
    at  at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:193)
    at  at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:179)
    at  at ch.qos.logback.core.joran.spi.EventPlayer.play(EventPlayer.java:62)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:165)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:152)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:110)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:53)
    at  at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:75)
    at  at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:150)
    at  at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
    at  at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55)
    at  at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
    at  at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
    at  at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
    at  at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
    at  at org.apache.nifi.bootstrap.RunNiFi.<init>(RunNiFi.java:145)
    at  at org.apache.nifi.bootstrap.RunNiFi.main(RunNiFi.java:284)
</code>```

I'm also sharing the Kubernetes manifest part that describe the pv and PVC I used for creating the NiFi cluster:

```<code>        volumeMounts:
          - name: "data"
            mountPath: /opt/nifi/nifi-current/data
          - name: "flowfile-repository"
            mountPath: /opt/nifi/nifi-current/flowfile_repository
          - name: "content-repository"
            mountPath: /opt/nifi/nifi-current/content_repository
          - name: "provenance-repository"
            mountPath: /opt/nifi/nifi-current/provenance_repository
          - name: "logs"
            mountPath: /opt/nifi/nifi-current/logs

  volumeClaimTemplates:
    - metadata:
        name: "data"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 1Gi
    - metadata:
        name: "flowfile-repository"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 10Gi
    - metadata:
        name: "content-repository"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 10Gi
    - metadata:
        name: "provenance-repository"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 10Gi
    - metadata:
        name: "logs"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 5Gi
</code>```

Any help is appreciated.

答:
Assuming you don´t have any issues creating pv and pvc, try to use an extra initContainers section to allow the NiFi user with UID and GID 1000 read and write to the provisioned EBS volume:

initContainers:
- name: fixmount
  image: busybox
  command: [ 'sh', '-c', 'chown -R 1000:1000 /opt/nifi/nifi-current/logs' ]
  volumeMounts:
  - name: logs
    mountPath: /opt/nifi/nifi-current/logs
```

I hope this will help solve your issues. Here is the official Kubernetes documentation page Init Containers.

Body:
I've created a NiFi cluster on the AWS EKS. The initial deployment was working fine. Later I attached Persistent volume and persistent volume claim to the NiFi setup. After starting the NiFi, I'm getting this error:

ERROR in ch.qos.logback.core.rolling.RollingFileAppender[USER_FILE] - openFile(/opt/nifi/nifi-current/logs/nifi-user.log,true) call failed. java.io.FileNotFoundException: /opt/nifi/nifi-current/logs/nifi-user.log (Permission denied)

As I'm not an expert in NiFi and Kubernetes, I couldn't identify the issue. It looks like a permission issue on NiFi. The NiFi version I'm using is NiFI 1.15.0.

What may be the possible root cause for this? Is that because NiFi is not using the root user or is that something else?

I'm sharing the full error here:

13:56:22,449 |-ERROR in ch.qos.logback.core.rolling.RollingFileAppender[USER_FILE] - openFile(/opt/nifi/nifi-current/logs/nifi-user.log,true) call failed. java.io.FileNotFoundException: /opt/nifi/nifi-current/logs/nifi-user.log (Permission denied)
    at java.io.FileNotFoundException: /opt/nifi/nifi-current/logs/nifi-user.log (Permission denied)
    at  at java.io.FileOutputStream.open0(Native Method)
    at  at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at  at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at  at ch.qos.logback.core.recovery.ResilientFileOutputStream.<init>(ResilientFileOutputStream.java:26)
    at  at ch.qos.logback.core.FileAppender.openFile(FileAppender.java:204)
    at  at ch.qos.logback.core.FileAppender.start(FileAppender.java:127)
    at  at ch.qos.logback.core.rolling.RollingFileAppender.start(RollingFileAppender.java:100)
    at  at ch.qos.logback.core.joran.action.AppenderAction.end(AppenderAction.java:90)
    at  at ch.qos.logback.core.joran.spi.Interpreter.callEndAction(Interpreter.java:309)
    at  at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:193)
    at  at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:179)
    at  at ch.qos.logback.core.joran.spi.EventPlayer.play(EventPlayer.java:62)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:165)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:152)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:110)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:53)
    at  at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:75)
    at  at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:150)
    at  at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
    at  at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55)
    at  at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
    at  at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
    at  at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
    at  at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
    at  at org.apache.nifi.bootstrap.RunNiFi.<init>(RunNiFi.java:145)
    at  at org.apache.nifi.bootstrap.RunNiFi.main(RunNiFi.java:284)

I'm also sharing the Kubernetes manifest part that describe the pv and PVC I used for creating the NiFi cluster:

        volumeMounts:
          - name: "data"
            mountPath: /opt/nifi/nifi-current/data
          - name: "flowfile-repository"
            mountPath: /opt/nifi/nifi-current/flowfile_repository
          - name: "content-repository"
            mountPath: /opt/nifi/nifi-current/content_repository
          - name: "provenance-repository"
            mountPath: /opt/nifi/nifi-current/provenance_repository
          - name: "logs"
            mountPath: /opt/nifi/nifi-current/logs

  volumeClaimTemplates:
    - metadata:
        name: "data"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 1Gi
    - metadata:
        name: "flowfile-repository"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 10Gi
    - metadata:
        name: "content-repository"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 10Gi
    - metadata:
        name: "provenance-repository"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 10Gi
    - metadata:
        name: "logs"
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: "gp2"
        resources:
          requests:
            storage: 5Gi

Any help is appreciated.

Body:
Assuming you don´t have any issues creating pv and pvc, try to use an extra initContainers section to allow the NiFi user with UID and GID 1000 read and write to the provisioned EBS volume:

initContainers:
- name: fixmount
  image: busybox
  command: [ 'sh', '-c', 'chown -R 1000:1000 /opt/nifi/nifi-current/logs' ]
  volumeMounts:
  - name: logs
    mountPath: /opt/nifi/nifi-current/logs

I hope this will help solve your issues. Here is the official Kubernetes documentation page Init Containers.


问:
How to enable developer options on Huawei device (Cloud debugging) for using Fake GPS?
I don't have a physical Huawei device so I use Huawei Cloud Debugging to test my app.

However, I can't test all features without using a fake gps location.

I didn't find such a function in the emulator itself, so I want to do it with a third party fake gps emulation app. But for this I need to enable developer mode, on real Huawei devices this is done through the “Settings”>” System”>” About Phone” and tapping 7 times on “Build Number”, but when I click even 20 times on the menu item, nothing happens!
Also, clicking on any other field in the device information does not help - the developer mode does not turn on

I will be very grateful if you tell me how to emulate the user's location in any way!

答:
We contacted Huawei representatives and it turned out that at the moment the geolocation mock on the emulator is available only for developers from China

However, Huawei representatives can provide a physical device for development (contact them for details)


问:
Getfem++ is installed on Ubuntu 18.04, but it is not working
I installed Python GetFEM++ using these two lines in Ubuntu 18.04

```<code>sudo apt-get update
sudo apt-get install python-getfem++
</code>```

Then I started writing my code on Anaconda,

```<code>import getfem
m = mesh('cartesian', range(0, 3), range(0,3))
</code>```

I got this error:

```<code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-7f9e03c41e63> in <module>
      1 import getfem
----> 2 m = mesh('cartesian', range(0, 3), range(0,3))

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

What should I do? Is it necessary to update Ubuntu 18.04 or install other packages?

答:
It should either be

```<code>import getfem
m = getfem.Mesh('cartesian', range(0, 3), range(0,3))
</code>```

or

```<code>import getfem as gf
m = gf.Mesh('cartesian', range(0, 3), range(0,3))
</code>```

Body:
I installed Python GetFEM++ using these two lines in Ubuntu 18.04

sudo apt-get update
sudo apt-get install python-getfem++

Then I started writing my code on Anaconda,

import getfem
m = mesh('cartesian', range(0, 3), range(0,3))

I got this error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-7f9e03c41e63> in <module>
      1 import getfem
----> 2 m = mesh('cartesian', range(0, 3), range(0,3))

NameError: name 'mesh' is not defined

What should I do? Is it necessary to update Ubuntu 18.04 or install other packages?

Body:
It should either be

import getfem
m = getfem.Mesh('cartesian', range(0, 3), range(0,3))

or

import getfem as gf
m = gf.Mesh('cartesian', range(0, 3), range(0,3))


问:
Extending Global in jest with typescript
So I'm trying to have some global variables to use easily in my test files so I researched a lot and managed to make a jest setup file that runs before all my test files to initialize the global variables and this is the setup.ts file

```<code>import  app  from'../src/express';
import request from 'supertest';

//Set Express app as global
global.app = request(app);

//TODO: Add global data
</code>```

It's working fine but the autocomplete isn't working in my test files so after searching for the problem I found out I had to merge my new added variables to NodeJS.Global and ended up doing so in a file called global.d.ts

```<code>
declare global {
    namespace NodeJS {
     interface Global {
       app: import('supertest').SuperTest<import('supertest').Test>;
     }
   }
 }

</code>```

but still, nothing is working tried other solutions but none worked.

Note

ts.config

```<code>"target": "es2019",
    "moduleResolution": "node",
    "module": "commonjs",
    "lib": ["es2019"],
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "resolveJsonModule": true,
    "alwaysStrict": true,
    "removeComments": true,
    "noImplicitReturns": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "allowJs": true /* Allow javascript files to be compiled. */,
    "typeRoots": [
      "./types",
      "node_modules/@types",

    ] /* List of folders to include type definitions from. */,
    "types": [ "node","jest"],
  },
  "include": ["./src/**/*", "./utils/**/*", "localization", "./tests/**/*"],
  "exclude": ["./seeds/**/*"]
</code>```

jest.config.ts

```<code>/*
 * For a detailed explanation regarding each configuration property and type check, visit:
 * https://jestjs.io/docs/configuration
 */

export default {
  clearMocks: true,
  coverageProvider: "v8",
  coverageDirectory: "coverage",
  collectCoverage: true,
  setupFiles: ["<rootDir>/tests/setup.ts"],
  testMatch: [
    "<rootDir>/tests/**/*.test.ts"
  ],

};

</code>```

答:
I had a similar usecase, where I needed a safeSubscribe helper available globally in all my tests.

This function would perform the subscription and then do the unsubscription in a general afterEach hook, executed after any test.

Here is how I achieved that:

```<code>// test/setup/safe-subscribe.ts
import { Observable, Subscription } from 'rxjs';

const subscriptions: Subscription[] = [];
const safeSubscribeFn = <T>(source: Observable<T>): T[] => {
  const res: T[] = [];
  const subscription = source.subscribe((value) => {
    res.push(value);
  });
  subscriptions.push(subscription);
  return res;
};

global.safeSubscribe = safeSubscribeFn; // Add helper implementation

global.afterEach(() => {
  while (subscriptions.length > 0) {
    const subscription = subscriptions.pop();
    subscription?.unsubscribe();
  }
});

declare global {
  // See: https://stackoverflow.com/a/68328575/12292636
  var safeSubscribe: typeof safeSubscribeFn;
}
</code>```

// jest.config.js
module.exports = {
  ...,
  setupFilesAfterEnv: [
    ...,
    './test/setup/safe-subscribe.ts', // Import your setup in jest config
  ],
};
```
<pre class="lang-json prettyprint-override"><code>// tsconfig.spec.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "module": "commonjs",
    "types": ["jest", "node"],
    "resolveJsonModule": true,
    "esModuleInterop": true,
  },
  "files": ["src/polyfills.ts", "test/setup/*.ts"], // Add it there
  "include": ["src/**/*.d.ts", "src/**/*.spec.ts", "test/setup/*.ts"] // And also there
}
</code>```

Now, it is possible to use the globally-defined safeSubscribe in the tests:

```<code>// foo.spec.ts
it('should emit value', () => {
  // Given
  const outputs = safeSubscribe(service.myObservable$); // global import with typescript stuff ✔
  // When
  actions$.next(action);
  // Then
  expect(outputs).toHaveLength(1);
});
</code>```

Body:
So I'm trying to have some global variables to use easily in my test files so I researched a lot and managed to make a jest setup file that runs before all my test files to initialize the global variables and this is the setup.ts file

import  app  from'../src/express';
import request from 'supertest';

//Set Express app as global
global.app = request(app);

//TODO: Add global data

It's working fine but the autocomplete isn't working in my test files so after searching for the problem I found out I had to merge my new added variables to NodeJS.Global and ended up doing so in a file called global.d.ts

declare global {
    namespace NodeJS {
     interface Global {
       app: import('supertest').SuperTest<import('supertest').Test>;
     }
   }
 }

but still, nothing is working tried other solutions but none worked.

Note

ts.config

"target": "es2019",
    "moduleResolution": "node",
    "module": "commonjs",
    "lib": ["es2019"],
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "resolveJsonModule": true,
    "alwaysStrict": true,
    "removeComments": true,
    "noImplicitReturns": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "allowJs": true /* Allow javascript files to be compiled. */,
    "typeRoots": [
      "./types",
      "node_modules/@types",

    ] /* List of folders to include type definitions from. */,
    "types": [ "node","jest"],
  },
  "include": ["./src/**/*", "./utils/**/*", "localization", "./tests/**/*"],
  "exclude": ["./seeds/**/*"]

jest.config.ts

/*
 * For a detailed explanation regarding each configuration property and type check, visit:
 * https://jestjs.io/docs/configuration
 */

export default {
  clearMocks: true,
  coverageProvider: "v8",
  coverageDirectory: "coverage",
  collectCoverage: true,
  setupFiles: ["<rootDir>/tests/setup.ts"],
  testMatch: [
    "<rootDir>/tests/**/*.test.ts"
  ],

};

Body:
I had a similar usecase, where I needed a safeSubscribe helper available globally in all my tests.

This function would perform the subscription and then do the unsubscription in a general afterEach hook, executed after any test.

Here is how I achieved that:

// test/setup/safe-subscribe.ts
import { Observable, Subscription } from 'rxjs';

const subscriptions: Subscription[] = [];
const safeSubscribeFn = <T>(source: Observable<T>): T[] => {
  const res: T[] = [];
  const subscription = source.subscribe((value) => {
    res.push(value);
  });
  subscriptions.push(subscription);
  return res;
};

global.safeSubscribe = safeSubscribeFn; // Add helper implementation

global.afterEach(() => {
  while (subscriptions.length > 0) {
    const subscription = subscriptions.pop();
    subscription?.unsubscribe();
  }
});

declare global {
  // See: https://stackoverflow.com/a/68328575/12292636
  var safeSubscribe: typeof safeSubscribeFn;
}

// jest.config.js
module.exports = {
  ...,
  setupFilesAfterEnv: [
    ...,
    './test/setup/safe-subscribe.ts', // Import your setup in jest config
  ],
};

// tsconfig.spec.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "module": "commonjs",
    "types": ["jest", "node"],
    "resolveJsonModule": true,
    "esModuleInterop": true,
  },
  "files": ["src/polyfills.ts", "test/setup/*.ts"], // Add it there
  "include": ["src/**/*.d.ts", "src/**/*.spec.ts", "test/setup/*.ts"] // And also there
}

Now, it is possible to use the globally-defined safeSubscribe in the tests:

// foo.spec.ts
it('should emit value', () => {
  // Given
  const outputs = safeSubscribe(service.myObservable$); // global import with typescript stuff ✔
  // When
  actions$.next(action);
  // Then
  expect(outputs).toHaveLength(1);
});


问:
Angular Error: Cannot match any routes error redirect to 404
I have so many url, and sometimes I can not handle all error with

core.js:6479 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'

Does someone knows some common solution to handle this kind of error, and redirect user to 404, somekind of interceptor or something else, thank

答:
You can add the wild card in route, If path does not match then it will redirect to error component which will be common for handling error page.

eg.

```<code>const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: '',   redirectTo: '/about', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent },  // Wildcard route for a 404 page
];
</code>```

Here,

If a non existent page is called, then the first two route gets failed. But, the final wildcard route will succeed and the PageNotFoundComponent gets called.

Body:
You can add the wild card in route, If path does not match then it will redirect to error component which will be common for handling error page.

eg.

const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: '',   redirectTo: '/about', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent },  // Wildcard route for a 404 page
];

Here,

If a non existent page is called, then the first two route gets failed. But, the final wildcard route will succeed and the PageNotFoundComponent gets called.


问:
Permission denied in firebase cloud functions
In firebase cloud function I am getting access denied on admin-firebase on read or write to realtime database.
This https://github.com/firebase/firebase-functions/issues/16 does not solve my problem , App engine default service account rights are set to Editor.

I also have Node.js admin sdk configured with service Account Key and there  everything works as expected.

I have set default security rules in db.

This is an example function

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
admin.database.enableLogging(true);

//event fires properly
exports.sendNotif = functions.database.ref('/messages/{roomId}/{msgKey}')
    .onWrite(event => {
        const message = event.data.val().text;
    //this executes as expected
        console.log(message);

//here I am getting access denied and consequently function timeout after 60 seconds.
        return admin.database().ref('/userFCMTokens').once('value')
            .then(snap => console.log(snap.val()));
    });
</code>```

and here is log snippet from firebase  realtime db

```<code>Realtime connection established.
2017-06-08T15:19:03.168Z I sendNotif: p:0: connection ready
2017-06-08T15:19:03.168Z I sendNotif: p:0: {"r":28,"a":"gauth","b":{"cred”:”********************”}}
2017-06-08T15:19:03.169Z I sendNotif: p:0: Listen on /userFCMTokens for default
2017-06-08T15:19:03.169Z I sendNotif: p:0: {"r":29,"a":"q","b":{"p":"/userFCMTokens","h":""}}
2017-06-08T15:19:03.538Z I sendNotif: p:0: from server: {"r":28,"b":{"s":"permission_denied","d":"Access denied."}}
2017-06-08T15:19:03.538Z I sendNotif: Auth token revoked: permission_denied/Access denied.
2017-06-08T15:19:03.538Z I sendNotif: c:0:13: Closing realtime connection.
2017-06-08T15:19:03.538Z I sendNotif: c:0:13: Shutting down all connections
2017-06-08T15:19:03.538Z I sendNotif: c:0:13:0 WebSocket is being closed
</code>```

Here without logging on realtime db for brevity:

```<code>2017-06-08T15:26:23.164035495Z D sendNotif: Function execution started
2017-06-08T15:26:23.164076543Z D sendNotif: Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
2017-06-08T15:26:23.539Z I sendNotif: message console logged
2017-06-08T15:27:23.165321703Z D sendNotif: Function execution took 60002 ms, finished with status: 'timeout'
</code>```

Why I can’t read and write using admin in cloud functions?

答: I needed that anyone from my app could use a callable https function so I had to assign the All users to the Cloud Functions Invoker permission to the specific function in GCP.

Body:
In firebase cloud function I am getting access denied on admin-firebase on read or write to realtime database.
This https://github.com/firebase/firebase-functions/issues/16 does not solve my problem , App engine default service account rights are set to Editor.

I also have Node.js admin sdk configured with service Account Key and there  everything works as expected.

I have set default security rules in db.

This is an example function

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
admin.database.enableLogging(true);

//event fires properly
exports.sendNotif = functions.database.ref('/messages/{roomId}/{msgKey}')
    .onWrite(event => {
        const message = event.data.val().text;
    //this executes as expected
        console.log(message);

//here I am getting access denied and consequently function timeout after 60 seconds.
        return admin.database().ref('/userFCMTokens').once('value')
            .then(snap => console.log(snap.val()));
    });

and here is log snippet from firebase  realtime db

Realtime connection established.
2017-06-08T15:19:03.168Z I sendNotif: p:0: connection ready
2017-06-08T15:19:03.168Z I sendNotif: p:0: {"r":28,"a":"gauth","b":{"cred”:”********************”}}
2017-06-08T15:19:03.169Z I sendNotif: p:0: Listen on /userFCMTokens for default
2017-06-08T15:19:03.169Z I sendNotif: p:0: {"r":29,"a":"q","b":{"p":"/userFCMTokens","h":""}}
2017-06-08T15:19:03.538Z I sendNotif: p:0: from server: {"r":28,"b":{"s":"permission_denied","d":"Access denied."}}
2017-06-08T15:19:03.538Z I sendNotif: Auth token revoked: permission_denied/Access denied.
2017-06-08T15:19:03.538Z I sendNotif: c:0:13: Closing realtime connection.
2017-06-08T15:19:03.538Z I sendNotif: c:0:13: Shutting down all connections
2017-06-08T15:19:03.538Z I sendNotif: c:0:13:0 WebSocket is being closed

Here without logging on realtime db for brevity:

2017-06-08T15:26:23.164035495Z D sendNotif: Function execution started
2017-06-08T15:26:23.164076543Z D sendNotif: Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
2017-06-08T15:26:23.539Z I sendNotif: message console logged
2017-06-08T15:27:23.165321703Z D sendNotif: Function execution took 60002 ms, finished with status: 'timeout'

Why I can’t read and write using admin in cloud functions?


问:
How to configure OAuth Code flow wihout discovery
It is my first try with OAuth. I am using Angular 13 + angular-oauth2-oidc library and I am trying to configure code flow. My problem is that in tutorial discovery document is used by default but my auth server does not have anything like that so when in the beggining app asking about identity_provider_url/.well-known/openid-configuration I am getting an 404 error. Question is how to configure code flow without loading discovery document from auth server?
I found only configuration without discovery document for implicit flow.
That is how my code looks like right now:

auth.config.ts

```<code>import { AuthConfig } from 'angular-oauth2-oidc';

export const authCodeFlowConfig: AuthConfig = {
  // Url of the Identity Provider
  issuer: '**************', // identity provider URL,
  redirectUri: window.location.origin + '/index.html',
  clientId: 'spa',
  dummyClientSecret: 'secret',
  responseType: 'code',
  scope: 'read, write',
  showDebugInformation: true,
};
</code>```

app.component.ts

```<code>import {Component} from '@angular/core';
import {authCodeFlowConfig} from './sso.confiig';
import {OAuthService} from 'angular-oauth2-oidc';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'sso';

  constructor(private oAuthService: OAuthService) {
    this.oAuthService.configure(authCodeFlowConfig);
    this.oauthService.loadDiscoveryDocumentAndTryLogin(); // I don`t want this
  }
}
</code>```

login.component.ts

```<code>import {Component, OnInit} from '@angular/core';
import {OAuthErrorEvent, OAuthService} from 'angular-oauth2-oidc';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(private oAuthService: OAuthService) {
    this.oAuthService.events.subscribe(e => (e instanceof OAuthErrorEvent) ? console.error(e) : console.warn(e));
  }

  public async login(): Promise<void> {
    await this.oAuthService.initCodeFlow();
  }

  public logout(): void {
    this.oAuthService.logOut();
  }

  public get userName() {
    let claims = this.oAuthService.getIdentityClaims();
    if (!claims) return null;
    return claims;
  }
}
</code>```

答:
Extending auth.config about additional loginUrl and tokenUrl solved the issue.

This is finall version of my config file:

```<code>export const OAUTH_CONFIG: AuthConfig = {
  issuer: environment.identityProviderBaseUrl,
  loginUrl: environment.identityProviderLoginUrl,
  logoutUrl: environment.identityProviderLogoutUrl,
  redirectUri: environment.identityProvideRedirectUrl,
  tokenEndpoint: environment.identityProviderTokenUrl,
  clientId: environment.clientId,
  dummyClientSecret: environment.clientSecret,
  responseType: 'code',
  requireHttps: false,
  scope: 'write',
  showDebugInformation: true,
  oidc: false,
  useIdTokenHintForSilentRefresh: false
};
</code>```

Of corse then we should remember to remove loadDiscoveryDocumentAndTryLogin() .

```<code>  public configureCodeFlow(): void {
    this.authService.configure(OAUTH_CONFIG);
    this.authService.setupAutomaticSilentRefresh(undefined, 'access_token');
    this.authService.tryLoginCodeFlow();
  }
</code>```

Body:
It is my first try with OAuth. I am using Angular 13 + angular-oauth2-oidc library and I am trying to configure code flow. My problem is that in tutorial discovery document is used by default but my auth server does not have anything like that so when in the beggining app asking about identity_provider_url/.well-known/openid-configuration I am getting an 404 error. Question is how to configure code flow without loading discovery document from auth server?
I found only configuration without discovery document for implicit flow.
That is how my code looks like right now:

auth.config.ts

import { AuthConfig } from 'angular-oauth2-oidc';

export const authCodeFlowConfig: AuthConfig = {
  // Url of the Identity Provider
  issuer: '**************', // identity provider URL,
  redirectUri: window.location.origin + '/index.html',
  clientId: 'spa',
  dummyClientSecret: 'secret',
  responseType: 'code',
  scope: 'read, write',
  showDebugInformation: true,
};

app.component.ts

import {Component} from '@angular/core';
import {authCodeFlowConfig} from './sso.confiig';
import {OAuthService} from 'angular-oauth2-oidc';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'sso';

  constructor(private oAuthService: OAuthService) {
    this.oAuthService.configure(authCodeFlowConfig);
    this.oauthService.loadDiscoveryDocumentAndTryLogin(); // I don`t want this
  }
}

login.component.ts

import {Component, OnInit} from '@angular/core';
import {OAuthErrorEvent, OAuthService} from 'angular-oauth2-oidc';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(private oAuthService: OAuthService) {
    this.oAuthService.events.subscribe(e => (e instanceof OAuthErrorEvent) ? console.error(e) : console.warn(e));
  }

  public async login(): Promise<void> {
    await this.oAuthService.initCodeFlow();
  }

  public logout(): void {
    this.oAuthService.logOut();
  }

  public get userName() {
    let claims = this.oAuthService.getIdentityClaims();
    if (!claims) return null;
    return claims;
  }
}

Body:
Extending auth.config about additional loginUrl and tokenUrl solved the issue.

This is finall version of my config file:

export const OAUTH_CONFIG: AuthConfig = {
  issuer: environment.identityProviderBaseUrl,
  loginUrl: environment.identityProviderLoginUrl,
  logoutUrl: environment.identityProviderLogoutUrl,
  redirectUri: environment.identityProvideRedirectUrl,
  tokenEndpoint: environment.identityProviderTokenUrl,
  clientId: environment.clientId,
  dummyClientSecret: environment.clientSecret,
  responseType: 'code',
  requireHttps: false,
  scope: 'write',
  showDebugInformation: true,
  oidc: false,
  useIdTokenHintForSilentRefresh: false
};

Of corse then we should remember to remove loadDiscoveryDocumentAndTryLogin() .

  public configureCodeFlow(): void {
    this.authService.configure(OAUTH_CONFIG);
    this.authService.setupAutomaticSilentRefresh(undefined, 'access_token');
    this.authService.tryLoginCodeFlow();
  }


问:
How could we assign environment variable to key "topicName" in service-bus-trigger/function.json
I have an azure function with type as serviceBusTrigger.
Right now the value of "topicName" is considered as a string.
I want to add the topicName as an enviroment variable (AZURE_FUNC_TOPIC_NAME) in app.settings.json.
would like to have value of this variable AZURE_FUNC_TOPIC_NAME to be assigned to the key topicName in below function.json
How could i achieve it?</p>
```<code>{
  "bindings": [
    {
      "name": "mySbMsg",
      "type": "serviceBusTrigger",
      "direction": "in",
      "topicName": "AZURE_SERVICE_BUS_TOPIC",
      "connection": "",
      "subscriptionName": ""
    }
  ],
  "disabled": false
}
</code>```

答:
In local.settings.json file, define your variables like topic name in the key-value format and get that environment variable in your function code.

To get an environment variable or an app setting value, use System.Environment.GetEnvironmentVariable, as shown below.

public static string GetEnvironmentVariable(string name)
{
    return name + ": " +
        System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
```

Reference: https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#environment-variables

Body:
I have an azure function with type as serviceBusTrigger.
Right now the value of "topicName" is considered as a string.
I want to add the topicName as an enviroment variable (AZURE_FUNC_TOPIC_NAME) in app.settings.json.
would like to have value of this variable AZURE_FUNC_TOPIC_NAME to be assigned to the key topicName in below function.json
How could i achieve it?

{
  "bindings": [
    {
      "name": "mySbMsg",
      "type": "serviceBusTrigger",
      "direction": "in",
      "topicName": "AZURE_SERVICE_BUS_TOPIC",
      "connection": "",
      "subscriptionName": ""
    }
  ],
  "disabled": false
}

Body:
In local.settings.json file, define your variables like topic name in the key-value format and get that environment variable in your function code.

To get an environment variable or an app setting value, use System.Environment.GetEnvironmentVariable, as shown below.

public static string GetEnvironmentVariable(string name)
{
    return name + ": " +
        System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}

Reference: https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#environment-variables