问:
show filename with matching word from grep only
I am trying to find which words happened in logfiles plus show the logfilename for anything that matches following pattern:

```<code>'BA10\|BA20\|BA21\|BA30\|BA31\|BA00'
</code>```

so if file dummylogfile.log contains BA10002 I would like to get a result such as:

dummylogfile.log:BA10002

it is totally fine if the logfile shows up twice for duplicate matches.

the closest I got is:

```<code>for f in $(find . -name '*.err' -exec grep -l 'BA10\|BA20\|BA21\|BA30\|BA31\|BA00' {} \+);do printf $f;printf ':';grep -o  'BA10\|BA20\|BA21\|BA30\|BA31\|BA00' $f;done
</code>```

but this gives things like:

```<code>./register-05-14-11-53-59_24154.err:BA10
BA10
./register_mdw_files_2020-05-14-11-54-32_24429.err:BA10
BA10
./process_tables.2020-05-18-11-18-09_11428.err:BA30
./status_load_2020-05-18-11-35-31_9185.err:BA30
</code>```

so,

1) there are empty lines with only the second match and

2) the full match (e.g., BA10004) is not shown.

thanks for the help

答:
There are a couple of options you can pass to grep:

-H: This will report the filename and the match

-o: only show the match, not the full line

-w: The match must represent a full word (string build from [A-Za-z0-9_])

If we look at your regex, you use BA01, this will match only BA01 which can appear anywhere in the text, also mid word. If you want the regex to match a full word, it should read BA01[[:alnum:]_]* which adds any sequence of word-constituent characters (equivalent to [A-Za-z0-9_]). You can test this with

```<code>$ echo "foo BA01234 barBA012" | grep -Ho "BA01"
(standard input):BA01
(standard input):BA01
$ echo "foo BA01234 barBA012" | grep -How "BA01"
$ echo "foo BA01234 barBA012" | grep -How "BA01[[:alnum:]_]*"
(standard input):BA01234
</code>```

So your grep should look like

```<code>grep -How "\('BA10\|BA20\|BA21\|BA30\|BA31\|BA00'\)[[:alnum:]_]*" *.err
</code>```

Body:
I am trying to find which words happened in logfiles plus show the logfilename for anything that matches following pattern:

'BA10\|BA20\|BA21\|BA30\|BA31\|BA00'

so if file dummylogfile.log contains BA10002 I would like to get a result such as:

dummylogfile.log:BA10002

it is totally fine if the logfile shows up twice for duplicate matches.

the closest I got is:

for f in $(find . -name '*.err' -exec grep -l 'BA10\|BA20\|BA21\|BA30\|BA31\|BA00' {} \+);do printf $f;printf ':';grep -o  'BA10\|BA20\|BA21\|BA30\|BA31\|BA00' $f;done

but this gives things like:

./register-05-14-11-53-59_24154.err:BA10
BA10
./register_mdw_files_2020-05-14-11-54-32_24429.err:BA10
BA10
./process_tables.2020-05-18-11-18-09_11428.err:BA30
./status_load_2020-05-18-11-35-31_9185.err:BA30

so,

1) there are empty lines with only the second match and

2) the full match (e.g., BA10004) is not shown.

thanks for the help

Body:
There are a couple of options you can pass to grep:

-H: This will report the filename and the match

-o: only show the match, not the full line

-w: The match must represent a full word (string build from [A-Za-z0-9_])

If we look at your regex, you use BA01, this will match only BA01 which can appear anywhere in the text, also mid word. If you want the regex to match a full word, it should read BA01[[:alnum:]_]* which adds any sequence of word-constituent characters (equivalent to [A-Za-z0-9_]). You can test this with

$ echo "foo BA01234 barBA012" | grep -Ho "BA01"
(standard input):BA01
(standard input):BA01
$ echo "foo BA01234 barBA012" | grep -How "BA01"
$ echo "foo BA01234 barBA012" | grep -How "BA01[[:alnum:]_]*"
(standard input):BA01234

So your grep should look like

grep -How "\('BA10\|BA20\|BA21\|BA30\|BA31\|BA00'\)[[:alnum:]_]*" *.err


来源: stackexchange

问:
How to list all documents in an RxDB collection?
In RxDB, to list all documents in a collection on a remote db that has documents, I've tried:

 myCollection.dump()
  .then(json => console.dir(json));
```

<p>and </p>

<pre class="lang-js prettyprint-override"><code>myCollection.find().exec() // <- find all documents
  .then(documents => console.dir(documents));
</code>```

from the documentation: https://rxdb.info/rx-collection.html#dump
https://rxdb.info/rx-document.html#find

but both do a _find post with body:

```<code>{"selector":{"_id":{}}}
</code>```

that return an empty docs [] array. That same _find selector executed outside of RxDB also returns an empty docs array.

If I add documents to the collection with myCollection.upsert(), the doc is added to the remote server and then appears as a response in the two above calls. But maybe only from what's stored in memory, as there's still this remote _find POST with an empty docs: [] response. So on a page refresh those list calls are empty again.

I'm using:

```<code>    "pouchdb-adapter-http": "7.0.0",
    "rxdb": "8.0.4",
    "rxjs": "6.3.3"
</code>```

答: You can head on to rxdb.info since the major version release 9.0.0 has announced several improvements in querying the document fields in a better way</p>

ContentLicense: CC BY-SA 4.0

Body:
In RxDB, to list all documents in a collection on a remote db that has documents, I've tried:

 myCollection.dump()
  .then(json => console.dir(json));

and

myCollection.find().exec() // <- find all documents
  .then(documents => console.dir(documents));

from the documentation: https://rxdb.info/rx-collection.html#dump
https://rxdb.info/rx-document.html#find

but both do a _find post with body:

{"selector":{"_id":{}}}

that return an empty docs [] array. That same _find selector executed outside of RxDB also returns an empty docs array.

If I add documents to the collection with myCollection.upsert(), the doc is added to the remote server and then appears as a response in the two above calls. But maybe only from what's stored in memory, as there's still this remote _find POST with an empty docs: [] response. So on a page refresh those list calls are empty again.

I'm using:

    "pouchdb-adapter-http": "7.0.0",
    "rxdb": "8.0.4",
    "rxjs": "6.3.3"


问:
how to create a scala sbt project model which represents a model to other sbt projects?
i have a scala js sbt project, i developped in this project new user interface components.

the person p1 has a project with the same structure (same build.properties & plugins.sbt), how can he access to my user interface components.

Should i add some specification in build.sbt ?

答:
If you want to share some project settings, you can create a sbt plugin - it will allow you to have some common settings, add dependencies to other sbt plugins and even override their configuration. See for example sbt-softwaremill as a example of plugin that is used to share some commons between projects.

It won't magically update all configs, because:

build.properties is evaluated before the sbt code is run

you have to add this plugin to plugins.sbt

you have to create project structure in each project

Any more config sharing than that is theoretically possible by e.g. using git submodules and commiting symlinks to repo, but that would be pretty wrong - any change to one project would result in a change in another project, and you have them separated for a reason - if both projects were the same you would have one project in the first place.

And if you are need to share the code itself, you can build the code, publish it to an artifactory and add dependency in another project.

But that's only if you really have two projects, and it's entirely possible that you just need to have one git project with different branches, where ever developer would work on their own branch and then merge changes to common branch, bacause that's the point of using git.


问:
Rebuilding original signal from frequencies, amplitude, and phase obtained after doing an fft
Rebuilding original signal from frequencies, amplitude, and phase obtained after doing an fft.

Greetings

I'm trying to rebuild a signal from the frequency, amplitude, and phase obtained after I do an fft of a signal, but when I try and combine the fft data (frequency, amplitude, and phase) back to see if I get a similar signal, the pattern is a little off.  I think it has
to do with my formula which may be a little incorrect.

The formula I'm using to combine the data is:

```<code>amplitude*sin(2*pi*time*frequency+phase)+amplitude*cos(2*pi*time*frequency+phase);
</code>```

Please note:
At the moment I don't want to use IFFT due to the fact that I will be editing the amplitude and frequencies before the calculations are done

An image of the plot is below.  The top one is the original signal and the bottom one is the signal created with the equation.  If you want to know I'm using matlab but I think the problem is with the equation.

tia

答:
I don't see why you want both a sin and a cos term in your equation: this should do it...

```<code>amplitude*sin(2*pi*time*frequency+phase);
</code>```

Using both sin and cosine terms will, unless there is something odd about the FFT, cause scaling issues and a phase shift. However I do not know if that would explain the distortion you've seen. That may be due to something to do with the FFT block sizes you have used.

ContentLicense: CC BY-SA 3.0

Body:
Rebuilding original signal from frequencies, amplitude, and phase obtained after doing an fft.

Greetings

I'm trying to rebuild a signal from the frequency, amplitude, and phase obtained after I do an fft of a signal, but when I try and combine the fft data (frequency, amplitude, and phase) back to see if I get a similar signal, the pattern is a little off.  I think it has
to do with my formula which may be a little incorrect.

The formula I'm using to combine the data is:

amplitude*sin(2*pi*time*frequency+phase)+amplitude*cos(2*pi*time*frequency+phase);

Please note:
At the moment I don't want to use IFFT due to the fact that I will be editing the amplitude and frequencies before the calculations are done

An image of the plot is below.  The top one is the original signal and the bottom one is the signal created with the equation.  If you want to know I'm using matlab but I think the problem is with the equation.

tia

Body:
I don't see why you want both a sin and a cos term in your equation: this should do it...

amplitude*sin(2*pi*time*frequency+phase);

Using both sin and cosine terms will, unless there is something odd about the FFT, cause scaling issues and a phase shift. However I do not know if that would explain the distortion you've seen. That may be due to something to do with the FFT block sizes you have used.


问:
Compare Nested Objects and save difference in new object using Javascript
I have two Javascript objects

```<code>var order1 = {
    sandwich: 'tuna',
    chips: true,
    drink: 'soda',
    order: 1,
    toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 20, PreferredFlag: false, SupportedFlag: true}],
    details: {
        name: 'Chris',
        phone: '555-555-5555',
        email: 'no@thankyou.com'
    },
    otherVal1: '1'
};

var order2 = {
    sandwich: 'turkey',
    chips: true,
    drink: 'soda',
    order: 2,
    toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, PreferredFlag: false, SupportedFlag: false}, {VendorNumber: 20, PreferredFlag: true, SupportedFlag: true}],
    details: {
        name: 'Jon',
        phone: '(555) 555-5555',
        email: 'yes@please.com'
    },
    otherVal1: '2'
};
</code>```

