问:
Find the value in where in json clause
I have coupons table where I have rules column which is json

```<code>rules:"{\"books\":[1,2,3,4,5]}"
</code>```

and I have book table which has no relation with coupons table

I also CartVue.vue file where I have store the books in cart .
Now I want to have a attribute called getCouponArrtibute() which will return the coupon
where $coupon->rules->books has the particular book id from cart .

So far I have done this

```<code>public function getCouponAttribute()
{
    $discount = Coupon::whereJsonContains('rules->books', $this->id)->get();
    return $discount;
}
</code>```

and From Cartvue.vue I can now access coupon property but it is returning null or empty array every time wheather that book id is in coupon->rules->books or not

答:
Right now Eloquent believes that $discount->rules is a string. You need to cast this to an object, this is done by utilizing Eloquent Model $casts property. This is done by adding casts property on your Courpon.php model.

```<code>class Coupon {
    protected $casts = [
        'rules' => 'object',
    ];
}
</code>```

This should make the access $coupon->rules->books work.

Title: Find the value in where in json clause

Body:
I have coupons table where I have rules column which is json

rules:"{\"books\":[1,2,3,4,5]}"

and I have book table which has no relation with coupons table

I also CartVue.vue file where I have store the books in cart .
Now I want to have a attribute called getCouponArrtibute() which will return the coupon
where $coupon->rules->books has the particular book id from cart .

So far I have done this

public function getCouponAttribute()
{
    $discount = Coupon::whereJsonContains('rules->books', $this->id)->get();
    return $discount;
}

and From Cartvue.vue I can now access coupon property but it is returning null or empty array every time wheather that book id is in coupon->rules->books or not

Body:
Right now Eloquent believes that $discount->rules is a string. You need to cast this to an object, this is done by utilizing Eloquent Model $casts property. This is done by adding casts property on your Courpon.php model.

class Coupon {
    protected $casts = [
        'rules' => 'object',
    ];
}

This should make the access $coupon->rules->books work.


来源: stackexchange

问:
Modelica - How can I best move a large array from a .CSV file or .MAT file to an external C object?
I am using Open Modelica.

I have a large array of floating point numbers (~4,000,000 numbers) in .csv format or .mat format (they are equally convenient to me).

I load the data into OpenModelica using the ExternData package (.csv) or using Modelica.Utilities.Streams.readRealMatrix (.mat). It is stored as a constant array of Real type.

I have produced a C function that performs some operations on this data set (some weird interpolation). This is associated with an ExternalObject that hold the data, which is given to it through its constructor and Modelica interface.

My problem is that the OpenModelica translator appears to grind to a halt, with massive memory consumption, when faced with a constant array of large size. For example, the follow model translates slowly. If the size of the array is increased, the translation time and memory consumption seems to increase exponentially.

```<code>model test
constant Real[10000,5] test_array;

end test;
</code>```

Is there another way that I can move my data from the .csv or .mat files to the external object? I thought that my external C code could import the .csv or .mat file themselves, but that is quite beyond my almost non-existent C programming ability. Is there another way?

答: The recommended way is to have such large array data not within the model but as external data files. The CombiTimeTable supports both reading from text file and MATLAB MAT file at simulation run-time. You will also benefit from shorter translation times.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am using Open Modelica.

I have a large array of floating point numbers (~4,000,000 numbers) in .csv format or .mat format (they are equally convenient to me).

I load the data into OpenModelica using the ExternData package (.csv) or using Modelica.Utilities.Streams.readRealMatrix (.mat). It is stored as a constant array of Real type.

I have produced a C function that performs some operations on this data set (some weird interpolation). This is associated with an ExternalObject that hold the data, which is given to it through its constructor and Modelica interface.

My problem is that the OpenModelica translator appears to grind to a halt, with massive memory consumption, when faced with a constant array of large size. For example, the follow model translates slowly. If the size of the array is increased, the translation time and memory consumption seems to increase exponentially.

model test
constant Real[10000,5] test_array;

end test;

Is there another way that I can move my data from the .csv or .mat files to the external object? I thought that my external C code could import the .csv or .mat file themselves, but that is quite beyond my almost non-existent C programming ability. Is there another way?


问:
Crystal Report direct saving as PDF, instead of viewing
I want to make a report from ASP.Net, in Crystal Report. I want, when user click on print, it should simply show a browser dialog of Save,Open,Save as, and PDF should be saved, or Crystal Report print preview should appear, I don't want to display report first in Viewer then click on button to get print or PDF, I want simply from clicking on asp button, I have all the idea of parameters and know how to make report, my question is just to not to show viewer and take report from asp button in a form of PDF or print preview dialog to print. I have used the Export method of .Net for Crystal Report, but it does not work.</p>

答:
Here is the solution you are looking for:

http://www.c-sharpcorner.com/UploadFile/mahesh/ExportCRtoPDF10062006161918PM/ExportCRtoPDF.aspx

Here is the quote from the site:

The following steps will guide you to achieve the same:

Add crystal report (.cr) file to your ASP.NET application.
  Add a report instance on the page level.

Dim report As MyReport = New MyReport

Populate reports data on Page_Init

Dim ds As DataSet = GetData()

report.SetDataSource(ds)

Export Report

report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, False, "ExportedReport")

If you wish to format report to other formats, just change the ExportFormatType enumeration value to > your desired format.

If you wish to download the report, then you simply change the third parameter of >ExportToHttpResponse method in Step 4 to True.

ContentLicense: CC BY-SA 3.0


问:
Need to add Spaces at certain Indexes
So this is data i have,

```<code>s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
</code>```

These are the index position where i need to add spaces,

```<code>d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'
</code>```

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction
```

<p>and so on.....</p>

<p>I have calculated the indexes by doing this,</p>

```s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)
```

<p>When I individually try and add the space using the index, I get an output,</p>

```d[0:s[0]] + ' ' + d[s[0]:]
```

<p>I get the following, which is correct</p>

<pre class="lang-none prettyprint-override"><code>'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube
</code>```

But, when I try and iterate over the indexes, i get List out of Range

```<code>temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range
</code>```

答:
Instead of storing the indexes, you could directly store the character to print as follows:

l = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i + 1].islower() and d[i + 2].islower():
        l.append(" ")
    l.append(d[i])
output = "".join(l)
```

<p>However, there are still some problems with this code, it seems like you miss cases like: "InstructionCDMA", "AccessCRT"...
Moreover, you can get some <code>IndexError: string index out of range</code>...</p>

<p>To fix both, you could do:</p>

<pre class="lang-py prettyprint-override"><code>l = []
for i in range(0, len(d) - 2):
    if d[i].isupper() and d[i + 1].islower() and d[i + 2].islower():
        l.append(" ")
    l.append(d[i])
    if d[i].islower() and d[i + 1].isupper() and d[i + 2].isupper():
        l.append(" ")
output = "".join(l)
</code>```

Title: Need to add Spaces at certain Indexes

Body:
So this is data i have,

s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]

These are the index position where i need to add spaces,

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction

and so on.....

I have calculated the indexes by doing this,

s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)

When I individually try and add the space using the index, I get an output,

d[0:s[0]] + ' ' + d[s[0]:]

I get the following, which is correct

'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube

But, when I try and iterate over the indexes, i get List out of Range

temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range

Body:
Instead of storing the indexes, you could directly store the character to print as follows:

l = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i + 1].islower() and d[i + 2].islower():
        l.append(" ")
    l.append(d[i])
output = "".join(l)

However, there are still some problems with this code, it seems like you miss cases like: "InstructionCDMA", "AccessCRT"...
Moreover, you can get some IndexError: string index out of range...

To fix both, you could do:

l = []
for i in range(0, len(d) - 2):
    if d[i].isupper() and d[i + 1].islower() and d[i + 2].islower():
        l.append(" ")
    l.append(d[i])
    if d[i].islower() and d[i + 1].isupper() and d[i + 2].isupper():
        l.append(" ")
output = "".join(l)


问:
Problem with React making Get request to Node(express)
As the title says, i have  a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:

So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"

```<code>async handleClickLicencia (event) {
        event.preventDefault();
        console.log(this.state);
        console.log("licenciaInput: "+this.state.licenciaInput);
        const datoBuscar = this.state.licenciaInput;

        axios.get('http://localhost:3001/atletas/:licencia',this.state)
            .then(response =>{
                console.log(response)

            })
            .catch(error =>{
                console.log(error)
            })
</code>```

And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:

```<code>const getAtletasByLicencia = (request, response) => {
   const licencia = request.body.licenciaInput;
   console.log("Request: "+request);
   console.log("what the server gets: "+licencia);
   // const licencia = request.licenciaInput;
   const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
   pool.query(sentencia, (error, results) =>{
        if(error){
            throw error
        }
        response.status(200).json(results.rows)
    })
}
</code>```

As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.

TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work

I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance

EDIT: Im also adding this code that i have which shows the route for my method in the server:

app.get('/atletas/:licencia', db.getAtletasByLicencia)

As @Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client

答:
Change your request to:

axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
  ...

```

<p>and your route (if you are using express) should look like this:</p>

<pre class="lang-js prettyprint-override"><code>
app.get('/atletas/:licencia', function (req, res) {
  var licencia = req.params.licencia
  ...
})

</code>```

Body:
As the title says, i have  a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:

So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"

async handleClickLicencia (event) {
        event.preventDefault();
        console.log(this.state);
        console.log("licenciaInput: "+this.state.licenciaInput);
        const datoBuscar = this.state.licenciaInput;

        axios.get('http://localhost:3001/atletas/:licencia',this.state)
            .then(response =>{
                console.log(response)

            })
            .catch(error =>{
                console.log(error)
            })

And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:

const getAtletasByLicencia = (request, response) => {
   const licencia = request.body.licenciaInput;
   console.log("Request: "+request);
   console.log("what the server gets: "+licencia);
   // const licencia = request.licenciaInput;
   const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
   pool.query(sentencia, (error, results) =>{
        if(error){
            throw error
        }
        response.status(200).json(results.rows)
    })
}

As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.

TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work

I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance

EDIT: Im also adding this code that i have which shows the route for my method in the server:

app.get('/atletas/:licencia', db.getAtletasByLicencia)

As @Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client

Body:
Change your request to:

axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
  ...

and your route (if you are using express) should look like this:

app.get('/atletas/:licencia', function (req, res) {
  var licencia = req.params.licencia
  ...
})


答:
Maybe a different approach would be simpler. Depending on how consistent your data is you may be able to re.split() on capitalized words r'([A-Z][a-z]+) and capture the delimiter. Something like:

```<code>import re

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

out = " ".join(filter(len, re.split(r'([A-Z][a-z]+)', d)))
</code>```

This will give you:

'CC Carbon Copy CAI Computer Aided Instruction CDMA Code Division Multiple Access CRT Cathode Ray Tube CAD Computer Aided Design CADD Computer Aided Design Drafting CD Compact Disk CDRW Compact Disk Rewritable CAM Computer Aided Manufacturing CROM Computerized Range Motion CDROM Compact Disk Read Only Memory'

This seems to work on your given string, but there could be edge cases if your data is different.

Title: Need to add Spaces at certain Indexes

Body:
Maybe a different approach would be simpler. Depending on how consistent your data is you may be able to re.split() on capitalized words r'([A-Z][a-z]+) and capture the delimiter. Something like:

import re

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

out = " ".join(filter(len, re.split(r'([A-Z][a-z]+)', d)))

This will give you:

'CC Carbon Copy CAI Computer Aided Instruction CDMA Code Division Multiple Access CRT Cathode Ray Tube CAD Computer Aided Design CADD Computer Aided Design Drafting CD Compact Disk CDRW Compact Disk Rewritable CAM Computer Aided Manufacturing CROM Computerized Range Motion CDROM Compact Disk Read Only Memory'

This seems to work on your given string, but there could be edge cases if your data is different.


问:
What is the & operating doing in this situation
In the function below, what is the meaning of the & character? I'm not aware how it's valid syntax or how this would be used normally.

Normally using &= together would do a concatenation and assignment, resulting in "Hello world". However in this "typo" the code actually compiles but the result is just an assignment of " world" to the MyStr variable.  Also if you define MyStr in the function rather than at the class level, the result is that it will not compile and interprets the & as a Type Character and fails because MyStr is a string and not of type Long.

```<code>Public Class MyClassName

    Private MyStr As String

    Public Sub New()

    End Sub

    Public Function MyFunction() As String

        MyStr = "Hello"

        MyStr& = " World"

        Return MyStr

    End Function

End Class
</code>```

答:
```<code>I think this may explain the purpose of the operators

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    XYZ(9&) '  Long values
    XYZ(9L)

    XYZ(9I) ' Int32 values
    XYZ(9%)

    XYZ(9S) 'Int16 value

    XYZ("9"c) ' a single charcter
    XYZ("9") '  a string
End Sub

Sub XYZ(ByVal arg As Object)
    Debug.Print("arg type is " & arg.GetType.ToString)

    'do some stuff depends on the type of arg

End Sub
</code>```

<p>.</p>

Body:
In the function below, what is the meaning of the & character? I'm not aware how it's valid syntax or how this would be used normally.

Normally using &= together would do a concatenation and assignment, resulting in "Hello world". However in this "typo" the code actually compiles but the result is just an assignment of " world" to the MyStr variable.  Also if you define MyStr in the function rather than at the class level, the result is that it will not compile and interprets the & as a Type Character and fails because MyStr is a string and not of type Long.

Public Class MyClassName

    Private MyStr As String

    Public Sub New()

    End Sub

    Public Function MyFunction() As String

        MyStr = "Hello"

        MyStr& = " World"

        Return MyStr

    End Function

End Class

Body:
I think this may explain the purpose of the operators

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    XYZ(9&) '  Long values
    XYZ(9L)

    XYZ(9I) ' Int32 values
    XYZ(9%)

    XYZ(9S) 'Int16 value

    XYZ("9"c) ' a single charcter
    XYZ("9") '  a string
End Sub

Sub XYZ(ByVal arg As Object)
    Debug.Print("arg type is " & arg.GetType.ToString)

    'do some stuff depends on the type of arg

End Sub

.


问:
Combine two NumPy arrays into one structured array for appending to a PyTables table
I have two unstructured NumPy arrays a and b with shapes (N,) and (N, 256, 2) respectively and dtype np.float. I wish to combine these into a single structured array with shape (N,) and dtype [('field1', np.float), ('field2', np.float, (256, 2))].

The documentation on this is surprisingly lacking. I've found methods like np.lib.recfunctions.merge_arrays but have not been able to find the precise combination of features required to do this.

For the sake of avoiding the XY problem, I'll state my wider aims.

I have a PyTables table with layout {"field1": tables.FloatCol(), "field2": tables.FloatCol(shape = (256, 2))}. The two NumPy arrays represent N new rows to be appended to each of these fields. N is large, so I wish to do this with a single efficient table.append(rows) call, rather than the slow process of looping through table.row['field'] = ....

The table.append documentation says

The rows argument may be any object which can be converted to a structured array compliant with the table structure (otherwise, a ValueError is raised). This includes NumPy structured arrays, lists of tuples or array records, and a string or Python buffer.

Converting my arrays to an appropriate structured array seems to be what I should be doing here. I'm looking for speed, and I anticipate the other options being slower.

答:
In order to have test printouts of decent size, my solution assumes:

N = 5,

the second dimension - only 4 (instead of your 256).

To generate the result, proceed as follows:

Start from import numpy.lib.recfunctions as rfn (will be needed soon).

Create source arrays:

```<code>a = np.array([10, 20, 30, 40, 50])
b = np.arange(1, 41).reshape(5, 4, 2)
</code>```

Create the result:

```<code>result = rfn.unstructured_to_structured(
    np.hstack((a[:,np.newaxis], b.reshape(-1,8))),
    np.dtype([('field1', 'f4'), ('field2', 'f4', (4,2))]))
</code>```

The generated array contains:

```<code>array([(10., [[ 1.,  2.], [ 3.,  4.], [ 5.,  6.], [ 7.,  8.]]),
       (20., [[ 9., 10.], [11., 12.], [13., 14.], [15., 16.]]),
       (30., [[17., 18.], [19., 20.], [21., 22.], [23., 24.]]),
       (40., [[25., 26.], [27., 28.], [29., 30.], [31., 32.]]),
       (50., [[33., 34.], [35., 36.], [37., 38.], [39., 40.]])],
      dtype=[('field1', '<f4'), ('field2', '<f4', (4, 2))])
</code>```

Note that the source array to unstructured_to_structured is created
the following way:

Column 0 - from a (converted to a column),

Remaining colums - from b reshaped in such a way that all elements
of the respective 4 * 2 slice are converted to a single row. Data
from each row (from these columns) are converted back to "4 * 2"
shape by this function.

Both the above components are assembled with hstack.

During the above experiments I assumed type of f4, maybe you should change
it to f8 (your decision).

In the target version of the code:

change 4 in the first dimension of field2 to 256,

change 8 in b.reshape to 512 (= 2 * 256).

Body:
In order to have test printouts of decent size, my solution assumes:

N = 5,

the second dimension - only 4 (instead of your 256).

To generate the result, proceed as follows:

Start from import numpy.lib.recfunctions as rfn (will be needed soon).

Create source arrays:

a = np.array([10, 20, 30, 40, 50])
b = np.arange(1, 41).reshape(5, 4, 2)

Create the result:

result = rfn.unstructured_to_structured(
    np.hstack((a[:,np.newaxis], b.reshape(-1,8))),
    np.dtype([('field1', 'f4'), ('field2', 'f4', (4,2))]))

The generated array contains:

array([(10., [[ 1.,  2.], [ 3.,  4.], [ 5.,  6.], [ 7.,  8.]]),
       (20., [[ 9., 10.], [11., 12.], [13., 14.], [15., 16.]]),
       (30., [[17., 18.], [19., 20.], [21., 22.], [23., 24.]]),
       (40., [[25., 26.], [27., 28.], [29., 30.], [31., 32.]]),
       (50., [[33., 34.], [35., 36.], [37., 38.], [39., 40.]])],
      dtype=[('field1', '<f4'), ('field2', '<f4', (4, 2))])

Note that the source array to unstructured_to_structured is created
the following way:

Column 0 - from a (converted to a column),

Remaining colums - from b reshaped in such a way that all elements
of the respective 4 * 2 slice are converted to a single row. Data
from each row (from these columns) are converted back to "4 * 2"
shape by this function.

Both the above components are assembled with hstack.

During the above experiments I assumed type of f4, maybe you should change
it to f8 (your decision).

In the target version of the code:

change 4 in the first dimension of field2 to 256,

change 8 in b.reshape to 512 (= 2 * 256).


问:
How to access docker container localhost
I executed docker-compose up and my services worked as well but unfortunately when i hit the url " http://localhost:3000 " it gives me an error I'll paste the docker-compose.yml here.

```<code>version: "3.7"
services:
  db:
    image: postgres
    container_name: psql
    environment:
      POSTGRES_DB: ${DB_DATABASE}
      POSTGRES_USER: ${DB_USERNAME}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres:/var/lib/postgresql/data
      - ./postgresql/conf:/etc/postgresql/
    restart: always
    ports:
     - '5432:5432'
  api:
    build: .
    container_name: api
    restart: always
    command: yarn start
    depends_on:
      - db
    ports:
      - "3000:3000"
    volumes:
      - .:/usr/app
volumes:
  postgres:
</code>```

When I get into the container and execute curl localhost:3000 it works fine.

答: My problem was solved after I changed the host in my node api to '0.0.0.0' it was 'localhost' so I think the application was running only inside the container and after that change it was visible from all the created network.</p>

Body:
I executed docker-compose up and my services worked as well but unfortunately when i hit the url " http://localhost:3000 " it gives me an error I'll paste the docker-compose.yml here.

version: "3.7"
services:
  db:
    image: postgres
    container_name: psql
    environment:
      POSTGRES_DB: ${DB_DATABASE}
      POSTGRES_USER: ${DB_USERNAME}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres:/var/lib/postgresql/data
      - ./postgresql/conf:/etc/postgresql/
    restart: always
    ports:
     - '5432:5432'
  api:
    build: .
    container_name: api
    restart: always
    command: yarn start
    depends_on:
      - db
    ports:
      - "3000:3000"
    volumes:
      - .:/usr/app
volumes:
  postgres:

When I get into the container and execute curl localhost:3000 it works fine.


问:
jquery: using OR with .click()?
I need help trying to figure out how to use .click() function for two different attributes.

```<code>$('#prev').click(function() {}
</code>```

and

```<code>$('#image').click(function() {}
</code>```

So how would I do an OR statement if user clicks on #prev and #image without writing two identical scripts?

Thanks!

答:
```<code>$('#prev, #image').click(function() {...});
</code>```

or

```<code>function handleClick() {}
$('#prev').click(handleClick);
$('#image').click(handleClick);
</code>```

Title: jquery: using OR with .click()?

Body:
I need help trying to figure out how to use .click() function for two different attributes.

$('#prev').click(function() {}

and

$('#image').click(function() {}

So how would I do an OR statement if user clicks on #prev and #image without writing two identical scripts?

Thanks!

Body:
$('#prev, #image').click(function() {...});

or

function handleClick() {}
$('#prev').click(handleClick);
$('#image').click(handleClick);


问:
Filter values to php array
Below is a variable read that outputs the below results  </p>

```<code> $read = s1 0kg s2 2939kg s3 193kg s4 10kg;
</code>```

<p>how do i filter the values such that i only obtain the values before 'kg' and have them in an array
the output should be </p>

```<code>$read = {0,2939,193,10}
</code>```

答:
With the help of regular expressions, it is:

```<code>$read = 's1 0kg s2 2939kg s3 193kg s4 10kg';
$matches = [];
preg_match_all('/(\d+)kg/', $read, $matches);
// with `minus` sign
// preg_match_all('/(\-?\d+)kg/', $read, $matches);
print_r($matches[1]);
</code>```

Fiddle here.

Title: Filter values to php array

Body:
Below is a variable read that outputs the below results

 $read = s1 0kg s2 2939kg s3 193kg s4 10kg;

how do i filter the values such that i only obtain the values before 'kg' and have them in an array
the output should be

$read = {0,2939,193,10}

Body:
With the help of regular expressions, it is:

$read = 's1 0kg s2 2939kg s3 193kg s4 10kg';
$matches = [];
preg_match_all('/(\d+)kg/', $read, $matches);
// with `minus` sign
// preg_match_all('/(\-?\d+)kg/', $read, $matches);
print_r($matches[1]);

Fiddle here.


问:
Makefile: add prefix to nothing
In Bash, brace expansion just works:

```<code>$ echo client_win{,_throttle,_freq}.exe
client_win.exe client_win_throttle.exe client_win_freq.exe
</code>```

In Makefile:

```<code>$(addsuffix .exe,client_win $(addprefix client_win, _throttle _freq )):client_win.c def.h
client_win.exe:
    $(CC_W)                -o $@ $< -lws2_32
client_win_throttle.exe:
    $(CC_W_REL) -DTHROTTLE -o $@ $< -lws2_32
client_win_freq.exe:
    $(CC_W_REL) -DFREQ     -o $@ $< -lws2_32
</code>```

Is it possible to have client_win itself absorbed into $(addprefix client_win,...)?

Something like this?

```<code>$(addprefix client_win, NOTHING _throttle _freq )
</code>```

答:
This is not easy because make, unlike the shell, has no concept of "existing but zero length string".  Make will expand something and look at the resulting string and if it contains no characters it's as if it didn't exist at all.

You could do something like this:

```<code>$(patsubst %,client_%.exe, win win_throttle win_freq)
</code>```

To remove the "empty" option by adding more to it.

Or you can just write the "empty" one out:

```<code>client-win.exe $(patsubst %,client_win_%.exe, throttle freq)
</code>```

Title: Makefile: add prefix to nothing

Body:
In Bash, brace expansion just works:

$ echo client_win{,_throttle,_freq}.exe
client_win.exe client_win_throttle.exe client_win_freq.exe

In Makefile:

$(addsuffix .exe,client_win $(addprefix client_win, _throttle _freq )):client_win.c def.h
client_win.exe:
    $(CC_W)                -o $@ $< -lws2_32
client_win_throttle.exe:
    $(CC_W_REL) -DTHROTTLE -o $@ $< -lws2_32
client_win_freq.exe:
    $(CC_W_REL) -DFREQ     -o $@ $< -lws2_32

Is it possible to have client_win itself absorbed into $(addprefix client_win,...)?

Something like this?

$(addprefix client_win, NOTHING _throttle _freq )

Body:
This is not easy because make, unlike the shell, has no concept of "existing but zero length string".  Make will expand something and look at the resulting string and if it contains no characters it's as if it didn't exist at all.

You could do something like this:

$(patsubst %,client_%.exe, win win_throttle win_freq)

To remove the "empty" option by adding more to it.

Or you can just write the "empty" one out:

client-win.exe $(patsubst %,client_win_%.exe, throttle freq)


问:
dynamic_cast on a vector of objects c++
I have this code:

```<code>//set the AppSystem's Application Vector
void AppSystem::setAppVector(vector<Application *> &applicationVector){
   try{
       vector<Application *> &tmp1();
       tmp1 = dynamic_cast<vector<Application *>>(applicationVector);
       if ((tmp1 == NULL) || (applicationVector == NULL)) throw new MyExceptions();
       this->ClearAppVector();
       this->AppVector = applicationVector;
   }catch(MyExceptions e){
       return e.ObjectVectorException();
   }
}
</code>```

and I get the following error:

```
AppSystem.cpp:23:69: error: cannot dynamic_cast 'applicationVector' (of type 'class std::vector<Application*>') to type 'class std::vector<Application*>' (target is not pointer or reference)
         tmp1 = dynamic_cast<vector<Application *>>(applicationVector);
```

but the target is a reference of type vector<Application*>. Any suggestion?

答:
vector<Application *> &tmp1(); is not a declaration of a variable named tmp1 of type vector<Application*>&. It is a declaration of a function named tmp1 that returns a vector<Application*>&. Even if it were a variable, you can't declare an uninitialized reference.

As for the error message itself, it is self-explanatory if you actually read it:

target is not pointer or reference

You are passing in a reference to a vector object (that is OK) and trying to cast it to a non-reference type (that is not OK). vector<Application*> is not a reference type. vector<Application*>& is a reference type.

You don't need the dynamic_cast at all. You are trying to cast a reference to a vector<Application*> into a vector<Application*>, which is redundant. And since a reference can't be NULL, and a cast of a reference can't return a NULL pointer, your exception handling is unnecessary, too:

//set the AppSystem's Application Vector
void AppSystem::setAppVector(vector<Application *> &applicationVector)
{
    this->ClearAppVector();
    this->AppVector = applicationVector;
}
```

Title: dynamic_cast on a vector of objects c++

Body:
I have this code:

//set the AppSystem's Application Vector
void AppSystem::setAppVector(vector<Application *> &applicationVector){
   try{
       vector<Application *> &tmp1();
       tmp1 = dynamic_cast<vector<Application *>>(applicationVector);
       if ((tmp1 == NULL) || (applicationVector == NULL)) throw new MyExceptions();
       this->ClearAppVector();
       this->AppVector = applicationVector;
   }catch(MyExceptions e){
       return e.ObjectVectorException();
   }
}

and I get the following error:

AppSystem.cpp:23:69: error: cannot dynamic_cast 'applicationVector' (of type 'class std::vector<Application*>') to type 'class std::vector<Application*>' (target is not pointer or reference)
         tmp1 = dynamic_cast<vector<Application *>>(applicationVector);

but the target is a reference of type vector<Application*>. Any suggestion?


答:
Notice the following:

```<code>s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)
</code>```

Here, i goes from 0 to len(d). What do you think happens when you call d[len(d)+1]?

Title: Need to add Spaces at certain Indexes

Body:
Notice the following:

s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)

Here, i goes from 0 to len(d). What do you think happens when you call d[len(d)+1]?


问:
Not able to create a SignUp page using Django
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py

```<code>def SignUpView(request):

    if request.method == 'POST':
        user_form = SignUpForm(data=request.POST)
        profile_form = ProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            new_profile.user = new_user
            userName = new_user.username
            password = new_profile.password1
            new_user.save(commit=True)
            new_profile.save(commit=True)
            user = authenticate(username = userName, password = password)
            login(request, user)
            return redirect('blog-home')
    else:
        user_form = SignUpForm()
        profile_form = ProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'user/signup.html', context=context)
</code>```

forms.py:

```<code>class SignUpForm(UserCreationForm):
    class meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = ['user', 'email']
</code>```

models.py:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # img =
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.CharField(blank=True, max_length=500)
    location = models.CharField(blank=True, max_length=50)
    email = models.EmailField(unique=True, max_length=200)

    def __str__(self):
        return f'Profile for {self.user.username}'
</code>```

It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.

答:
Change it to - class Meta</p>

```<code>class SignUpForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['user', 'email']
</code>```

Body:
I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py

def SignUpView(request):

    if request.method == 'POST':
        user_form = SignUpForm(data=request.POST)
        profile_form = ProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            new_profile.user = new_user
            userName = new_user.username
            password = new_profile.password1
            new_user.save(commit=True)
            new_profile.save(commit=True)
            user = authenticate(username = userName, password = password)
            login(request, user)
            return redirect('blog-home')
    else:
        user_form = SignUpForm()
        profile_form = ProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'user/signup.html', context=context)