What I need is to compare these two objects (order1 is existing and order2 is the edited data) and store the difference in a new variable named var order3. However if there is an array inside an object like the toppings array to be copied as whole with the changes.

In short the result should be

```<code>{
  details: {
    email: "yes@please.com",
    name: "Jon",
    phone: "(555) 555-5555"
  },
  order: 2,
  otherVal1: "2",
  sandwich: "turkey",
  toppings: [{
  PreferredFlag: false,
  SupportedFlag: true,
  VendorNumber: 18
}, {
  PreferredFlag: false,
  SupportedFlag: false,
  VendorNumber: 19
}, {
  PreferredFlag: true,
  SupportedFlag: true,
  VendorNumber: 20
}]
}
</code>```

How can i achieve this ?

答:
I think you are looking for a diff'ing algorithm. Wrote this quick recursive function that iterates over each enumerable property of your JavaScript object (not json object) testing equality. Note that the position of arguments does affect the output

function diff(obj1, obj2) {
    if (typeof obj1 === "object") {
        const obj = {};
        for (const prop in obj1) {
            if (diff(obj1[prop], obj2[prop])) {
                obj[prop] = obj1[prop]
            }
        }
        return obj
    } else {
        return obj1 !== obj2;
    }
}

console.log(diff(order2, order1))
```

Body:
I have two Javascript objects

var order1 = {
    sandwich: 'tuna',
    chips: true,
    drink: 'soda',
    order: 1,
    toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 20, PreferredFlag: false, SupportedFlag: true}],
    details: {
        name: 'Chris',
        phone: '555-555-5555',
        email: 'no@thankyou.com'
    },
    otherVal1: '1'
};

var order2 = {
    sandwich: 'turkey',
    chips: true,
    drink: 'soda',
    order: 2,
    toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, PreferredFlag: false, SupportedFlag: false}, {VendorNumber: 20, PreferredFlag: true, SupportedFlag: true}],
    details: {
        name: 'Jon',
        phone: '(555) 555-5555',
        email: 'yes@please.com'
    },
    otherVal1: '2'
};

What I need is to compare these two objects (order1 is existing and order2 is the edited data) and store the difference in a new variable named var order3. However if there is an array inside an object like the toppings array to be copied as whole with the changes.

In short the result should be

{
  details: {
    email: "yes@please.com",
    name: "Jon",
    phone: "(555) 555-5555"
  },
  order: 2,
  otherVal1: "2",
  sandwich: "turkey",
  toppings: [{
  PreferredFlag: false,
  SupportedFlag: true,
  VendorNumber: 18
}, {
  PreferredFlag: false,
  SupportedFlag: false,
  VendorNumber: 19
}, {
  PreferredFlag: true,
  SupportedFlag: true,
  VendorNumber: 20
}]
}

How can i achieve this ?


问:
Automate the Boring Stuff, Chapter 6 Table Printer
I am following http://automatetheboringstuff.com/chapter6/

At the very bottom of the page is an exercise about formatting tables.

Here is my code:

```<code>tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

def printTable(table):
    colWidths = [0] * len(table)

    for line in table:
        max = 0
        for word in line:
            if len(word) > max:
                max = len(word)
        colWidths[table.index(line)] = max

    for a in range(len(table)-2):
        for b in range(len(table[0])):
            print(table[a][b].rjust(colWidths[0])+table[a+1][b].rjust(colWidths[1])+table[a+2][b].rjust(colWidths[2]))

    """
    print(table[0][0].rjust(colWidths[0]), table[1][0].rjust(colWidths[1]), table[2][0].rjust(colWidths[2]))
    print(table[0][1].rjust(colWidths[0]), table[1][1].rjust(colWidths[1]), table[2][1].rjust(colWidths[2]))
    print(table[0][2].rjust(colWidths[0]), table[1][2].rjust(colWidths[1]), table[2][2].rjust(colWidths[2]))
    print(table[0][3].rjust(colWidths[0]), table[1][3].rjust(colWidths[1]), table[2][3].rjust(colWidths[2]))
    """
    print()

printTable(tableData)
</code>```

The commented out lines format everything how it should be.  The actual code does not.  For it to be formatted correctly, I would need to add 1 to .rjust() for each column (eg with 100 columns I would have to .rjust(colWidths[1]+99)).

Why does this happen when it seems to be working just fine when I just manually print?

答:
Here's my code, which is finally working after a week bugging me and chasing me in my dreams:</p>

```<code>tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bobolon', 'Carolina', 'Davidovv'],
             ['dogsee', 'puscats', 'moosara', 'gooseano']]

def printTable(table):
    colwidths=[0]*len(table)
    for i in range(len(table)):
        for j in range(len(table[i])):
            if len(table[i][j])>colwidths[i]:
                colwidths[i]=len(table[i][j])

    for line in range(len(table[0])): #PYTHON PRINTS LINE PER LINE. NOT COLUMN PER COLUMN.ABOUT TABLE[0]: IT IS ESTABLISHED THAT ALL ITEMS IN TABLEDATA WILL HVE THE SAME LENGTH, SO THAT IT DOESNT MATTER WETHER YOU PUT [0], [1] OR [2] BECAUSE THEY ALL HAVE LENGTH OF 4 ITEMS (IN CASE OF THE TABLEDATA LIST
        for column in range(len(table)): #THERE ARE AS MANY COLUMNS AS ITEMS(LISTS) IN TABLEDATA
            print(table[column][line].ljust(colwidths[column]*2),end=" ") #NOW, WE PRINT THE FIRST WORD OF THE FIRST COLUMN, FOLLOWED BUYT THE FIRST WORD OF THE SECOND COLUMN AND SO ON. .END= HELPS WITH NOT HAVING TO CONCATENATE THESE AND KEEPING ITEMS IN THE SAME LINE.
        print() #WITHOUT THIS PRINT (WHICH PRINTS A NEW LINE), ALL ITEMS WOULD BE IN THE SAME LINE, DUE TO THE PREVIOS .END=

printTable(tableData)
</code>```

Body:
I am following http://automatetheboringstuff.com/chapter6/

At the very bottom of the page is an exercise about formatting tables.

Here is my code:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

def printTable(table):
    colWidths = [0] * len(table)

    for line in table:
        max = 0
        for word in line:
            if len(word) > max:
                max = len(word)
        colWidths[table.index(line)] = max

    for a in range(len(table)-2):
        for b in range(len(table[0])):
            print(table[a][b].rjust(colWidths[0])+table[a+1][b].rjust(colWidths[1])+table[a+2][b].rjust(colWidths[2]))

    """
    print(table[0][0].rjust(colWidths[0]), table[1][0].rjust(colWidths[1]), table[2][0].rjust(colWidths[2]))
    print(table[0][1].rjust(colWidths[0]), table[1][1].rjust(colWidths[1]), table[2][1].rjust(colWidths[2]))
    print(table[0][2].rjust(colWidths[0]), table[1][2].rjust(colWidths[1]), table[2][2].rjust(colWidths[2]))
    print(table[0][3].rjust(colWidths[0]), table[1][3].rjust(colWidths[1]), table[2][3].rjust(colWidths[2]))
    """
    print()

printTable(tableData)

The commented out lines format everything how it should be.  The actual code does not.  For it to be formatted correctly, I would need to add 1 to .rjust() for each column (eg with 100 columns I would have to .rjust(colWidths[1]+99)).

Why does this happen when it seems to be working just fine when I just manually print?

Body:
Here's my code, which is finally working after a week bugging me and chasing me in my dreams:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bobolon', 'Carolina', 'Davidovv'],
             ['dogsee', 'puscats', 'moosara', 'gooseano']]

def printTable(table):
    colwidths=[0]*len(table)
    for i in range(len(table)):
        for j in range(len(table[i])):
            if len(table[i][j])>colwidths[i]:
                colwidths[i]=len(table[i][j])

    for line in range(len(table[0])): #PYTHON PRINTS LINE PER LINE. NOT COLUMN PER COLUMN.ABOUT TABLE[0]: IT IS ESTABLISHED THAT ALL ITEMS IN TABLEDATA WILL HVE THE SAME LENGTH, SO THAT IT DOESNT MATTER WETHER YOU PUT [0], [1] OR [2] BECAUSE THEY ALL HAVE LENGTH OF 4 ITEMS (IN CASE OF THE TABLEDATA LIST
        for column in range(len(table)): #THERE ARE AS MANY COLUMNS AS ITEMS(LISTS) IN TABLEDATA
            print(table[column][line].ljust(colwidths[column]*2),end=" ") #NOW, WE PRINT THE FIRST WORD OF THE FIRST COLUMN, FOLLOWED BUYT THE FIRST WORD OF THE SECOND COLUMN AND SO ON. .END= HELPS WITH NOT HAVING TO CONCATENATE THESE AND KEEPING ITEMS IN THE SAME LINE.
        print() #WITHOUT THIS PRINT (WHICH PRINTS A NEW LINE), ALL ITEMS WOULD BE IN THE SAME LINE, DUE TO THE PREVIOS .END=

printTable(tableData)


问:
Where to access persistance in DDD
I am looking into Domain Driven Design (yes, I am quite late for that party) and so far I have come to the realization that the Domain Model should be the center of the universe. The data persistance is merely a practical detail.

However, if this is true, then I have a hard time figuring out where the communication with the persititance part (e.g. a repository) should be.

For instance, if I want to be able to add a new grade to a student, should I call the repository from inside the student domain model, like this?

```<code>interface IGradeRepository
{
    void SaveGrade(int courseId, string grade);
    // ...other methods
}

class Student
{
    IGradeRepository _gradeRepository;
    List<Grade> _grades = new List<Grade>();

    public Student(IGradeRepository gradeRepository)
    {
        _gradeRepository = gradeRepository;
    }

    int StudentId { get; set; }

    void AddGrade(int courseId, string grade)
    {
        var grade = new Grade(this.StudentId, courseId, grade);
        _grades.Add(grade);

        // Do I put the call to the data persistance here?
        _gradeRepository.SaveGrade(grade);
    }
}
</code>```

As you can see, my best bet is to access the repository from inside the domain model. However, I am not sure if this is the way to go about it. It seems to be one of the things that is left out in many tutorials.

So to summarize: From where do I access the data layer, when doing Domain Driven Design?

Update

As some have commented, it is not clear from my example, how I would access the student class. I would probably do that from a view model or through some sort of use case service.

Example with view model:

```<code>class StudentGradesViewModel
{
    // (...) all sort of VM-stuff

    private Student _student;
    private Course _selectedCourse;

    public void AddGrade(string grade)
    {
        _student.AddGrade(_course.CourseId, grade);
    }
}
</code>```

答:
should I call the repository from inside the student domain model, like this?

That's not the usual pattern.

Instead, it is more common that the interaction with the repositories happens at the application layer, rather than within the domain layer.

The repositories give the application access to the aggregate root, and the application interacts with the aggregate root only.  So the simple pattern looks something like

```<code>using transaction():
    Root root = _repository.get(rootId)
    root.doSomeCoolDomainThing(...)