forms.py:

class SignUpForm(UserCreationForm):
    class meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class meta:
        model = Profile
        fields = ['user', 'email']

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # img =
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.CharField(blank=True, max_length=500)
    location = models.CharField(blank=True, max_length=50)
    email = models.EmailField(unique=True, max_length=200)

    def __str__(self):
        return f'Profile for {self.user.username}'

It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.

Body:
Change it to - class Meta

class SignUpForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['user', 'email']


问:
Silverlight - RIA Services - get insert ID
I am using RIA services in my Silverlight Application the following is the code generated by Visual Studio 2010,

```<code>public void InsertDiscussion_topic(discussion_topic discussion_topic)
{
    if ((discussion_topic.EntityState != EntityState.Detached))
    {
        this.ObjectContext.ObjectStateManager.ChangeObjectState(discussion_topic, EntityState.Added);
    }
    else
    {
        this.ObjectContext.discussion_topics.AddObject(discussion_topic);
    }
}
</code>```

now this doesn't return the inserted ID how do i get the inserted ID?

thank you for all the help!!!

答:
If you use WCF RIa Services, you Id will automatically updated after DataContext.SubmitChanges()</p>

```<code>MyEntity ent = new MyEntity(); //entity that has Id, mapped
//from primary key (Identity) from data base

MyDataContext.MyEntities.Add(ent);
MyDataContext.SubmitChanges(op => { if (!op.HasError) MessageBox.Show(ent.Id.ToString()); });
</code>```

Body:
I am using RIA services in my Silverlight Application the following is the code generated by Visual Studio 2010,

public void InsertDiscussion_topic(discussion_topic discussion_topic)
{
    if ((discussion_topic.EntityState != EntityState.Detached))
    {
        this.ObjectContext.ObjectStateManager.ChangeObjectState(discussion_topic, EntityState.Added);
    }
    else
    {
        this.ObjectContext.discussion_topics.AddObject(discussion_topic);
    }
}

now this doesn't return the inserted ID how do i get the inserted ID?

thank you for all the help!!!

Body:
If you use WCF RIa Services, you Id will automatically updated after DataContext.SubmitChanges()

MyEntity ent = new MyEntity(); //entity that has Id, mapped
//from primary key (Identity) from data base

MyDataContext.MyEntities.Add(ent);
MyDataContext.SubmitChanges(op => { if (!op.HasError) MessageBox.Show(ent.Id.ToString()); });


问:
Keeping track of the shortest path between two nodes using Dijkstra's algorithm
I am quite new to c++ and have been having trouble modifying Dijkstra's algorithm to keep track of the shortest path between two nodes, not just the shortest distance. I have it computing the shortest distance correctly. This is the function that calculates the shortest distance:

```<code>  vector<vertex<T>> shortest_path(directed_graph<T> g, int u_id, int v_id) {
  vector<vertex<T>> shortest;
  vector<vector<T>> graph = g.get_adjacency_matrix();

  if (!g.contains(u_id) && !g.contains(v_id)) {
    return shortest;
  }

  shortest.push_back(vertex<T>(u_id, g.get_vert_weight(u_id)));

  int *dist = new int[g.num_vertices()]; // Will hold the shortest distance from u_id to i
  bool *sptSet = new bool[g.num_vertices()]; // Will be true if vertex i is including in shortest path tree from u_id to i

  int parent[g.num_vertices()]; // parent to store the shortest path tree

  // initialise all distances as INFINITE and set stpset as false
  for (int i = 0; i < g.num_vertices(); i++) {
    parent[u_id] = -1;
    dist[i] = INT_MAX;
    sptSet[i] = false;
  }

  dist[u_id] = 0; // Distance of source vertex to itself is always 0

  for (int count = 0; count < (g.num_vertices() - 1); count++) { // find shortest path for all vertices
    int u = min_distance(dist, sptSet, g.num_vertices()); // pick the min distance vertex from the set of vertices not yet processed
    sptSet[u] = true; // mark the picked vertex as processed

    for (int v = 0; v < g.num_vertices(); v++) { // update dist value of the adjacent vertices of the picked vertex
      // update dist[v] only if its not in sptset, there is an edge from u to v, and total weight of path from u_id to v
      // through u is smaller than current distance value of dist[v]
      if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
        parent[v] = u;
        dist[v] = dist[u] + graph[u][v];
      }
    }
  }

  for (int i = 0; i < g.num_vertices(); i++) {
    if (dist[i] != INT_MAX) {
      cout << u_id << " -> " << i << " : " << dist[i] << endl;
    } else {
      cout << u_id << " -> " << i << " : n/a" << endl;
    }
  }

  return shortest;

}
</code>```

and here is the graph I've been using for testing:

```<code>    g1.add_edge(0, 1, 4);
    g1.add_edge(7, 0, 8);
    g1.add_edge(1, 7, 11);
    g1.add_edge(7, 8, 7);
    g1.add_edge(1, 2, 8);
    g1.add_edge(8, 2, 2);
    g1.add_edge(7, 6, 1);
    g1.add_edge(8, 6, 6);
    g1.add_edge(6, 5, 2);
    g1.add_edge(5, 2, 4);
    g1.add_edge(2, 3, 7);
    g1.add_edge(3, 5, 14);
    g1.add_edge(4, 3, 9);
    g1.add_edge(5, 4, 10);
</code>```

Could someone please help me with the shortest path bit?

答:
You could make use of parent array to reconstruct the path starting from target node to source node, for example:

```<code>vector<int> path;
int idx = v_id;
while (idx != u_id) {
    path.emplace_back(idx);
    idx = parent[idx];
}
path.emplace_back(idx);
reverse(path.begin, path.end());
cout << "PATH: ";
for (int x : path) {
    cout << x << " ";
}
</code>```

Body:
I am quite new to c++ and have been having trouble modifying Dijkstra's algorithm to keep track of the shortest path between two nodes, not just the shortest distance. I have it computing the shortest distance correctly. This is the function that calculates the shortest distance:

  vector<vertex<T>> shortest_path(directed_graph<T> g, int u_id, int v_id) {
  vector<vertex<T>> shortest;
  vector<vector<T>> graph = g.get_adjacency_matrix();

  if (!g.contains(u_id) && !g.contains(v_id)) {
    return shortest;
  }

  shortest.push_back(vertex<T>(u_id, g.get_vert_weight(u_id)));

  int *dist = new int[g.num_vertices()]; // Will hold the shortest distance from u_id to i
  bool *sptSet = new bool[g.num_vertices()]; // Will be true if vertex i is including in shortest path tree from u_id to i

  int parent[g.num_vertices()]; // parent to store the shortest path tree

  // initialise all distances as INFINITE and set stpset as false
  for (int i = 0; i < g.num_vertices(); i++) {
    parent[u_id] = -1;
    dist[i] = INT_MAX;
    sptSet[i] = false;
  }

  dist[u_id] = 0; // Distance of source vertex to itself is always 0

  for (int count = 0; count < (g.num_vertices() - 1); count++) { // find shortest path for all vertices
    int u = min_distance(dist, sptSet, g.num_vertices()); // pick the min distance vertex from the set of vertices not yet processed
    sptSet[u] = true; // mark the picked vertex as processed

    for (int v = 0; v < g.num_vertices(); v++) { // update dist value of the adjacent vertices of the picked vertex
      // update dist[v] only if its not in sptset, there is an edge from u to v, and total weight of path from u_id to v
      // through u is smaller than current distance value of dist[v]
      if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
        parent[v] = u;
        dist[v] = dist[u] + graph[u][v];
      }
    }
  }

  for (int i = 0; i < g.num_vertices(); i++) {
    if (dist[i] != INT_MAX) {
      cout << u_id << " -> " << i << " : " << dist[i] << endl;
    } else {
      cout << u_id << " -> " << i << " : n/a" << endl;
    }
  }

  return shortest;

}

and here is the graph I've been using for testing:

    g1.add_edge(0, 1, 4);
    g1.add_edge(7, 0, 8);
    g1.add_edge(1, 7, 11);
    g1.add_edge(7, 8, 7);
    g1.add_edge(1, 2, 8);
    g1.add_edge(8, 2, 2);
    g1.add_edge(7, 6, 1);
    g1.add_edge(8, 6, 6);
    g1.add_edge(6, 5, 2);
    g1.add_edge(5, 2, 4);
    g1.add_edge(2, 3, 7);
    g1.add_edge(3, 5, 14);
    g1.add_edge(4, 3, 9);
    g1.add_edge(5, 4, 10);

Could someone please help me with the shortest path bit?

Body:
You could make use of parent array to reconstruct the path starting from target node to source node, for example:

vector<int> path;
int idx = v_id;
while (idx != u_id) {
    path.emplace_back(idx);
    idx = parent[idx];
}
path.emplace_back(idx);
reverse(path.begin, path.end());
cout << "PATH: ";
for (int x : path) {
    cout << x << " ";
}