</code>```

The assumption here being that root has access to all of the persisted information required to maintaining its domain invariant while doing the cool thing (which normally means that the entire graph of information is available in memory).

In some cases, you'll see the save of the root into the repository be made more explicit:

```<code>using transaction():
    Root root = _repository.get(rootId)
    root.doSomeCoolDomainThing(...)
    _repository.save(root)
</code>```

What is the root when you get all the way to the bottom?

Root is a domain model entity; it's the one that is "in charge", so to speak, of all of the other entities in that particular aggregate.

Here, I'm just using it as a stand in.  In a real project, the spelling would reflect the language of your domain -- Student, GradeBook, ReportCard, etc.

Title: Where to access persistance in DDD

Body:
I am looking into Domain Driven Design (yes, I am quite late for that party) and so far I have come to the realization that the Domain Model should be the center of the universe. The data persistance is merely a practical detail.

However, if this is true, then I have a hard time figuring out where the communication with the persititance part (e.g. a repository) should be.

For instance, if I want to be able to add a new grade to a student, should I call the repository from inside the student domain model, like this?

interface IGradeRepository
{
    void SaveGrade(int courseId, string grade);
    // ...other methods
}

class Student
{
    IGradeRepository _gradeRepository;
    List<Grade> _grades = new List<Grade>();

    public Student(IGradeRepository gradeRepository)
    {
        _gradeRepository = gradeRepository;
    }

    int StudentId { get; set; }

    void AddGrade(int courseId, string grade)
    {
        var grade = new Grade(this.StudentId, courseId, grade);
        _grades.Add(grade);

        // Do I put the call to the data persistance here?
        _gradeRepository.SaveGrade(grade);
    }
}

As you can see, my best bet is to access the repository from inside the domain model. However, I am not sure if this is the way to go about it. It seems to be one of the things that is left out in many tutorials.

So to summarize: From where do I access the data layer, when doing Domain Driven Design?

Update

As some have commented, it is not clear from my example, how I would access the student class. I would probably do that from a view model or through some sort of use case service.

Example with view model:

class StudentGradesViewModel
{
    // (...) all sort of VM-stuff

    private Student _student;
    private Course _selectedCourse;

    public void AddGrade(string grade)
    {
        _student.AddGrade(_course.CourseId, grade);
    }
}

Body:
should I call the repository from inside the student domain model, like this?

That's not the usual pattern.

Instead, it is more common that the interaction with the repositories happens at the application layer, rather than within the domain layer.

The repositories give the application access to the aggregate root, and the application interacts with the aggregate root only.  So the simple pattern looks something like

using transaction():
    Root root = _repository.get(rootId)
    root.doSomeCoolDomainThing(...)

The assumption here being that root has access to all of the persisted information required to maintaining its domain invariant while doing the cool thing (which normally means that the entire graph of information is available in memory).

In some cases, you'll see the save of the root into the repository be made more explicit:

using transaction():
    Root root = _repository.get(rootId)
    root.doSomeCoolDomainThing(...)
    _repository.save(root)

What is the root when you get all the way to the bottom?

Root is a domain model entity; it's the one that is "in charge", so to speak, of all of the other entities in that particular aggregate.

Here, I'm just using it as a stand in.  In a real project, the spelling would reflect the language of your domain -- Student, GradeBook, ReportCard, etc.


问:
Can not set lxc.apparmor.profile
I can not disable apparmor for lxc container:

```<code>$ lxc launch images:centos/7 a1
Creating a1
Starting a1
$ lxc config set a1 lxc.apparmor.profile unconfined
Error: Invalid config: Unknown configuration key: lxc.apparmor.profile
$ lxc --version
3.0.3
</code>```

What's wrong and how to set property ?

答:
It's an LXC setting for an LXD container. So it should be set as:

```<code>lxc config set a1 raw.lxc "lxc.apparmor.profile=unconfined"
</code>```

or the previous property before version 3:

```<code>lxc config set a1 raw.lxc "lxc.aa_profile=unconfined"
</code>```

Title: Can not set lxc.apparmor.profile

Body:
I can not disable apparmor for lxc container:

$ lxc launch images:centos/7 a1
Creating a1
Starting a1
$ lxc config set a1 lxc.apparmor.profile unconfined
Error: Invalid config: Unknown configuration key: lxc.apparmor.profile
$ lxc --version
3.0.3

What's wrong and how to set property ?

Body:
It's an LXC setting for an LXD container. So it should be set as:

lxc config set a1 raw.lxc "lxc.apparmor.profile=unconfined"

or the previous property before version 3:

lxc config set a1 raw.lxc "lxc.aa_profile=unconfined"


问:
EmberJS show router model in application.hbs
I am working with Ember.js, and I am trying to make my pages display the title of the page just below the navbar. To make this work I have tried to use model hook, and show it in the application.hbs file.

So far I have tried variations of this:

routes/contact.js

```<code>import Route from '@ember/routing/route';

export default class ContactRoute extends Route {
  model() {
    return 'Title of page';
  }
}
</code>```

templates/application.hbs

```<code><div>
  <NavBar />

  <div class="pageTitle">
    <h2>
      <p>{{@model}}</p>
    </h2>
  </div>

  <div class="body">
    {{outlet}}
  </div>
</div>
</code>```

I've mostly tried to mess around with @model in application.hbs things like outlet.@model. But all of these attempts have resulted in empty titles or Template Compiler Errors.
Does anyone have a solution for this? Preferably one that does not involve jquery?

答:
If I understand correctly what you are trying to accomplish, it is a good use case for services.

You need a couple parts. A service to keep track of the page title, and then you need to inject that service in the application controller so the template has access to the service, and also to inject the page title service in the routes so you can update the page title in the respective hooks.

Page service

import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';

export default class extends Service {
  @tracked title = "Your App"
}
```

<ol start="2">
<li>Application controller and template</li>
</ol>

<pre class="lang-js prettyprint-override"><code>import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default class ApplicationController extends Controller {
  @service pageTitle;
}
</code>```

```<code><h1>Welcome to {{this.pageTitle.title}}</h1>
<br>
<br>
{{outlet}}
<LinkTo @route="my-route">my route</LinkTo>
<br>
<br>
</code>```

MyRoute route updating the page title value in a model hook

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class extends Route {
  @service pageTitle;

  model() {
    this.pageTitle.title = "My Route"
  }
}
```

I have put it all together in an interactive Ember Twiddle demo.

Hope this helps!

Body:
I am working with Ember.js, and I am trying to make my pages display the title of the page just below the navbar. To make this work I have tried to use model hook, and show it in the application.hbs file.

So far I have tried variations of this:

routes/contact.js

import Route from '@ember/routing/route';

export default class ContactRoute extends Route {
  model() {
    return 'Title of page';
  }
}

templates/application.hbs

  <NavBar />

{{@model}}

    {{outlet}}

I've mostly tried to mess around with @model in application.hbs things like outlet.@model. But all of these attempts have resulted in empty titles or Template Compiler Errors.
Does anyone have a solution for this? Preferably one that does not involve jquery?

Body:
If I understand correctly what you are trying to accomplish, it is a good use case for services.

You need a couple parts. A service to keep track of the page title, and then you need to inject that service in the application controller so the template has access to the service, and also to inject the page title service in the routes so you can update the page title in the respective hooks.

Page service

import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';

export default class extends Service {
  @tracked title = "Your App"
}

Application controller and template

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default class ApplicationController extends Controller {
  @service pageTitle;
}

<h1>Welcome to {{this.pageTitle.title}}</h1>
<br>
<br>
{{outlet}}
<LinkTo @route="my-route">my route</LinkTo>
<br>
<br>

MyRoute route updating the page title value in a model hook

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class extends Route {
  @service pageTitle;

  model() {
    this.pageTitle.title = "My Route"
  }
}

I have put it all together in an interactive Ember Twiddle demo.

Hope this helps!


问:
Named Arguments do not work in a string with conditional logic
I have a multiline string with an in-line if condition as follows:

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        Good bye. """
</code>```

However, when I insert a named parameter, it does not seem to properly treat it. With some testing I found out that removing the IF from the string would allow the named parameters to work

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}
</code>```

Is there a specific reason why this won't work?

答:
msg_key is not a variable, it just identifies the placeholder in the string.

This works:

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}
</code>```

Body:
I have a multiline string with an in-line if condition as follows:

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        Good bye. """

However, when I insert a named parameter, it does not seem to properly treat it. With some testing I found out that removing the IF from the string would allow the named parameters to work

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}

Is there a specific reason why this won't work?

Body:
msg_key is not a variable, it just identifies the placeholder in the string.

This works:

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}


问:
Return list of all dictionary keys
Is there a way to return a list of all dictionary keys in the provided input (at all levels)?

The keys should be ordered by level, for example:

```<code>{
    "A": 1,
    "B": [{
        "B1": 1,
        "B2": 1
    }, {
        "B3": 1,
        "B4": 1
    }],
    "C": {
        "C1": 1,
        "C2": 1
    }
}
</code>```

I have tried using dict.keys() and dict.items() but did not get the desired output.

The output should be like this ["A", "B", "C", "B1", "B2", "B3", "B4", "C1", "C2"].

Any help is appreciated.

答:
I would do a recursive function:

```<code>d = {
    "A": 1,
    "B": [{
        "B1": 1,
        "B2": 1
    }, {
        "B3": 1,
        "B4": 1
    }],
    "C": {
        "C1": 1,
        "C2": 1
    }
}

def flatten(d, lst=None):
    if not lst:
        lst = []
    if isinstance(d, list):
        for item in d:
            lst = flatten(item, lst)
    elif isinstance(d, dict):
        for k in d.keys():
            lst.append(k)
        for v in d.values():
            lst = flatten(v, lst)
    return lst

print(flatten(d)) # Output: ['A', 'B', 'C', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2']
</code>```

EDIT: Above code assumes you're using Python 3.7+ where dict are ordered by default. If you're running an older version, you can use collection.OrderedDict instead while initializing d to have the same behavior.

Title: Return list of all dictionary keys

Body:
Is there a way to return a list of all dictionary keys in the provided input (at all levels)?

The keys should be ordered by level, for example:

{
    "A": 1,
    "B": [{
        "B1": 1,
        "B2": 1
    }, {
        "B3": 1,
        "B4": 1
    }],
    "C": {
        "C1": 1,
        "C2": 1
    }
}

I have tried using dict.keys() and dict.items() but did not get the desired output.

The output should be like this ["A", "B", "C", "B1", "B2", "B3", "B4", "C1", "C2"].

Any help is appreciated.

Body:
I would do a recursive function:

d = {
    "A": 1,
    "B": [{
        "B1": 1,
        "B2": 1
    }, {
        "B3": 1,
        "B4": 1
    }],
    "C": {
        "C1": 1,
        "C2": 1
    }
}

def flatten(d, lst=None):
    if not lst:
        lst = []
    if isinstance(d, list):
        for item in d:
            lst = flatten(item, lst)
    elif isinstance(d, dict):
        for k in d.keys():
            lst.append(k)
        for v in d.values():
            lst = flatten(v, lst)
    return lst

print(flatten(d)) # Output: ['A', 'B', 'C', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2']

EDIT: Above code assumes you're using Python 3.7+ where dict are ordered by default. If you're running an older version, you can use collection.OrderedDict instead while initializing d to have the same behavior.


问:
Postgres not accepting connection in Docker
I am running the docker project on docker toolbox windows 7 sp1 and the project does not give any error but still due to postgres not working the whole project in not functional.
The code of Docker compose file is :

```<code>version: '3'
services:
  postgres:
    image: 'postgres:latest'
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: "db"
      POSTGRES_PASSWORD: postgres_password
      POSTGRES_HOST_AUTH_METHOD: "trust"
      DATABASE_URL: postgresql://postgres:p3wrd@postgres:5432/postgres
    deploy:
      restart_policy:
        condition: on-failure
        window: 15m
  redis:
    image: 'redis:latest'
  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - '3050:80'
  api:
    depends_on:
      - "postgres"
    build:
      dockerfile: Dockerfile.dev
      context: ./server
    volumes:
      - ./server/copy:/usr/src/app/data
    environment:
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - PGUSER=postgres
      - PGHOST=postgres
      - PGDATABASE=postgres
      - PGPASSWORD=postgres_password
      - PGPORT=5432
  client:
    depends_on:
      - "postgres"
    build:
      dockerfile: Dockerfile.dev
      context: ./client
    volumes:
      - ./client/copy:/usr/src/app/data
      - /usr/src/app/node_modules
  worker:
    build:
      dockerfile: Dockerfile.dev
      context: ./worker
    volumes:
      - ./worker/copy:/usr/src/app/data
      - /usr/src/app/node_modules
    depends_on:
      - "postgres"
</code>```

But when i run the project i get this :

```<code>redis_1     | 1:C 29 May 2020 05:07:37.909 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1     | 1:C 29 May 2020 05:07:37.910 # Redis version=6.0.3, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1     | 1:C 29 May 2020 05:07:37.911 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1     | 1:M 29 May 2020 05:07:37.922 * Running mode=standalone, port=6379.
redis_1     | 1:M 29 May 2020 05:07:37.928 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1     | 1:M 29 May 2020 05:07:37.929 # Server initialized
redis_1     | 1:M 29 May 2020 05:07:37.929 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1     | 1:M 29 May 2020 05:07:37.933 * Loading RDB produced by version 6.0.3
redis_1     | 1:M 29 May 2020 05:07:37.934 * RDB age 8 seconds
redis_1     | 1:M 29 May 2020 05:07:37.934 * RDB memory usage when created 0.81 Mb
redis_1     | 1:M 29 May 2020 05:07:37.934 * DB loaded from disk: 0.001 seconds
postgres_1  |
postgres_1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres_1  |
postgres_1  | 2020-05-29 05:07:38.927 UTC [1] LOG:  starting PostgreSQL 12.3 (Debian 12.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
postgres_1  | 2020-05-29 05:07:38.928 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres_1  | 2020-05-29 05:07:38.929 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres_1  | 2020-05-29 05:07:38.933 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1  | 2020-05-29 05:07:38.993 UTC [24] LOG:  database system was shut down at 2020-05-29 05:07:29 UTC
api_1       |
api_1       | > @ dev /usr/src/app
api_1       | > nodemon
api_1       |
api_1       | [nodemon] 1.18.3
api_1       | [nodemon] to restart at any time, enter `rs`
api_1       | [nodemon] watching: *.*
</code>```

With or without data volumes the same error comes and due to which the project is not running. Please Help

答:
Along with Allan Chua's answer, Please mention a startup dependency on Postgres service in your docker-compose file.

```<code>    depends_on:
      - postgres
</code>```

Add this to your api service.

Body:
I am running the docker project on docker toolbox windows 7 sp1 and the project does not give any error but still due to postgres not working the whole project in not functional.
The code of Docker compose file is :

version: '3'
services:
  postgres:
    image: 'postgres:latest'
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: "db"
      POSTGRES_PASSWORD: postgres_password
      POSTGRES_HOST_AUTH_METHOD: "trust"
      DATABASE_URL: postgresql://postgres:p3wrd@postgres:5432/postgres
    deploy:
      restart_policy:
        condition: on-failure
        window: 15m
  redis:
    image: 'redis:latest'
  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - '3050:80'
  api:
    depends_on:
      - "postgres"
    build:
      dockerfile: Dockerfile.dev
      context: ./server
    volumes:
      - ./server/copy:/usr/src/app/data
    environment:
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - PGUSER=postgres
      - PGHOST=postgres
      - PGDATABASE=postgres
      - PGPASSWORD=postgres_password
      - PGPORT=5432
  client:
    depends_on:
      - "postgres"
    build:
      dockerfile: Dockerfile.dev
      context: ./client
    volumes:
      - ./client/copy:/usr/src/app/data
      - /usr/src/app/node_modules
  worker:
    build:
      dockerfile: Dockerfile.dev
      context: ./worker
    volumes:
      - ./worker/copy:/usr/src/app/data
      - /usr/src/app/node_modules
    depends_on:
      - "postgres"

But when i run the project i get this :