问:
Are there any examples of abstract class vs interface use in the java standard libraries from jdk-8 on forward?
For example, in the java tutorials (https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html), the AbstractMap class is used as an example for an abstract class. Since jdk8, where interface methods can now be default or static, is there any reason (other than the fact that it's already there and previously made sense) that AbstractMap couldn't have been an interface? As far as I understand, the remaining differences post jdk8 are:

An abstract class can be used to abstract state (not constrained to static final fields/ and have can have constructors) where an interface can not.

Multiple interfaces can be implemented (by related or unrelated classes) while only one class can be extended.

The added functionality to interface was to preserve backwards compatibility.

It looks like if done from scratch, an interface would have provided largely the same functionality in most cases, and deciding on which to use boils down to points 1 and 2 regardless of 3 being the reason for the expanded interface functionality.

Is there anything I'm missing? Are there any examples of standard library classes made at or post jdk8 that exemplify these differences? I'm learning so please forgive me if I've overlooked something.

答:
One point missing from the list is protected methods. An interface can only have public ones. So, if you have a template method pattern, where you want the subclasses to implements something, but not expose it as a public API, you can't do that with an interface.

An example could be AbstractList#removeRange(int, int). Also an example of no.1 from your list (has a protected field).

Now, to why particularily the AbstractMap is not an interface in the new APIs, I can't speak for JDK developers. One thing is the java.util collections share a similar design and changing one but not the others would break consistency. Some backwards compatibility too. Even if personally I wouldn't probably depend on the fact that something is a class rather than an interface.


问:
AAPT: error: resource drawable/example (aka com.app:drawable/example) not found
I added one shape to the drawable folder as follows;

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:color="#7A828D" android:width="1dp"/>
    <solid android:color="@color/white" />
    <corners android:radius="8dp"/>
</shape>
</code>```

Then I included this in my layout;

```<code><androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="64dp"
            android:background="@drawable/shape_info_bg_1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@id/sl_userid"
            android:layout_marginBottom="20dp">
            <ImageView
                android:id="@+id/img_info"
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:src="@drawable/ico_info"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginStart="20dp"
                />
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                tools:text="asdasdasdasda"
                android:fontFamily="@font/medium"
                android:layout_marginEnd="50dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/img_info"
                app:layout_constraintTop_toTopOf="@id/img_info"
                app:layout_constraintBottom_toBottomOf="@+id/img_info"
                android:layout_marginStart="15dp"/>
        </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

and when i get build on real device i get the following errors;

```<code>...\src\main\res\layout\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxxx:drawable/shape_info_bg_1) not found.

    AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{"file":"C:\\Users\\xxxx\\Documents\\xxxx\\app\\src\\main\\res\\layout\\activity_login.xml","position":{"startLine":40}}],"original":"C:\\Users\\xxxx\\Documents\\xxxx\\app\\src\\main\\res\\layout\\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxx:drawable/shape_info_bg_1) not found.\n    ","tool":"AAPT"}

> Task :app:mergeExtDexDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\xxxxx\Documents\xxxxx\app\src\main\res\layout\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxxx/shape_info_bg_1) not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 12s
</code>```

I always add shape in this way and there is no problem. I could not solve this problem. I have never met before, can you help me?

答:
Delete The File And Build The Project.

Create The File again which you have deleted.

Body:
I added one shape to the drawable folder as follows;

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:color="#7A828D" android:width="1dp"/>
    <solid android:color="@color/white" />
    <corners android:radius="8dp"/>
</shape>

Then I included this in my layout;

<androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="64dp"
            android:background="@drawable/shape_info_bg_1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@id/sl_userid"
            android:layout_marginBottom="20dp">
            <ImageView
                android:id="@+id/img_info"
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:src="@drawable/ico_info"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginStart="20dp"
                />
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                tools:text="asdasdasdasda"
                android:fontFamily="@font/medium"
                android:layout_marginEnd="50dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/img_info"
                app:layout_constraintTop_toTopOf="@id/img_info"
                app:layout_constraintBottom_toBottomOf="@+id/img_info"
                android:layout_marginStart="15dp"/>
        </androidx.constraintlayout.widget.ConstraintLayout>

and when i get build on real device i get the following errors;

...\src\main\res\layout\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxxx:drawable/shape_info_bg_1) not found.

    AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{"file":"C:\\Users\\xxxx\\Documents\\xxxx\\app\\src\\main\\res\\layout\\activity_login.xml","position":{"startLine":40}}],"original":"C:\\Users\\xxxx\\Documents\\xxxx\\app\\src\\main\\res\\layout\\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxx:drawable/shape_info_bg_1) not found.\n    ","tool":"AAPT"}

> Task :app:mergeExtDexDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\xxxxx\Documents\xxxxx\app\src\main\res\layout\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxxx/shape_info_bg_1) not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 12s

I always add shape in this way and there is no problem. I could not solve this problem. I have never met before, can you help me?


问:
How to get file size in byte using wc -c
when I use the command to get the file size in bye using wc -c the command return two values, the size in byte and the file name, ex:
the output for wc -c my_file is 322 my_file
I need to get only the first value to use it if condition, and I need to use this specific command not any other one..
Any help please, thank you.

答:
This can also be done without redirection or wastefully reading the whole file using stat:

```<code>stat -c %s my_file
</code>```

Body:
This can also be done without redirection or wastefully reading the whole file using stat:

stat -c %s my_file


问:
responses mock requests.ConnectionError, assert function
I have a function that returns False if a requests.ConnectionError occurred.
How can I test the result of the function in case this exception happens?

The following test fails with the Exception rather than asserting that the function should return False

```<code>@responses.activate
def test_get_system_mem_failure(self):
    responses.add(responses.GET,"https://myapi.com/api",
        body=Exception(requests.ConnectionError))
    with pytest.raises(requests.ConnectionError):
        self.assertEqual(sm.get_system_mem(),False)
</code>```

答:
Got help from Github user hramezani
Assuming that the function is something like this:

```<code>def test_func():
    try:
        # some code which calls https://myapi.com/api and
        # might cause requests.ConnectionError
        requests.get("https://myapi.com/api")
    except requests.ConnectionError:
        return False
</code>```

You can test your function behavior(return Fales in case of requests.ConnectionError) like this:

```<code>@responses.activate
def test_get_system_mem_failure():
    responses.add(responses.GET,"https://myapi.com/api",
        body=requests.ConnectionError())

    assert test_func() is False
</code>```

Body:
I have a function that returns False if a requests.ConnectionError occurred.
How can I test the result of the function in case this exception happens?

The following test fails with the Exception rather than asserting that the function should return False

@responses.activate
def test_get_system_mem_failure(self):
    responses.add(responses.GET,"https://myapi.com/api",
        body=Exception(requests.ConnectionError))
    with pytest.raises(requests.ConnectionError):
        self.assertEqual(sm.get_system_mem(),False)

Body:
Got help from Github user hramezani
Assuming that the function is something like this:

def test_func():
    try:
        # some code which calls https://myapi.com/api and
        # might cause requests.ConnectionError
        requests.get("https://myapi.com/api")
    except requests.ConnectionError:
        return False

You can test your function behavior(return Fales in case of requests.ConnectionError) like this:

@responses.activate
def test_get_system_mem_failure():
    responses.add(responses.GET,"https://myapi.com/api",
        body=requests.ConnectionError())

    assert test_func() is False


问:
Create column with grouped means in r
so i have a dataset of countries that have a variable called "country wave" and another called "famsaved". I want a function that adds a column to the set that gives me the mean for "famsaved" for the country wave category. I know that in STATA the function is egen AverFamSave = mean(FamSavedThisYr01), by(Country Wave).... any help?</p>

答:
We can use aggregate in base R

```<code>aggregate(FamSavedThisYr01~ Country + Wave, df1, mean, na.rm = TRUE)
</code>```

If we need to create a column, use ave

```<code>df1$MeanFamSavedThisYr01 <- with(df1, ave(FamSavedThisYr01, Country, Wave))
</code>```

Title: Create column with grouped means in r

Body:
We can use aggregate in base R

aggregate(FamSavedThisYr01~ Country + Wave, df1, mean, na.rm = TRUE)

If we need to create a column, use ave

df1$MeanFamSavedThisYr01 <- with(df1, ave(FamSavedThisYr01, Country, Wave))


问:
Using same domain name for frontend and backend deployment in aws
I am trying to deploy my angular app and nodejs server on aws. To deploy the angular app, I am using s3 bucket and enable static website hosting.
To deploy nodejs, I am using ec2. I have chosen to keep both the server and angular frontend separate.

I wanted to know how this will be available to the outside world. I have purchased a domain name say www.example.com. I am attaching with an s3 bucket, so upon launching www.example.com, I get to see my angular app. But I also want to use the same domain for my nodejs server as my angular app is making API calls to the nodejs server. Do I need to purchase a different domain for my backend server?
In my local development, I was simply running my frontend on localhost:4200 and nodje on localhost:3000. But I am not sure how it would work on the cloud.

答:
I've made the following diagram showing the pieces which this request will flow through:

As @jogold has said, the key is CloudFront, which will behave redirecting to FrontEnd or BackEnd (Same distribution, multiple origins, multiple behaviors)

Remember to create a new origin ("Origins and Origin Groups" tab), but also a new behavior ("Behaviors" tab): Use the expected "Path Param" (Your app also should have this as a BasePath) and pay attention to "Precedence" (Default must always be the last).

In my case, "PathParam" value for BackEnd was "/api/*"


问:
Using objects to discriminate union types
I am trying to create union types in TypeScript where the discriminator is a value on a nested object, rather than a primitive value directly on the type. I am working with objects returned from an API and therefore cannot alter the data structures being returned.

Is this possible in TypeScript, without needing to resort to user-defined type guards?

Here is a simplified example:

```<code>type SquareIdentifier = {
  type: "square";
};

type CircleIdentifier = {
  type: "circle";
};

type SquareShape = {
  identifier: SquareIdentifier;
  sideLength: number;
};

type CircleShape = {
  identifier: CircleIdentifier;
  diameter: number;
};

type Shape = SquareShape | CircleShape;

// assume we have been given a variable `x` of Shape
const x = ({} as any) as Shape;

// at this point, x.identifier is considered a SquareIdentifier | CircleIdentifier
if (x.identifier.type === "square") {
  // at this point, x.identifier is considered a SquareIdentifier
  // however, x is still considered a Shape, not a SquareShape, which is the only Shape to contain a ShapeIdentifier
  // error here is:
  // "Property 'sideLength' does not exist on type 'Shape'"
  // "Property 'sideLength' does not exist on type 'CircleShape'"
  console.log(x.sideLength);
}
</code>```

答:
In your example, I would use in operator type guard:

type Shape = SquareShape | CircleShape;
// assume we have been given a variable `x` of Shape
const x = ({} as any) as Shape;