redis_1     | 1:C 29 May 2020 05:07:37.909 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1     | 1:C 29 May 2020 05:07:37.910 # Redis version=6.0.3, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1     | 1:C 29 May 2020 05:07:37.911 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1     | 1:M 29 May 2020 05:07:37.922 * Running mode=standalone, port=6379.
redis_1     | 1:M 29 May 2020 05:07:37.928 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1     | 1:M 29 May 2020 05:07:37.929 # Server initialized
redis_1     | 1:M 29 May 2020 05:07:37.929 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1     | 1:M 29 May 2020 05:07:37.933 * Loading RDB produced by version 6.0.3
redis_1     | 1:M 29 May 2020 05:07:37.934 * RDB age 8 seconds
redis_1     | 1:M 29 May 2020 05:07:37.934 * RDB memory usage when created 0.81 Mb
redis_1     | 1:M 29 May 2020 05:07:37.934 * DB loaded from disk: 0.001 seconds
postgres_1  |
postgres_1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres_1  |
postgres_1  | 2020-05-29 05:07:38.927 UTC [1] LOG:  starting PostgreSQL 12.3 (Debian 12.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
postgres_1  | 2020-05-29 05:07:38.928 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres_1  | 2020-05-29 05:07:38.929 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres_1  | 2020-05-29 05:07:38.933 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1  | 2020-05-29 05:07:38.993 UTC [24] LOG:  database system was shut down at 2020-05-29 05:07:29 UTC
api_1       |
api_1       | > @ dev /usr/src/app
api_1       | > nodemon
api_1       |
api_1       | [nodemon] 1.18.3
api_1       | [nodemon] to restart at any time, enter `rs`
api_1       | [nodemon] watching: *.*

With or without data volumes the same error comes and due to which the project is not running. Please Help

Body:
Along with Allan Chua's answer, Please mention a startup dependency on Postgres service in your docker-compose file.

    depends_on:
      - postgres

Add this to your api service.


问:
Pass a python variable into an SQL query
I am working on Databricks and I am trying to pass a python variable into a SQL query:

```<code>series_name "LogTest"

query = """SELECT * FROM results_table
  WHERE name = $series_name
  """
spark.sql(query).toPandas()
</code>```

I tried with $ but it does not work.

How do I do this?

Regards

答:
In this case, your variable and queries are just strings. You can do:

```<code>query = f"""SELECT * FROM results_table
WHERE name = '{series_name}'
"""
</code>```

... in python 3. Remember that your query string needs the single quotes around the inserted variable. However, for certain variables, you may need to pass the variable directly to the spark module so it can interpret it. I use pyodbc a lot and would do this:

```<code>query = f"""SELECT * FROM results_table
WHERE name = ?"""
cursor.execute(query, series_name)
</code>```

Body:
I am working on Databricks and I am trying to pass a python variable into a SQL query:

series_name "LogTest"

query = """SELECT * FROM results_table
  WHERE name = $series_name
  """
spark.sql(query).toPandas()

I tried with $ but it does not work.

How do I do this?

Regards

Body:
In this case, your variable and queries are just strings. You can do:

query = f"""SELECT * FROM results_table
WHERE name = '{series_name}'
"""

... in python 3. Remember that your query string needs the single quotes around the inserted variable. However, for certain variables, you may need to pass the variable directly to the spark module so it can interpret it. I use pyodbc a lot and would do this:

query = f"""SELECT * FROM results_table
WHERE name = ?"""
cursor.execute(query, series_name)


问:
Merge a single list of dictionaries with the same key value
I can see many similar questions on here but not one that I can find that helps me get the desired output.

I have a single list of dictionaries that have the same ID but with different key value pairs, id like to join all those key values pairs into a single list entry, below is a sample of data and the desired output.

Thanks for your help

```<code>data = [
    {'id': '10', 'animal' : 'cat'},
    {'id': '11', 'animal' : 'dog'},
    {'id': '3', 'animal' : 'pigeon'},
    {'id': '10', 'color' : 'yellow'},
    {'id': '11', 'color' : 'brown'},
    {'id': '3', 'color' : 'grey'},
    {'id': '10', 'type' : 'furry'},
    {'id': '11', 'type' : 'fluffy'},
    {'id': '3', 'type' : 'dirty'},
]
</code>```

desired output

```<code>data = [
    {'id': '10', 'animal' : 'cat', 'color' : 'yellow', 'type' : 'furry'},
    {'id': '11', 'animal' : 'dog', 'color' : 'brown', 'type' : 'fluffy'},
    {'id': '3', 'animal' : 'pigeon', 'color' : 'grey', 'type' : 'dirty'},
]
</code>```

答:
You can do it using groupby and ChainMap

```<code>from itertools import groupby
from collections import ChainMap

id_getter = lambda x: x['id']
gp = groupby(sorted(data, key=id_getter), key=id_getter)
result = [dict(ChainMap(*a)) for _, a in gp]
</code>```

groupby works on sorted collection, hence sort data before call groupby

ChainMap is used to merge a list of dictionaries to a single dictionary

Body:
I can see many similar questions on here but not one that I can find that helps me get the desired output.

I have a single list of dictionaries that have the same ID but with different key value pairs, id like to join all those key values pairs into a single list entry, below is a sample of data and the desired output.

Thanks for your help

data = [
    {'id': '10', 'animal' : 'cat'},
    {'id': '11', 'animal' : 'dog'},
    {'id': '3', 'animal' : 'pigeon'},
    {'id': '10', 'color' : 'yellow'},
    {'id': '11', 'color' : 'brown'},
    {'id': '3', 'color' : 'grey'},
    {'id': '10', 'type' : 'furry'},
    {'id': '11', 'type' : 'fluffy'},
    {'id': '3', 'type' : 'dirty'},
]

desired output

data = [
    {'id': '10', 'animal' : 'cat', 'color' : 'yellow', 'type' : 'furry'},
    {'id': '11', 'animal' : 'dog', 'color' : 'brown', 'type' : 'fluffy'},
    {'id': '3', 'animal' : 'pigeon', 'color' : 'grey', 'type' : 'dirty'},
]

Body:
You can do it using groupby and ChainMap

from itertools import groupby
from collections import ChainMap

id_getter = lambda x: x['id']
gp = groupby(sorted(data, key=id_getter), key=id_getter)
result = [dict(ChainMap(*a)) for _, a in gp]

groupby works on sorted collection, hence sort data before call groupby

ChainMap is used to merge a list of dictionaries to a single dictionary


答:
The best time to join the party is right now so no worries. You should not access the data persistence directly from your domain model, instead this should be done in the infrastructure layer. If you are familiar with Onion Architecture, it explains this nicely. You can look it up here or here. The same principles described in the links can be applied to your case.

Accessing the persistence layer (usually named infrastructure) is via executing your use-cases which are usually placed in the application layer and implemented via commands (manipulating the state of entities) or queries (reading the state of entities in persistance)

Title: Where to access persistance in DDD


问:
const doesn't seem to pass value through functions
I define two DOM selectors as constants but I can't seem to call them through functions. Essentially I should be able to pass two constants as arguments of a function where one gets it's display style set to block and the other set to none.

My JS is:

```<code>const divOne = document.querySelector("#divOne");
const divTwo = document.querySelector("#divTwo");

function showHide(show, hide){
    show.style.display = "block";
    hide.style.display = "none";
}

function changeDisplay(arg) {
    //do some other bits
    showHide(divOne, divTwo);
}
</code>```

But this doesn't seem to change and I get an error

```<code>Uncaught TypeError: Cannot read property 'style' of null
        at showHide
</code>```

Am I not able to pass querySelectors through functions?

答: Make sure that the dom has both "#divOne" and "#divTwo". If they are not available then the const variable will hold undefined</p>

Body:
I define two DOM selectors as constants but I can't seem to call them through functions. Essentially I should be able to pass two constants as arguments of a function where one gets it's display style set to block and the other set to none.

My JS is:

const divOne = document.querySelector("#divOne");
const divTwo = document.querySelector("#divTwo");

function showHide(show, hide){
    show.style.display = "block";
    hide.style.display = "none";
}

function changeDisplay(arg) {
    //do some other bits
    showHide(divOne, divTwo);
}

But this doesn't seem to change and I get an error

Uncaught TypeError: Cannot read property 'style' of null
        at showHide

Am I not able to pass querySelectors through functions?


问:
How to debug C++/C programs on VsCode
I am using the gcc/g++ compiler using msys64 and mingw64 with VsCode. I've attached the bash.exe of mingw64 to my VsCode terminal. I can run my programs on the bash terminal using g++ file_name.cpp && ./a.exe.
But how do I debug my programs?

答:
Actually debugging in VScode is a bit tricky. Have you followed the methods here-

https://code.visualstudio.com/docs/cpp/cpp-debug

Title: How to debug C++/C programs on VsCode


问:
How to get a target date given a specific date after converting specific date from CET to IST and excluding weekends
I am trying to get a future date and time based on Specific date from the user input. I need to convert from CET to IST and then add some hours based on some conditions and it has to give us a future date excluding weekends and particular time for example if it time is greater than 5pm then it has  to give the next available day.

I have an MVC form where it accepts a date and then i have to convert this date to a future date in C# code.

Can anyone help me in this.

I can give a logic in pseudo code if needed.

Please help me in this. As i am not able to figure out  how.

答:
Thanks for your help. I used your code and further used my own logic and came up with the final solution which gives me the Target Date as expected.

Below is my code :-

DateTime d =  Convert.ToDateTime(model.RecievedDate);

```<code>                DateTime end_time = new DateTime(1901,01,01, 17, 0 ,0);

                TimeSpan timeFrom = TimeSpan.Parse(d.ToString("HH:mm"));
                TimeSpan timeTo = TimeSpan.Parse(end_time.ToString("HH:mm"));
                TimeSpan timediff = timeTo.Subtract(timeFrom);

                if (model.Complexity == "L")
                {
                    if (timediff.TotalHours >= 4)
                    {
                        d = d.AddHours(4);
                    }
                    else if (timediff.TotalHours < 4 && timediff.TotalHours > 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + (4 - timediff.TotalHours));
                    }
                    else if (timediff.TotalHours < 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + 4);
                    }
                }
                else if (model.Complexity == "M")
                {
                    if (timediff.TotalHours >= 9)
                    {
                        d = d.AddHours(9);
                    }
                    else if (timediff.TotalHours < 9 && timediff.TotalHours > 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + (9 - timediff.TotalHours));
                    }
                    else if (timediff.TotalHours < 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + 9);
                    }
                }
                else if (model.Complexity == "H")
                {
                    var day = d.ToString("ddd");
                    if (day == "Mon")
                    {
                        d = d.AddHours(120);
                    }
                    else if (day == "Tue" || day == "Wed" || day == "Thu")
                    {
                        d = d.AddHours(120 + 48);
                    }
                    else if (day == "Fri" && timediff.TotalHours > 0)
                    {
                        d = d.AddHours(120 + 48);
                    }
                    else if (day == "Fri" && timediff.TotalHours < 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + 48 + 120);
                    }
                }
                switch (d.DayOfWeek)
                {
                    case DayOfWeek.Saturday:
                        d = d.AddDays(2);// increment day to Monday
                        break;

                    case DayOfWeek.Sunday:
                        d = d.AddDays(1); // increment day to Monday
                        break;
                }
                d = d.AddHours(3.5);
                model.TargetDate = d; // show value of d
</code>```

Body:
Thanks for your help. I used your code and further used my own logic and came up with the final solution which gives me the Target Date as expected.

Below is my code :-

DateTime d =  Convert.ToDateTime(model.RecievedDate);

                DateTime end_time = new DateTime(1901,01,01, 17, 0 ,0);

                TimeSpan timeFrom = TimeSpan.Parse(d.ToString("HH:mm"));
                TimeSpan timeTo = TimeSpan.Parse(end_time.ToString("HH:mm"));
                TimeSpan timediff = timeTo.Subtract(timeFrom);

                if (model.Complexity == "L")
                {
                    if (timediff.TotalHours >= 4)
                    {
                        d = d.AddHours(4);
                    }
                    else if (timediff.TotalHours < 4 && timediff.TotalHours > 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + (4 - timediff.TotalHours));
                    }
                    else if (timediff.TotalHours < 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + 4);
                    }
                }
                else if (model.Complexity == "M")
                {
                    if (timediff.TotalHours >= 9)
                    {
                        d = d.AddHours(9);
                    }
                    else if (timediff.TotalHours < 9 && timediff.TotalHours > 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + (9 - timediff.TotalHours));
                    }
                    else if (timediff.TotalHours < 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + 9);
                    }
                }
                else if (model.Complexity == "H")
                {
                    var day = d.ToString("ddd");
                    if (day == "Mon")
                    {
                        d = d.AddHours(120);
                    }
                    else if (day == "Tue" || day == "Wed" || day == "Thu")
                    {
                        d = d.AddHours(120 + 48);
                    }
                    else if (day == "Fri" && timediff.TotalHours > 0)
                    {
                        d = d.AddHours(120 + 48);
                    }
                    else if (day == "Fri" && timediff.TotalHours < 0)
                    {
                        d = d.AddHours(timediff.TotalHours + 15 + 48 + 120);
                    }
                }
                switch (d.DayOfWeek)
                {
                    case DayOfWeek.Saturday:
                        d = d.AddDays(2);// increment day to Monday
                        break;

                    case DayOfWeek.Sunday:
                        d = d.AddDays(1); // increment day to Monday
                        break;
                }
                d = d.AddHours(3.5);
                model.TargetDate = d; // show value of d


问:
How to fix rounded-img issue on mobile
I have an rounded image in my website, and on computer it is fine, but on mobile or on resized browser it's like this:

enter image description here

Code:

```<code> <img src="'.$cover.'" class="rounded-circle img-profile" style="height:75px; width:75px; border: none;" alt="avatar">
</code>```

How can I fix this issue?

答:
In the image class, you can put " class="img img-responsive" " as in the following example:

<!DOCTYPE html>

<link rel="stylesheet"

href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />

<meta charset="utf-8" />

```

<p>And if you want to use this code make sure you insert the bootstrap code:</p>

<pre class="lang-html prettyprint-override"><code> <!-- Latest compiled and minified CSS -->

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />

    <!-- jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"type="text/
javascript"></script>

    <!-- Latest compiled JavaScript -->

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" type="text/javascript"></script>
</code>```

Title: How to fix rounded-img issue on mobile

Body:
I have an rounded image in my website, and on computer it is fine, but on mobile or on resized browser it's like this:

enter image description here

Code:

How can I fix this issue?

Body:
In the image class, you can put " class="img img-responsive" " as in the following example:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <!-- Latest compiled and minified CSS -->

<link rel="stylesheet"

href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />

    <!-- jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"

type="text/javascript"></script>

    <!-- Latest compiled JavaScript -->

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"

type="text/javascript"></script>

<meta charset="utf-8" />

</head>

<body>

 <img src="$cover" class="rounded-circle img-profile img-responsive"

style="height:75px; width:75px; border: none;" alt="avatar">

</body>

</html>

And if you want to use this code make sure you insert the bootstrap code:

 <!-- Latest compiled and minified CSS -->

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />

    <!-- jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"type="text/
javascript"></script>

    <!-- Latest compiled JavaScript -->

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" type="text/javascript"></script>