if ('sideLength' in x) {
  // x is inferred as SquareShape
  console.log(x.sideLength);
}
```

Body:
I am trying to create union types in TypeScript where the discriminator is a value on a nested object, rather than a primitive value directly on the type. I am working with objects returned from an API and therefore cannot alter the data structures being returned.

Is this possible in TypeScript, without needing to resort to user-defined type guards?

Here is a simplified example:

type SquareIdentifier = {
  type: "square";
};

type CircleIdentifier = {
  type: "circle";
};

type SquareShape = {
  identifier: SquareIdentifier;
  sideLength: number;
};

type CircleShape = {
  identifier: CircleIdentifier;
  diameter: number;
};

type Shape = SquareShape | CircleShape;

// assume we have been given a variable `x` of Shape
const x = ({} as any) as Shape;

// at this point, x.identifier is considered a SquareIdentifier | CircleIdentifier
if (x.identifier.type === "square") {
  // at this point, x.identifier is considered a SquareIdentifier
  // however, x is still considered a Shape, not a SquareShape, which is the only Shape to contain a ShapeIdentifier
  // error here is:
  // "Property 'sideLength' does not exist on type 'Shape'"
  // "Property 'sideLength' does not exist on type 'CircleShape'"
  console.log(x.sideLength);
}


问:
Pandas split column into multiple columns by comma
I am trying to split a column into multiple columns based on comma/space separation.

My dataframe currently looks like

```<code>     KEYS                                                  1
0   FIT-4270                                          4000.0439
1   FIT-4269                                          4000.0420, 4000.0471
2   FIT-4268                                          4000.0419
3   FIT-4266                                          4000.0499
4   FIT-4265                                          4000.0490, 4000.0499, 4000.0500, 4000.0504,
</code>```

I would like

```<code>   KEYS                                                  1           2            3        4
0   FIT-4270                                          4000.0439
1   FIT-4269                                          4000.0420  4000.0471
2   FIT-4268                                          4000.0419
3   FIT-4266                                          4000.0499
4   FIT-4265                                          4000.0490  4000.0499  4000.0500  4000.0504
</code>```

My code currently removes The KEYS column and I'm not sure why. Could anyone improve or help fix the issue?

```<code>v = dfcleancsv[1]

#splits the columns by spaces into new columns but removes KEYS?

dfcleancsv = dfcleancsv[1].str.split(' ').apply(Series, 1)
</code>```

答:
Check this out</p>

```<code>Responder_id    LanguagesWorkedWith
0   1   HTML/CSS;Java;JavaScript;Python
1   2   C++;HTML/CSS;Python
2   3   HTML/CSS
3   4   C;C++;C#;Python;SQL
4   5   C++;HTML/CSS;Java;JavaScript;Python;SQL;VBA
... ... ...
87564   88182   HTML/CSS;Java;JavaScript
87565   88212   HTML/CSS;JavaScript;Python
87566   88282   Bash/Shell/PowerShell;Go;HTML/CSS;JavaScript;W...
87567   88377   HTML/CSS;JavaScript;Other(s):
87568   88863   Bash/Shell/PowerShell;HTML/CSS;Java;JavaScript...`
###Split the LanguagesWorkedWith column into  multiple columns  by using` data= data1['LanguagesWorkedWith'].str.split(';').apply(pd.Series)`.###
` data1 = pd.read_csv('data.csv', sep=',')
data1.set_index('Responder_id',inplace=True)
data1
data1.loc[1,:]
data= data1['LanguagesWorkedWith'].str.split(';').apply(pd.Series)
data.head()`

</code>```

Body:
I am trying to split a column into multiple columns based on comma/space separation.

My dataframe currently looks like

     KEYS                                                  1
0   FIT-4270                                          4000.0439
1   FIT-4269                                          4000.0420, 4000.0471
2   FIT-4268                                          4000.0419
3   FIT-4266                                          4000.0499
4   FIT-4265                                          4000.0490, 4000.0499, 4000.0500, 4000.0504,

I would like

   KEYS                                                  1           2            3        4
0   FIT-4270                                          4000.0439
1   FIT-4269                                          4000.0420  4000.0471
2   FIT-4268                                          4000.0419
3   FIT-4266                                          4000.0499
4   FIT-4265                                          4000.0490  4000.0499  4000.0500  4000.0504

My code currently removes The KEYS column and I'm not sure why. Could anyone improve or help fix the issue?

v = dfcleancsv[1]

#splits the columns by spaces into new columns but removes KEYS?

dfcleancsv = dfcleancsv[1].str.split(' ').apply(Series, 1)

Body:
Check this out

Responder_id    LanguagesWorkedWith
0   1   HTML/CSS;Java;JavaScript;Python
1   2   C++;HTML/CSS;Python
2   3   HTML/CSS
3   4   C;C++;C#;Python;SQL
4   5   C++;HTML/CSS;Java;JavaScript;Python;SQL;VBA
... ... ...
87564   88182   HTML/CSS;Java;JavaScript
87565   88212   HTML/CSS;JavaScript;Python
87566   88282   Bash/Shell/PowerShell;Go;HTML/CSS;JavaScript;W...
87567   88377   HTML/CSS;JavaScript;Other(s):
87568   88863   Bash/Shell/PowerShell;HTML/CSS;Java;JavaScript...`
###Split the LanguagesWorkedWith column into  multiple columns  by using` data= data1['LanguagesWorkedWith'].str.split(';').apply(pd.Series)`.###
` data1 = pd.read_csv('data.csv', sep=',')
data1.set_index('Responder_id',inplace=True)
data1
data1.loc[1,:]
data= data1['LanguagesWorkedWith'].str.split(';').apply(pd.Series)
data.head()`


问:
Getting the Stacktrace
When Exception happens you can print out the StackTrace and review it.

What if you want to get the StackTrace without an exception happening?

Is there a way to do this?

答: System.Environment.StackTrace is an awesome tool, but be aware that you don't always get what you're looking for and there are differences between x86 and x64 platforms that can affect the output.  Grody details here.</p>

OwnerDisplayName: Debbi

LastEditorDisplayName: BtBh

Title: Getting the Stacktrace

OwnerDisplayName: plinth

ContentLicense: CC BY-SA 2.5


问:
Disabling editing on rows based on boolean value, but editing is being disabled in all rows when it shouldn't be
I am trying to set rows columns to be disabled based on boolean value true, but not the Age column. When I run this it should only be setting 3 rows columns to be disabled, but its disabling all the columns, and it shouldn't be.

The flaw is my logic, but not sure exactly where though.

$(document).ready(function() {
  LoadBasicGrid();
});

$('#btn').on('click', () => {
  SetGridIntoReadOnly()
});

function LoadBasicGrid() {
  CreateGrid();
}

function CreateGrid() {
  let ds = [{
      "PersonID": 1,
      "First": "Albert",
      "Last": "Crane",
      "Age": 30,
      "City": "Toronto"
    },
    {
      "PersonID": 2,
      "First": "Betty",
      "Last": "Page",
      "Age": 23,
      "City": "Toronto"
    },
    {
      "PersonID": 3,
      "First": "Carol",
      "Last": "Michaels",
      "Age": 20,
      "City": "Brampton"
    },
    {
      "PersonID": 4,
      "First": "Dale",
      "Last": "Burns",
      "Age": 40,
      "City": "Etobicoke"
    },
    {
      "PersonID": 5,
      "First": "Edward",
      "Last": "Jones",
      "Age": 35,
      "City": "Bramalea"
    }
  ];

  $("#BasicGrid").empty();
  $("#BasicGrid").kendoGrid({
    dataSource: {
      data: ds,
      schema: {
        model: {
          id: "PersonID",
          fields: {
            PersonID: {
              type: "number",
              editable: false,
              hidden: true
            },
            First: {
              type: "string",
              editable: true
            },
            Last: {
              type: "string",
              editable: true
            },
            Age: {
              type: "number",
              editable: true
            },
            City: {
              type: "string",
              editable: true
            }
          }
        }
      }
    },

    selectable: "row",
    navigatable: true,
    scrollable: true,
    editable: {
      mode: "incell",
      confirmation: false
    },
    beforeEdit: function(e) {

    },
    edit: function(e) {

    },
    change: function(e) {

    },
    columns: [{
        field: "PersonID",
        title: "PersonID",
        editable: false,
        hidden: true
      },
      {
        field: "First",
        title: "First"
      },
      {
        field: "Last",
        title: "Last"
      },
      {
        field: "Age",
        title: "Age"
      },
      {
        field: "City",
        title: "City"
      }
    ],
    height: 300
  });
}

var EditableColumns = ['First', 'Last', 'Age', 'City'];
var PersonID = {
  "Person": [{
    "Orientation": [{
        "PersonID": 1,
        "Male": true
      },
      {
        "PersonID": 2,
        "Male": false
      },
      {
        "PersonID": 3,
        "Male": false
      },
      {
        "PersonID": 4,
        "Male": true
      },
      {
        "PersonID": 5,
        "Male": true
      }
    ]
  }]
};

function SetGridIntoReadOnly() {
  let grid = $('#BasicGrid').getKendoGrid();
  let person = PersonID.Person[0].Orientation;
  person.forEach((e, i) => {
    for (let i = 0; i < grid.dataSource.view().length; i++) {
      if (grid.dataSource.at(i).PersonID === e.PersonID) {
        if (e.Male === true) {
          //console.log(e.PersonID + ": " + i);
          for (let j = 0; j < EditableColumns.length - 1; j++) {
            if (EditableColumns[j] != "Age") {
              grid.dataSource.at(i).fields[EditableColumns[j]].editable = false;
            }
          }
        }
      }
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.2.513/styles/kendo.default-v2.min.css" />
<script src="https://kendo.cdn.telerik.com/2020.2.513/js/kendo.all.min.js"></script>

<div id="BasicGrid"></div>

<button id="btn"> Disable Edit </button></code>```

答:
So I figured out how to do it without a bunch of code, and it was right in front of my face the whole time, I added this in the edit function</p>

```<code>let foundPerson = PersonID.Person[0].Orientation.find(f => f.PersonID === e.model.PersonID).Male;
if (foundPerson === true && e.sender.editable.options.fields.field != "Age") {
    this.closeCell();
}
</code>```

Body:
I am trying to set rows columns to be disabled based on boolean value true, but not the Age column. When I run this it should only be setting 3 rows columns to be disabled, but its disabling all the columns, and it shouldn't be.

The flaw is my logic, but not sure exactly where though.

$(document).ready(function() {
  LoadBasicGrid();
});

$('#btn').on('click', () => {
  SetGridIntoReadOnly()
});

function LoadBasicGrid() {
  CreateGrid();
}

function CreateGrid() {
  let ds = [{
      "PersonID": 1,
      "First": "Albert",
      "Last": "Crane",
      "Age": 30,
      "City": "Toronto"
    },
    {
      "PersonID": 2,
      "First": "Betty",
      "Last": "Page",
      "Age": 23,
      "City": "Toronto"
    },
    {
      "PersonID": 3,
      "First": "Carol",
      "Last": "Michaels",
      "Age": 20,
      "City": "Brampton"
    },
    {
      "PersonID": 4,
      "First": "Dale",
      "Last": "Burns",
      "Age": 40,
      "City": "Etobicoke"
    },
    {
      "PersonID": 5,
      "First": "Edward",
      "Last": "Jones",
      "Age": 35,
      "City": "Bramalea"
    }
  ];

  $("#BasicGrid").empty();
  $("#BasicGrid").kendoGrid({
    dataSource: {
      data: ds,
      schema: {
        model: {
          id: "PersonID",
          fields: {
            PersonID: {
              type: "number",
              editable: false,
              hidden: true
            },
            First: {
              type: "string",
              editable: true
            },
            Last: {
              type: "string",
              editable: true
            },
            Age: {
              type: "number",
              editable: true
            },
            City: {
              type: "string",
              editable: true
            }
          }
        }
      }
    },

    selectable: "row",
    navigatable: true,
    scrollable: true,
    editable: {
      mode: "incell",
      confirmation: false
    },
    beforeEdit: function(e) {

    },
    edit: function(e) {

    },
    change: function(e) {

    },
    columns: [{
        field: "PersonID",
        title: "PersonID",
        editable: false,
        hidden: true
      },
      {
        field: "First",
        title: "First"
      },
      {
        field: "Last",
        title: "Last"
      },
      {
        field: "Age",
        title: "Age"
      },
      {
        field: "City",
        title: "City"
      }
    ],
    height: 300
  });
}

var EditableColumns = ['First', 'Last', 'Age', 'City'];
var PersonID = {
  "Person": [{
    "Orientation": [{
        "PersonID": 1,
        "Male": true
      },
      {
        "PersonID": 2,
        "Male": false
      },
      {
        "PersonID": 3,
        "Male": false
      },
      {
        "PersonID": 4,
        "Male": true
      },
      {
        "PersonID": 5,
        "Male": true
      }
    ]
  }]
};

function SetGridIntoReadOnly() {
  let grid = $('#BasicGrid').getKendoGrid();
  let person = PersonID.Person[0].Orientation;
  person.forEach((e, i) => {
    for (let i = 0; i < grid.dataSource.view().length; i++) {
      if (grid.dataSource.at(i).PersonID === e.PersonID) {
        if (e.Male === true) {
          //console.log(e.PersonID + ": " + i);
          for (let j = 0; j < EditableColumns.length - 1; j++) {
            if (EditableColumns[j] != "Age") {
              grid.dataSource.at(i).fields[EditableColumns[j]].editable = false;
            }
          }
        }
      }
    }
  });
}

<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.2.513/styles/kendo.default-v2.min.css" />

<button id="btn"> Disable Edit </button>

Body:
So I figured out how to do it without a bunch of code, and it was right in front of my face the whole time, I added this in the edit function

let foundPerson = PersonID.Person[0].Orientation.find(f => f.PersonID === e.model.PersonID).Male;
if (foundPerson === true && e.sender.editable.options.fields.field != "Age") {
    this.closeCell();
}


问:
Set Word style font to default theme font using Powershell (or VBA)
I'm writing a script to modify styles in a Word document. for each style I want to set the font to either the default 'Body' or 'Headings' style as determined by the document theme.

It's easy to set a style to a specific font:

```<code># Powershell
$word = New-Object -ComObject Word.Application
$word.Documents.Add()
$doc = $word.Documents | Select-Object -first 1

$doc.Styles["Normal"].Font.Name = "Calibri"
</code>```

How do I set the style to either the Body or Headings font?

答:
Since .Minorfont(...).Name is just a string, the cited code changes Normal style to whatever the Body theme font face is currently.  But if you then change the Body theme font definition to a different font face, Normal's face does not change with it.  To set Normal so that it follows changes in Body:

```<code>ActiveDocument.Styles("Normal").Font.Name = "+Body"
</code>```

(Similar for "+Headings".)
Normal's .Font.Name will still be a particular font name, like "Calibri". The setting that governs the link to +Body must be somewhere else...  I don't know how to test whether Normal is set to "Calibri" via a static font, via +Body that happens also to be "Calibri".

Body:
I'm writing a script to modify styles in a Word document. for each style I want to set the font to either the default 'Body' or 'Headings' style as determined by the document theme.

It's easy to set a style to a specific font:

# Powershell
$word = New-Object -ComObject Word.Application
$word.Documents.Add()
$doc = $word.Documents | Select-Object -first 1

$doc.Styles["Normal"].Font.Name = "Calibri"

How do I set the style to either the Body or Headings font?

Body:
Since .Minorfont(...).Name is just a string, the cited code changes Normal style to whatever the Body theme font face is currently.  But if you then change the Body theme font definition to a different font face, Normal's face does not change with it.  To set Normal so that it follows changes in Body:

ActiveDocument.Styles("Normal").Font.Name = "+Body"

(Similar for "+Headings".)
Normal's .Font.Name will still be a particular font name, like "Calibri". The setting that governs the link to +Body must be somewhere else...  I don't know how to test whether Normal is set to "Calibri" via a static font, via +Body that happens also to be "Calibri".


问:
Why did an empty query-set appeared in my Django program?
```<code>def Cart(request):
    if request.user.is_authenticated:
         customer=request.user.customer
         order,created=Order.objects.get_or_create(customer=customer,complete=True)
         items=order.orderitem_set.all()
         print(items)
    else:
        items=[]

    context={"items":items}
    return render(request,'store/Cart.html',context)
</code>```

<p>i'm trying to show some orderitems in the Cart template but nothing appears so i tried to
print the items and  i get a an    despite in the admin pannel i assisgned in an order some orderitems </p>

答:
try  this </p>

```<code>def Cart(request):
    if request.user.is_authenticated:
         customer=request.user.customer
         order=Order.objects.get_or_create(customer__user=customer,complete=True)
         items=order.orderitem_set.all()
         print(items)
    else:
        items=[]

    context={"items":items}
    return render(request,'store/Cart.html',context)
</code>```

Body:
def Cart(request):
    if request.user.is_authenticated:
         customer=request.user.customer
         order,created=Order.objects.get_or_create(customer=customer,complete=True)
         items=order.orderitem_set.all()
         print(items)
    else:
        items=[]

    context={"items":items}
    return render(request,'store/Cart.html',context)

i'm trying to show some orderitems in the Cart template but nothing appears so i tried to
print the items and  i get a an    despite in the admin pannel i assisgned in an order some orderitems

Body:
try  this

def Cart(request):
    if request.user.is_authenticated:
         customer=request.user.customer
         order=Order.objects.get_or_create(customer__user=customer,complete=True)
         items=order.orderitem_set.all()
         print(items)
    else:
        items=[]

    context={"items":items}
    return render(request,'store/Cart.html',context)


问:
Load content Ajax without lost the last content
I use ajax for load content without refresh , but if i go to another page and then i come, i lose the last content i have, and i want to save this information.

Now i have this

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

    $(document).ready(function() {
        var trigger =$('#nav ul li a'),
            container=$('#content');

        trigger.on('click', function() {
            var $this=$(this)
                    target=$this.data('target');
            container.load(target + '.php');
                lastTarget=target;
            return false;
            });
 });
  </script>

<nav id="nav" class="menuNav">
        <div class="logo"> <a href="index.php"> <img width="100px" src="images/logo.png"> </a> </div>
        <ul class="nav-links">
            <?php if(!isset($_SESSION["login"]) && !isset($_SESSION["loginEmpleado"])){ ?>
                <a href="formularioUsuario.php"><li class="nav">  Registrate </li></a>
                <a href="login.php"><li class="nav"> Iniciar Sesion </li></a>
            <?php } else{ ?>
                <li class="navL"><a href="#" data-target="consulta_inmuebles"> Inmuebles </a></li>
                <?php if(isset($_SESSION["loginEmpleado"])){ ?>
                    <li class="navL"><a href="#" data-target="consulta_demandas"> Demandas </a></li>
                    <li class="navL"><a href="#" data-target="consulta_contratos"> Contratos </a></li>
                <?php } if(isset($_SESSION["login"])) {  ?>
                <li class="navL"><a href="#" data-target="usuario"> Usuario </a></li>
                <?php } ?>
                <a href="desconectar.php"><li class="navL"> Cerrar Sesion</li> </a>
            <?php } ?>
        </ul>
    </nav>

<div id="content">
    <div class="bloqueI">
        <h2> Descripcion: </h2>
        <p> Aquí se mostraria informacion general sobre la empresa, asi como los inmuebles existentes. </p>
    </div>
</div>
</code>```

答:
What you need is to use ajax navigation to your entire page OR registering the content ID of what was already loaded by the user and then, make this content be loaded by default at main page.

Example(you have to change it according your context):

Page that gets content by ajax

```<code><?php
session_start();
if(!isset($_SESSION['loaded']))
   $_SESSION['loaded']=array();