问:
How to test .net core 3.0 web api using azure ad implicit grant flow
In Angular/.net core 3.0 app I am using Azure AD implicit grant flow. The Web API uses authorisation and allows access based on roles (e.g. SuperAdmin, Admin and User roles etc). I need to write automated integration test for the Webapi (I can use a seperate client app too for testing). Any ideas which will be the appropriate grant flow for testing. I have read about ROPC flow (Resource ownder password credentails) flow and its not recommended to be used. I can't use client credentails flow as this wont work with Authorisation. I will appreicate any links or examples.</p>

答: Just if it helps someone, I did not find an alternate to get an access token to call the webapi which uses role based authorization (i.e. allow access to only users in certain AD groups) for my integration tests. So created few test users in the relevant AD groups and used resource owner password credential flow to get the access tokens and called the web api</p>


问:
Distinct Unique Keys with JSON Server
I am using json-server from typicode, it works but is it possible to get requested key values as an array?

For example I have

```<code>{
    "users": [
        {
            "name": "ABC",
            "job": "Engineer",
            "age" : 28
        },
        {
            "name": "XYZ",
            "job": "Product Manager",
            "age" : 32
        },
        {
            "name": "ASD",
            "job": "HR Manager",
            "age" : 325
        }
    ]
}
</code>```

I want to get a array of jobs

```<code>["Engineer", "Product Manager", "Human Resource"]
</code>```

答:
let obj = {
    "users": [
        {
            "name": "ABC",
            "job": "Engineer",
            "age" : 28
        },
        {
            "name": "XYZ",
            "job": "Product Manager",
            "age" : 32
        },
        {
            "name": "ASD",
            "job": "HR Manager",
            "age" : 325
        }
    ]
}

console.log([...new Set(obj.users.map(user => user.job))]);```

Title: Distinct Unique Keys with JSON Server

Body:
I am using json-server from typicode, it works but is it possible to get requested key values as an array?

For example I have

{
    "users": [
        {
            "name": "ABC",
            "job": "Engineer",
            "age" : 28
        },
        {
            "name": "XYZ",
            "job": "Product Manager",
            "age" : 32
        },
        {
            "name": "ASD",
            "job": "HR Manager",
            "age" : 325
        }
    ]
}

I want to get a array of jobs

["Engineer", "Product Manager", "Human Resource"]


问:
How to replace values of each cell on a dataframe without looping it
How can I apply for each cell of my dataframe this conditional (check if I have a string and if its found, replace with a 0) in an easier way?

```<code>for col in data.columns:
    for day in data.index:
        if (type(data_input_df.loc[day, col]) == 'str'):
            data_input_df[col][day] = 0
</code>```

The data dataframe is:

```<code>                           Log      1233.de ...      asdad.w.1    fff.op
Tagname                                     ...
01/06/2008 00:00            ON      343.04  ...        73.75      79.03
02/06/2008 00:00            ON      332.31  ...        73.71      79.21
03/06/2008 00:00            ON      339.25  ...        75.77      80.11
04/06/2008 00:00            ON      353.25  ...        76.47      79.75
05/06/2008 00:00            ON      353.44  ...        77.35      82.48
</code>```

Which is uploaded as:

```<code>dat =  pd.read_csv('data.csv', header = 0, index_col = "Tagname")
data = pd.DataFrame(data)
</code>```

答:
You could coerce the dataframe to numeric datatype then fill NaN with zeroes.</p>

```<code>df = pd.to_numeric(df, errors='coerce').fillna(0)
</code>```

Body:
How can I apply for each cell of my dataframe this conditional (check if I have a string and if its found, replace with a 0) in an easier way?

for col in data.columns:
    for day in data.index:
        if (type(data_input_df.loc[day, col]) == 'str'):
            data_input_df[col][day] = 0

The data dataframe is:

                           Log      1233.de ...      asdad.w.1    fff.op
Tagname                                     ...
01/06/2008 00:00            ON      343.04  ...        73.75      79.03
02/06/2008 00:00            ON      332.31  ...        73.71      79.21
03/06/2008 00:00            ON      339.25  ...        75.77      80.11
04/06/2008 00:00            ON      353.25  ...        76.47      79.75
05/06/2008 00:00            ON      353.44  ...        77.35      82.48

Which is uploaded as:

dat =  pd.read_csv('data.csv', header = 0, index_col = "Tagname")
data = pd.DataFrame(data)

Body:
You could coerce the dataframe to numeric datatype then fill NaN with zeroes.

df = pd.to_numeric(df, errors='coerce').fillna(0)


问:
SQL query counts returns the same number
The following query:

Select t1.name
       , t1.email
       , t1.activated
       , count(t2.id) as 'reporter'
       , count(t3.id) as 'comments'
       , count(t4.id) as 'reported'
from users t1
     inner join tickets as t2 on t1.id = t2.reporter_id
     inner join comments as t3 on t1.id = t3.user_id
     inner join tickets as t4 on t1.id = t4.reported_id
group by name
```

The counts return all 3 the same number

答:
count() returns the number of rows with non-NULL values.  The ids are presumably NOT NULL so they return the same values.