loading_content(){

  // loads demands, contracts etc
  if(!in_array($database['demand_id'],$_SESSION['loaded_demands']);
     $_SESSION['loaded_demands'][]=$database['demand_id']; //store on session if it isn't there already
}
?>
</code>```

Your main page

```<code><?php
session_start();
if(isset($_SESSION['loaded_demands']) && sizeof($_SESSION['loaded_demands'])>0){
    $data = your_database_function("SELECT * FROM table_demands WHERE demand_id IN (".implode(',',$_SESSION['loaded_demands']).")");

    while($result = $data)
      echo 'Data stored => '.$result['column_name'];
}
?>
</code>```

When you doesn't need that "history" anymore, you only need to call unset($_SESSION['loaded_demand']).

Body:
I use ajax for load content without refresh , but if i go to another page and then i come, i lose the last content i have, and i want to save this information.

Now i have this

            <?php if(!isset($_SESSION["login"]) && !isset($_SESSION["loginEmpleado"])){ ?>

  Registrate

 Iniciar Sesion

            <?php } else{ ?>

 Inmuebles

                <?php if(isset($_SESSION["loginEmpleado"])){ ?>

 Demandas

 Contratos

                <?php } if(isset($_SESSION["login"])) {  ?>

 Usuario

                <?php } ?>

 Cerrar Sesion

            <?php } ?>

 Descripcion:

 Aquí se mostraria informacion general sobre la empresa, asi como los inmuebles existentes.

Body:
What you need is to use ajax navigation to your entire page OR registering the content ID of what was already loaded by the user and then, make this content be loaded by default at main page.

Example(you have to change it according your context):

Page that gets content by ajax

<?php
session_start();
if(!isset($_SESSION['loaded']))
   $_SESSION['loaded']=array();

loading_content(){

  // loads demands, contracts etc
  if(!in_array($database['demand_id'],$_SESSION['loaded_demands']);
     $_SESSION['loaded_demands'][]=$database['demand_id']; //store on session if it isn't there already
}
?>

Your main page

<?php
session_start();
if(isset($_SESSION['loaded_demands']) && sizeof($_SESSION['loaded_demands'])>0){
    $data = your_database_function("SELECT * FROM table_demands WHERE demand_id IN (".implode(',',$_SESSION['loaded_demands']).")");

    while($result = $data)
      echo 'Data stored => '.$result['column_name'];
}
?>

When you doesn't need that "history" anymore, you only need to call unset($_SESSION['loaded_demand']).


问:
How to upload contacts CSV file to my Gmail account?
Just wondering whether it' s possible to upload a CSV file with contacts information in it to my Gmail account?

I already looked at the Google Data API. it only allows you to add one at a time. Is there a bulk import ?

答:
My mistake, I found a method called Batch inside ContactsRequest class

```<code>               newContact.Title = name;
               newContact.Name.FullName = name;

               EMail primaryEmail = new EMail(email);
               primaryEmail.Primary = true;
               primaryEmail.Rel = ContactsRelationships.IsWork;
               newContact.Emails.Add(primaryEmail);

               newContact.BatchData = new GDataBatchEntryData();
               newContact.BatchData.Id = i.ToString();
               newContact.BatchData.Type = GDataBatchOperationType.insert;
               i ++;
               list.Add(newContact);
</code>```

And then

```<code>           cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.insert);
</code>```

Body:
My mistake, I found a method called Batch inside ContactsRequest class

               newContact.Title = name;
               newContact.Name.FullName = name;

               EMail primaryEmail = new EMail(email);
               primaryEmail.Primary = true;
               primaryEmail.Rel = ContactsRelationships.IsWork;
               newContact.Emails.Add(primaryEmail);

               newContact.BatchData = new GDataBatchEntryData();
               newContact.BatchData.Id = i.ToString();
               newContact.BatchData.Type = GDataBatchOperationType.insert;
               i ++;
               list.Add(newContact);

And then

           cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.insert);


问:
How to get distinct combinations of two fields from a collection when one of the fields is in an array of subdocuments
From a collection consisting of documents representing products similar to the following:

```<code>[
  {
    code: "0WE3A5CMY",
    name: "lorem",
    category: "voluptas",
    variants: [
      {
        color: "PapayaWhip",
        stock: 17,
        barcode: 4937310396997
      },
      {
        color: "RoyalBlue",
        stock: 13,
        barcode: 9787252504890
      },
      {
        color: "DodgerBlue",
        stock: 110,
        barcode: 97194456959791
      }
    ]
  },
  {
    code: "0WE3A5CMX",
    name: "ipsum",
    category: "temporibus",
    variants: [
      {
        color: "RoyalBlue",
        stock: 113,
        barcode: 23425202111840
      },
      {
        color: "DodgerBlue",
        stock: 10,
        barcode: 2342520211841
      }
    ]
  },
  {
    code: "0WE3A5CMZ",
    name: "dolor",
    category: "temporibus",
    variants: [
      {
        color: "MaroonRed",
        stock: 17,
        barcode: 3376911253701
      },
      {
        color: "RoyalBlue",
        stock: 12,
        barcode: 3376911253702
      },
      {
        color: "DodgerBlue",
        stock: 4,
        barcode: 3376911253703
      }
    ]
  }
]
</code>```

I would like to retrieve distinct combinations of variants.color and category. So the result should be:

```<code>[
    {
        category: 'voluptas',
        color: 'PapayaWhip',
    },
    {
        category: 'voluptas',
        color: 'RoyalBlue',
    },
    {
        category: 'voluptas',
        color: 'DodgerBlue',
    },
    {
        category: 'temporibus',
        color: 'RoyalBlue',
    },
    {
        category: 'temporibus',
        color: 'DodgerBlue',
    }
]
</code>```

Based on some cursory research I think I will have to use an aggregate but I've never worked with those and could use some help. I've tried the solution at How to efficiently perform "distinct" with multiple keys?
I've tried the method mentioned by jcarter in the comments but it doesn't solve my problem. If I do:

db.products.aggregate([
  {
    $group: {
      _id: {
        "category": "$category",
        "color": "$variants.color"
      }
    }
  }
])
```

<p>I get the result:</p>

```[
  {
    "_id": {
      "category": "temporibus",
      "color": [
        "MaroonRed",
        "RoyalBlue",
        "DodgerBlue"
      ]
    }
  },
  {
    "_id": {
      "category": "temporibus",
      "color": [
        "RoyalBlue",
        "DodgerBlue"
      ]
    }
  },
  {
    "_id": {
      "category": "voluptas",
      "color": [
        "PapayaWhip",
        "RoyalBlue",
        "DodgerBlue"
      ]
    }
  }
]
```

Which isn't what I need.

答:
Since variants is an array you need to unwind it & group on two fields to get unique docs based on category + 'variants.color' combo.

As group stage results something like :

```<code>[
  {
    "_id": {
      "category": "voluptas",
      "color": "DodgerBlue"
    }
  },
  {
    "_id": {
      "category": "voluptas",
      "color": "PapayaWhip"
    }
  }
]
</code>```

then using $replaceRoot stage you can make _id object field as root for each document to get desired result.

Query :

```<code>db.collection.aggregate([
    {
      $unwind: "$variants"
    },
    {
      $group: { _id: { "category": "$category", "color": "$variants.color" } }
    },
    {
      $replaceRoot: { newRoot: "$_id" }
    }
  ])
</code>```

Test : mongoplayground

Body:
From a collection consisting of documents representing products similar to the following:

[
  {
    code: "0WE3A5CMY",
    name: "lorem",
    category: "voluptas",
    variants: [
      {
        color: "PapayaWhip",
        stock: 17,
        barcode: 4937310396997
      },
      {
        color: "RoyalBlue",
        stock: 13,
        barcode: 9787252504890
      },
      {
        color: "DodgerBlue",
        stock: 110,
        barcode: 97194456959791
      }
    ]
  },
  {
    code: "0WE3A5CMX",
    name: "ipsum",
    category: "temporibus",
    variants: [
      {
        color: "RoyalBlue",
        stock: 113,
        barcode: 23425202111840
      },
      {
        color: "DodgerBlue",
        stock: 10,
        barcode: 2342520211841
      }
    ]
  },
  {
    code: "0WE3A5CMZ",
    name: "dolor",
    category: "temporibus",
    variants: [
      {
        color: "MaroonRed",
        stock: 17,
        barcode: 3376911253701
      },
      {
        color: "RoyalBlue",
        stock: 12,
        barcode: 3376911253702
      },
      {
        color: "DodgerBlue",
        stock: 4,
        barcode: 3376911253703
      }
    ]
  }
]

I would like to retrieve distinct combinations of variants.color and category. So the result should be:

[
    {
        category: 'voluptas',
        color: 'PapayaWhip',
    },
    {
        category: 'voluptas',
        color: 'RoyalBlue',
    },
    {
        category: 'voluptas',
        color: 'DodgerBlue',
    },
    {
        category: 'temporibus',
        color: 'RoyalBlue',
    },
    {
        category: 'temporibus',
        color: 'DodgerBlue',
    }
]

Based on some cursory research I think I will have to use an aggregate but I've never worked with those and could use some help. I've tried the solution at How to efficiently perform "distinct" with multiple keys?
I've tried the method mentioned by jcarter in the comments but it doesn't solve my problem. If I do:

db.products.aggregate([
  {
    $group: {
      _id: {
        "category": "$category",
        "color": "$variants.color"
      }
    }
  }
])

I get the result:

[
  {
    "_id": {
      "category": "temporibus",
      "color": [
        "MaroonRed",
        "RoyalBlue",
        "DodgerBlue"
      ]
    }
  },
  {
    "_id": {
      "category": "temporibus",
      "color": [
        "RoyalBlue",
        "DodgerBlue"
      ]
    }
  },
  {
    "_id": {
      "category": "voluptas",
      "color": [
        "PapayaWhip",
        "RoyalBlue",
        "DodgerBlue"
      ]
    }
  }
]

Which isn't what I need.

Body:
Since variants is an array you need to unwind it & group on two fields to get unique docs based on category + 'variants.color' combo.

As group stage results something like :

[
  {
    "_id": {
      "category": "voluptas",
      "color": "DodgerBlue"
    }
  },
  {
    "_id": {
      "category": "voluptas",
      "color": "PapayaWhip"
    }
  }
]

then using $replaceRoot stage you can make _id object field as root for each document to get desired result.

Query :

db.collection.aggregate([
    {
      $unwind: "$variants"
    },
    {
      $group: { _id: { "category": "$category", "color": "$variants.color" } }
    },
    {
      $replaceRoot: { newRoot: "$_id" }
    }
  ])

Test : mongoplayground