The quick-and-dirty solution to your problem is to use COUNT(DISTINCT:

```<code>Select t1.name, t1.email, t1.activated,
       count(distinct t2.id) as reporter,
       count(distinct t3.id) as comments,
       count(distinct t4.id) as reported
. . .
</code>```

Do not use single quotes for column aliases!  Only use single quotes for string and date constants.

Note that your query will never return 0 values for any of the counts.  Also, this is more expensive than necessary.  I am not providing a more efficient solution here, because the above answers your question.  If you have other issues with the query, then ask a new question with appropriate sample data, desired results, and an explanation of what you want to do.

Body:
The following query:

Select t1.name
       , t1.email
       , t1.activated
       , count(t2.id) as 'reporter'
       , count(t3.id) as 'comments'
       , count(t4.id) as 'reported'
from users t1
     inner join tickets as t2 on t1.id = t2.reporter_id
     inner join comments as t3 on t1.id = t3.user_id
     inner join tickets as t4 on t1.id = t4.reported_id
group by name

The counts return all 3 the same number

Body:
count() returns the number of rows with non-NULL values.  The ids are presumably NOT NULL so they return the same values.

The quick-and-dirty solution to your problem is to use COUNT(DISTINCT:

Select t1.name, t1.email, t1.activated,
       count(distinct t2.id) as reporter,
       count(distinct t3.id) as comments,
       count(distinct t4.id) as reported
. . .

Do not use single quotes for column aliases!  Only use single quotes for string and date constants.

Note that your query will never return 0 values for any of the counts.  Also, this is more expensive than necessary.  I am not providing a more efficient solution here, because the above answers your question.  If you have other issues with the query, then ask a new question with appropriate sample data, desired results, and an explanation of what you want to do.


答:
I think You can use map.</p>

```<code>const data = {
    "users": [
        {
            "name": "ABC",
            "job": "Engineer",
            "age" : 28
        },
        {
            "name": "XYZ",
            "job": "Product Manager",
            "age" : 32
        },
        {
            "name": "ASD",
            "job": "HR Manager",
            "age" : 325
        }
    ]
}

display.log(data.users.map((it) => it.job))```
</code>```

Title: Distinct Unique Keys with JSON Server

Body:
I think You can use map.

const data = {
    "users": [
        {
            "name": "ABC",
            "job": "Engineer",
            "age" : 28
        },
        {
            "name": "XYZ",
            "job": "Product Manager",
            "age" : 32
        },
        {
            "name": "ASD",
            "job": "HR Manager",
            "age" : 325
        }
    ]
}

display.log(data.users.map((it) => it.job))```


问:
Provide HTML output for paragraph
I am having an issue when I pull data into the WordPress website.

I use the code snippet below to print the category description.

```<code><p> {{ currentTax.activeTerm.description}} </p>
</code>```

It works fine, it prints description but it is not HTML output. Links, bold or other tags I enter in category don't show in the output.

For example it prints like this

This is description of the car category. In order to check cars check this link  Cars

It doesn't display a link, it shows text. Is there any way to quickly solve this issue?

答:
You can do this with innerHTML property binding:

```<code><p [innerHTML]="currentTax.activeTerm.description"></p>
</code>```

See: Sanitization and security contexts

Title: Provide HTML output for paragraph

Body:
I am having an issue when I pull data into the WordPress website.

I use the code snippet below to print the category description.

 {{ currentTax.activeTerm.description}}

It works fine, it prints description but it is not HTML output. Links, bold or other tags I enter in category don't show in the output.

For example it prints like this

This is description of the car category. In order to check cars check this link  Cars

It doesn't display a link, it shows text. Is there any way to quickly solve this issue?

Body:
You can do this with innerHTML property binding:

<p [innerHTML]="currentTax.activeTerm.description"></p>

See: Sanitization and security contexts


问:
Attempting to compile FFmpeg 4.2.3 statically for Windows 10 (x86_64), but binaries asks for missing DLLs
I am using Msys MinGW (x86_64) and pulled a snapshot of the latest major release of FFmpeg off of their website. Here is my ./configure options. I plan to use the binaries on both the computer that I compiled it on, and other Windows computers that I own.

```<code>./configure --enable-libaom --enable-avisynth --enable-chromaprint --enable-libdav1d --enable-libdavs2 --enable-libgme --enable-libmfx --enable-libkvazaar --enable-libmp3lame --enable-libilbc --enable-libvpx --enable-libmodplug --enable-version3 --enable-nonfree --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libvo-amrwbenc --enable-libfdk-aac --enable-libopenh264 --enable-libopenjpeg --enable-nvenc --enable-nvdec --enable-cuda --enable-cuvid --enable-libtwolame --enable-vapoursynth --enable-libwavpack --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxavs2 --enable-gpl --enable-static --disable-shared
</code>```

Output of configure script (pastebin)

Output of uname -a (in Msys)

```<code>MINGW64_NT-10.0-18362 <scrubbed> 3.1.4-340.x86_64 2020-05-22 08:28 UTC x86_64 Msys
</code>```

The issue that I'm facing is that despite passing the options --enable-static and --disable-shared, the executables generated still require libchromaprint.dll, libfdk-aac-2.dll, and libgme.dll to run. What I expected was that FFmpeg would execute independently of any DLL files since I passed those options to ./configure.

答:
Even if you specify --enable-static the shared libraries may be used in cases where no static library was found. You should get warnings from libtool regarding this during the build.

So if it looks for libchromaprint.a and can't find it it will link with libchromaprint.dll.a causing the dependancy on the DLL.

Check the dependancies to see if their static libraries are available (in your case libchromaprint.a, libfdk-aac-2.a, libgme.a).

OwnerDisplayName: Expectator

Body:
I am using Msys MinGW (x86_64) and pulled a snapshot of the latest major release of FFmpeg off of their website. Here is my ./configure options. I plan to use the binaries on both the computer that I compiled it on, and other Windows computers that I own.

./configure --enable-libaom --enable-avisynth --enable-chromaprint --enable-libdav1d --enable-libdavs2 --enable-libgme --enable-libmfx --enable-libkvazaar --enable-libmp3lame --enable-libilbc --enable-libvpx --enable-libmodplug --enable-version3 --enable-nonfree --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libvo-amrwbenc --enable-libfdk-aac --enable-libopenh264 --enable-libopenjpeg --enable-nvenc --enable-nvdec --enable-cuda --enable-cuvid --enable-libtwolame --enable-vapoursynth --enable-libwavpack --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxavs2 --enable-gpl --enable-static --disable-shared

Output of configure script (pastebin)

Output of uname -a (in Msys)

MINGW64_NT-10.0-18362 <scrubbed> 3.1.4-340.x86_64 2020-05-22 08:28 UTC x86_64 Msys

The issue that I'm facing is that despite passing the options --enable-static and --disable-shared, the executables generated still require libchromaprint.dll, libfdk-aac-2.dll, and libgme.dll to run. What I expected was that FFmpeg would execute independently of any DLL files since I passed those options to ./configure.


问:
How to customize colorbar in Seaborn Heatmap with text labels
I'd like to create a colorbar legend for a heatmap, that instead of numbers has text.

For example, suppose I am going to show the people distribution who traverse between some cities. But in colorbar, I want to have three texts "Low population", "medium" and "High" instead of number which shows the range of the population.

It is not professional at all but my code to address this issue is in the blow:

```<code>ax = sns.heatmap(Matrix_of_Population, cmap='viridis', cbar_kws={'label': 'Low      Medium    high'})
</code>```

But the number of population is also besides these texts.

答:
You can specify labels for specific ticks in the colorbar:

```<code>import seaborn as sns
import numpy as np

a = np.random.randn(20,20)
ax = sns.heatmap(a, cmap='viridis')
c_bar = ax.collections[0].colorbar
c_bar.set_ticks([-2, 0, 2])
c_bar.set_ticklabels(['Low', 'Medium', 'High'])
</code>```

Body:
I'd like to create a colorbar legend for a heatmap, that instead of numbers has text.

For example, suppose I am going to show the people distribution who traverse between some cities. But in colorbar, I want to have three texts "Low population", "medium" and "High" instead of number which shows the range of the population.

It is not professional at all but my code to address this issue is in the blow:

ax = sns.heatmap(Matrix_of_Population, cmap='viridis', cbar_kws={'label': 'Low      Medium    high'})

But the number of population is also besides these texts.

Body:
You can specify labels for specific ticks in the colorbar:

import seaborn as sns
import numpy as np

a = np.random.randn(20,20)
ax = sns.heatmap(a, cmap='viridis')
c_bar = ax.collections[0].colorbar
c_bar.set_ticks([-2, 0, 2])
c_bar.set_ticklabels(['Low', 'Medium', 'High'])


问:
Git-garbage retention time
I was trying to checkout a previous reflog hash after an accidental hard reset. Exactly for how long can GIT retain the reflog/ commits which were reset or garbage data?</p>

答:
By default it's 90 days, and you can configure it with gc.reflogExpire.

Also, it doesn't get altered by git reset commands. reflog is your safety net.

Title: Git-garbage retention time


答:
we can also try the following.</p>

```<code>series_name = "LogTest"
query = "SELECT * FROM results_table WHERE name = {}".format(series_name)
spark.sql(query).toPandas() #
</code>```

Title: Pass a python variable into an SQL query

Body:
I am working on Databricks and I am trying to pass a python variable into a SQL query:

series_name "LogTest"

query = """SELECT * FROM results_table
  WHERE name = $series_name
  """
spark.sql(query).toPandas()

I tried with $ but it does not work.

How do I do this?

Regards

Body:
we can also try the following.

series_name = "LogTest"
query = "SELECT * FROM results_table WHERE name = {}".format(series_name)
spark.sql(query).toPandas() #


问:
Removing attributes from elements
I will start off with the code...

```<code>private static void File()
{
    wixFile = XDocument.Load(filePath);

    var fileElements = from file in wixFile.Descendants(GetWixNamespace() + "File")
                        select file;
    foreach (var file in fileElements)
    {
        if(file.Attributes("Name").Any())
            file.Attribute("Name").Remove();
    }
    wixFile.Save(filePath);
}
</code>```

I actually check for quite a few attributes in the list and remove or correct them, but just to keep it short I took everything out except for one example of what I was doing.  The problem that I am having is that this code is not removing the Name attribute from anything like I would expect it.  When I put a break point in and watch it the "file" is getting updated as expected, but the changes are not going over to the wixFile when I save (or during the editing either).  I am not entirely sure what I am missing here so any help would be greatly appreciated.

EDIT:

Here is a snippet of the code that is being changed:

```<code><?define ApplicationPath=\\dwdata\develope\DocuWare\DW5\Mast_dsk\?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Directory Id="DATADIR" Name="data">
                            <Directory Id="mysql" Name="mysql">
                                <Component Id="procs_priv.MYI" Guid="{1148181A-4818-434F-B2D1-E4B417586168}">
                                    <File Id="procs_priv.MYI" Name="procs_priv.MYI" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\procs_priv.MYI" />
                                </Component>
                                <Component Id="procs_priv.MYD" Guid="{A6688F48-71AF-4242-B6D0-CA69452A01B4}">
                                    <File Id="procs_priv.MYD" Name="procs_priv.MYD" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\procs_priv.MYD" />
                                </Component>
                                <Component Id="procs_priv.frm" Guid="{3025C26C-8DFF-43D4-A62A-79E78D2D807D}">
                                    <File Id="procs_priv.frm" Name="procs_priv.frm" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\procs_priv.frm" />
                                </Component>
                                <Component Id="proc.MYI" Guid="{FD4AA2E1-E059-4549-AE61-222878185A0A}">
                                    <File Id="proc.MYI" Name="proc.MYI" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\proc.MYI" />
                                </Component>
                                <Component Id="proc.MYD" Guid="{12EE6EE8-AC44-4601-84C5-14B27CF9A3E6}">
                                    <File Id="proc.MYD" Name="proc.MYD" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\proc.MYD" />
                                </Component>
                                <Component Id="proc.frm" Guid="{8A6F2928-5484-4B55-B75F-8475C684A091}">
                                    <File Id="proc.frm" Name="proc.frm" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\proc.frm" />
                                </Component>
</Directory>
</Directory>
</Wix>
</code>```

I am getting the exact same thing back as well.  What I am trying to do is remove the "Name" attribute, but it just isn't working for whatever reason. The GetWiXNamespace() method returns the same namespace that is listed in the wix element as an XNamespace.

答:
I'm going to read between the lines here and guess you are converting from an old version of WiX ( say 2.0 ) that required a File@Name attribute to a version ( say 3.0-3.6 ) that can infer this attribute and doesn't require it.

Here's some code that I just whipped up that I know works assuming the source xml is WiX 3.x.  I'm not sure what is wrong with your code but perhaps the method that returns the namespace hasn't accounted for the url change.

```<code>    XNamespace ns = "http://schemas.microsoft.com/wix/2006/wi";
    var doc = XDocument.Load(@"C:\before.wxs");
    var elements = from element in doc.Descendants( ns + "File")
                   where element.Attribute("Name") != null
                   select element;

    foreach (var element in elements)
    {
        element.Attribute("Name").Remove();
    }
    doc.Save(@"C:\after.wxs");

<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <?define SourceDir="."?>
  <Module Id="YourModuleHere" Language="1033" Version="1.0.0.0">
    <Package Id="31c7722e-c2a0-4328-92a2-eacd443c10a9" Manufacturer="YourCompanyHere" InstallerVersion="200" />
    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="MergeRedirectFolder">
        <Component Id="owc7CEF9B0C53324FC23404D2AAAB5D12B8" Guid="6898e947-fa51-8efb-bda4-2e256dea8ed1">
          <File Id="owf7CEF9B0C53324FC23404D2AAAB5D12B8" Name="bfsvc.exe" Source="$(var.SourceDir)\Windows\bfsvc.exe" KeyPath="yes" />
        </Component>
        <Component Id="owc8C6EA26177072C0006EEF8265FEF72A4" Guid="91737806-0b20-24ad-9653-cca05b5778fb">
          <File Id="owf8C6EA26177072C0006EEF8265FEF72A4" Name="explorer.exe" Source="$(var.SourceDir)\Windows\explorer.exe" KeyPath="yes" />
        </Component>
      </Directory>
    </Directory>
  </Module>
</Wix>
</code>```

Title: Removing attributes from elements

Body:
I will start off with the code...

private static void File()
{
    wixFile = XDocument.Load(filePath);

    var fileElements = from file in wixFile.Descendants(GetWixNamespace() + "File")
                        select file;
    foreach (var file in fileElements)
    {
        if(file.Attributes("Name").Any())
            file.Attribute("Name").Remove();
    }
    wixFile.Save(filePath);
}

I actually check for quite a few attributes in the list and remove or correct them, but just to keep it short I took everything out except for one example of what I was doing.  The problem that I am having is that this code is not removing the Name attribute from anything like I would expect it.  When I put a break point in and watch it the "file" is getting updated as expected, but the changes are not going over to the wixFile when I save (or during the editing either).  I am not entirely sure what I am missing here so any help would be greatly appreciated.

EDIT:

Here is a snippet of the code that is being changed:

<?define ApplicationPath=\\dwdata\develope\DocuWare\DW5\Mast_dsk\?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Directory Id="DATADIR" Name="data">
                            <Directory Id="mysql" Name="mysql">
                                <Component Id="procs_priv.MYI" Guid="{1148181A-4818-434F-B2D1-E4B417586168}">
                                    <File Id="procs_priv.MYI" Name="procs_priv.MYI" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\procs_priv.MYI" />
                                </Component>
                                <Component Id="procs_priv.MYD" Guid="{A6688F48-71AF-4242-B6D0-CA69452A01B4}">
                                    <File Id="procs_priv.MYD" Name="procs_priv.MYD" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\procs_priv.MYD" />
                                </Component>
                                <Component Id="procs_priv.frm" Guid="{3025C26C-8DFF-43D4-A62A-79E78D2D807D}">
                                    <File Id="procs_priv.frm" Name="procs_priv.frm" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\procs_priv.frm" />
                                </Component>
                                <Component Id="proc.MYI" Guid="{FD4AA2E1-E059-4549-AE61-222878185A0A}">
                                    <File Id="proc.MYI" Name="proc.MYI" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\proc.MYI" />
                                </Component>
                                <Component Id="proc.MYD" Guid="{12EE6EE8-AC44-4601-84C5-14B27CF9A3E6}">
                                    <File Id="proc.MYD" Name="proc.MYD" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\proc.MYD" />
                                </Component>
                                <Component Id="proc.frm" Guid="{8A6F2928-5484-4B55-B75F-8475C684A091}">
                                    <File Id="proc.frm" Name="proc.frm" KeyPath="yes" Source="$(var.ApplicationPath)Common\MySql\Server\data\mysql\proc.frm" />
                                </Component>
</Directory>
</Directory>
</Wix>

I am getting the exact same thing back as well.  What I am trying to do is remove the "Name" attribute, but it just isn't working for whatever reason. The GetWiXNamespace() method returns the same namespace that is listed in the wix element as an XNamespace.

Body:
I'm going to read between the lines here and guess you are converting from an old version of WiX ( say 2.0 ) that required a File@Name attribute to a version ( say 3.0-3.6 ) that can infer this attribute and doesn't require it.

Here's some code that I just whipped up that I know works assuming the source xml is WiX 3.x.  I'm not sure what is wrong with your code but perhaps the method that returns the namespace hasn't accounted for the url change.

    XNamespace ns = "http://schemas.microsoft.com/wix/2006/wi";
    var doc = XDocument.Load(@"C:\before.wxs");
    var elements = from element in doc.Descendants( ns + "File")
                   where element.Attribute("Name") != null
                   select element;

    foreach (var element in elements)
    {
        element.Attribute("Name").Remove();
    }
    doc.Save(@"C:\after.wxs");

<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <?define SourceDir="."?>
  <Module Id="YourModuleHere" Language="1033" Version="1.0.0.0">
    <Package Id="31c7722e-c2a0-4328-92a2-eacd443c10a9" Manufacturer="YourCompanyHere" InstallerVersion="200" />
    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="MergeRedirectFolder">
        <Component Id="owc7CEF9B0C53324FC23404D2AAAB5D12B8" Guid="6898e947-fa51-8efb-bda4-2e256dea8ed1">
          <File Id="owf7CEF9B0C53324FC23404D2AAAB5D12B8" Name="bfsvc.exe" Source="$(var.SourceDir)\Windows\bfsvc.exe" KeyPath="yes" />
        </Component>
        <Component Id="owc8C6EA26177072C0006EEF8265FEF72A4" Guid="91737806-0b20-24ad-9653-cca05b5778fb">
          <File Id="owf8C6EA26177072C0006EEF8265FEF72A4" Name="explorer.exe" Source="$(var.SourceDir)\Windows\explorer.exe" KeyPath="yes" />
        </Component>
      </Directory>
    </Directory>
  </Module>
</Wix>


答:
IIUC, what you want to do is groupby using pd.Grouper to give the freq you want and Name, then use agg with all the columns and functions you want to get like:

```<code>data = (df.groupby([pd.Grouper(key='Date', freq='5T'), #replace 5T by D to get daily agggregation
                    'Name'])
          .agg(count=('Name','count'),
               sum_shares=('Shares','sum'),
               sum_comments=('Comments','sum'),
               sum_engagement=('Engagement','sum'), )
          .reset_index()
       )

print (data.head())
                 Date                      Name  count  sum_shares  \
0 2020-05-13 09:00:00   Guybrush's Page              1           4
1 2020-05-13 09:00:00   Herman Toothrot's Page       1          61
2 2020-05-13 09:10:00   Elaine's Page                2           1
3 2020-05-13 09:20:00   Elaine's Page                2           4
4 2020-05-13 09:20:00   Herman Toothrot's Page       1          26

   sum_comments  sum_engagement
0            27             512
1            39             710
2            17             540
3            19             290
4           101             635
</code>```

then you can use seaborn like:

```<code>import seaborn as sns
sns.lineplot(x='Date', y='count', data=data,
             hue='Name',
             size='sum_shares') #here for the size use what summed column you want
</code>```

I don't post image as there is nothing to see really with the 20 lines of data given.

Title: How do you make a Seaborn line plot from a Pandas MultiIndex?

Body:
Noobish Seaborn / Pandas question: I have a spreadsheet of Facebook Page posts data which looks like this (first 20 rows):

| Name                   | ID              | Type      | Date             | Shares | Comments | Reactions | Engagement |
|------------------------|-----------------|-----------|------------------|--------|----------|-----------|------------|
| Herman Toothrot's Page | 201295459914847 | link      | 13/05/2020 09:00 | 61     | 39       | 610       | 710        |
| Guybrush's Page        | 167959249906191 | link      | 13/05/2020 09:04 | 4      | 27       | 481       | 512        |
| Elaine's Page          | 187202271820522 | album     | 13/05/2020 09:12 | 0      | 3        | 96        | 99         |
| Elaine's Page          | 187202271820522 | album     | 13/05/2020 09:14 | 1      | 14       | 426       | 441        |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:20 | 3      | 8        | 158       | 169        |
| Herman Toothrot's Page | 201295459914847 | link      | 13/05/2020 09:20 | 26     | 101      | 508       | 635        |
| Elaine's Page          | 187202271820522 | undefined | 13/05/2020 09:23 | 1      | 11       | 109       | 121        |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:28 | 2      | 257      | 987       | 1246       |
| Herman Toothrot's Page | 201295459914847 | photo     | 13/05/2020 09:30 | 1      | 0        | 178       | 179        |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:31 | 3      | 6        | 162       | 171        |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:38 | 44     | 143      | 4294      | 4481       |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:39 | 7      | 79       | 631       | 795        |
| Herman Toothrot's Page | 201295459914847 | link      | 13/05/2020 09:40 | 3      | 0        | 104       | 107        |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:45 | 0      | 3        | 76        | 79         |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:45 | 20     | 78       | 1455      | 1553       |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:46 | 7      | 321      | 1847      | 2175       |
| Guybrush's Page        | 167959249906191 | link      | 13/05/2020 09:46 | 4      | 2        | 311       | 317        |
| Elaine's Page          | 187202271820522 | photo     | 13/05/2020 09:50 | 2      | 29       | 777       | 808        |
| Elaine's Page          | 187202271820522 | link      | 13/05/2020 09:53 | 0      | 0        | 115       | 115        |
| Herman Toothrot's Page | 201295459914847 | link      | 13/05/2020 10:00 | 143    | 255      | 10211     | 10609      |

The actual dataset extends over multiple days.

I want to make a Seaborn line plot, with time as the X axis ("Date"), and then a COUNT of posts (by day) as the Y axis.

I then want to set one of the numeric variables to the SIZE argument, and break out the Pages ("Name") by HUE.

So the end result would look something like this Seaborn tutorial example:

I know conceptually that this requires a resampling (or some kind of groupby?) by day, to create buckets of summed data for each Page by day, like in this Excel pivottable:

I suspect this may also require a MultiIndex?

I thought I was getting somewhere with,

facebook_dataframe.groupby(["Name", "Date", "Reactions"], as_index=False)["Engagement"].sum()

... but I don't want to have to sum just by Engagement (or just by any one of the variables), and I'd like to be able to plot by day.

I have tried resampling the dataframe by day, but I end up with a series showing either counts or sums, whereas I'd like buckets of days, with all the numeric variables intact (as per the pivot-table, above).

I hope this is clear. I apprecicate that the 20 sample rows provided all fall on one day, but any suggestion solution could resample by minute instead, the approach would be the same? Very grateful for any help

Body:
IIUC, what you want to do is groupby using pd.Grouper to give the freq you want and Name, then use agg with all the columns and functions you want to get like:

data = (df.groupby([pd.Grouper(key='Date', freq='5T'), #replace 5T by D to get daily agggregation
                    'Name'])
          .agg(count=('Name','count'),
               sum_shares=('Shares','sum'),
               sum_comments=('Comments','sum'),
               sum_engagement=('Engagement','sum'), )
          .reset_index()
       )

print (data.head())
                 Date                      Name  count  sum_shares  \
0 2020-05-13 09:00:00   Guybrush's Page              1           4
1 2020-05-13 09:00:00   Herman Toothrot's Page       1          61
2 2020-05-13 09:10:00   Elaine's Page                2           1
3 2020-05-13 09:20:00   Elaine's Page                2           4
4 2020-05-13 09:20:00   Herman Toothrot's Page       1          26

   sum_comments  sum_engagement
0            27             512
1            39             710
2            17             540
3            19             290
4           101             635

then you can use seaborn like:

import seaborn as sns
sns.lineplot(x='Date', y='count', data=data,
             hue='Name',
             size='sum_shares') #here for the size use what summed column you want

I don't post image as there is nothing to see really with the 20 lines of data given.


问:
streaming video from a python server to a web client
How do I stream a video from a python server to an html page web client (nodejs)?

I'm using a node js web project and I'm just writing frames with python and reading them with javascript but I can't use a high frame rate nor a high resolution.

Thanks for helping. This is the code I'm using to read the frame:

```<code>var button = document.getElementById('play');

button.addEventListener('click', function refresh() {

  document.getElementById("myimg").src = "images/color_img.jpg?" + new Date().getTime();
   v= setTimeout(refresh, 100);
});

var button2 = document.getElementById('pause');
button2.addEventListener('click', function myStopFunction() {
  clearTimeout(v);
});
</code>```

答:
First you use simple tag in html :

```<code><video id="videoPlayer" controls> <source src="localhost:3000/video" type="video/mp4"> </video>
</code>```

this link provides live streaming (if python is generating residue frames) and everything you need with nodejs, actually I highly recommend using docker to deploy easily

Body:
How do I stream a video from a python server to an html page web client (nodejs)?

I'm using a node js web project and I'm just writing frames with python and reading them with javascript but I can't use a high frame rate nor a high resolution.

Thanks for helping. This is the code I'm using to read the frame:

var button = document.getElementById('play');

button.addEventListener('click', function refresh() {

  document.getElementById("myimg").src = "images/color_img.jpg?" + new Date().getTime();
   v= setTimeout(refresh, 100);
});

var button2 = document.getElementById('pause');
button2.addEventListener('click', function myStopFunction() {
  clearTimeout(v);
});

Body:
First you use simple tag in html :

<video id="videoPlayer" controls> <source src="localhost:3000/video" type="video/mp4"> </video>

this link provides live streaming (if python is generating residue frames) and everything you need with nodejs, actually I highly recommend using docker to deploy easily