问:
Digital filter algorithm
I just found a fir algorithm on wikipedia

http://en.wikipedia.org/wiki/Digital_filter

```<code>// if the size of NB_COEF = 2^n use a bit mask instead of the modulo (%)
// %=NB_COEF => &=(NB_COEF-1)
// pipe is a circular buffer

#define NB_COEF 16  // numbers of coefficients of the filter
double x_buffer[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
double coef[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ptr_x_buffer=0;

double FiltreFIR(double x)
// x: Signal d'entrée
// y: Signal de sortie
{
  int n, y=0;
  x_buffer[ptr_x_buffer++] = x;
  ptr_x_buffer %= NB_COEF;

  for( n = (NB_COEF-1) ; n >= 0 ; n-- )
  {
    y += coef[n] * x_buffer[ptr_x_buffer++];
    ptr_x_buffer %= NB_COEF;
  }
  return(y);
}
</code>```

-Can anybody tell me why do we need constantly to do this expression

```<code>ptr_x_buffer%= NB_COEFF.
</code>```

Because for me it would mean the variable ptr_x_buffer always take the value 0 ?!
And it seems to me far from logic?!

And also can somebody explain to me the first comment about bit masking and modulo.

thank you in advance
:)

答:
It is used to ensure that the ptr_x_buffer is always a valid index inside the x_buffer array which is used as a cyclic buffer. Whenever ptr_x_buffer would overflow the array size it gets reset to 0.

ptr_x_buffer gets incremented with each invocation of the function and on each iteration of the loop in x_buffer[ptr_x_buffer++].

You could also replace the lines ptr_x_buffer %= NB_COEF; with this:

```<code> if( ptr_x_buffer == NB_COEF )
     ptr_x_buffer = 0;
</code>```

Or if you are sure that NB_COEF is a power of 2 you could mask them with a bitmask if as is stated in the comment already: ptr_x_buffer &= NB_COEF-1;.

Title: Digital filter algorithm

Body:
I just found a fir algorithm on wikipedia

http://en.wikipedia.org/wiki/Digital_filter

// if the size of NB_COEF = 2^n use a bit mask instead of the modulo (%)
// %=NB_COEF => &=(NB_COEF-1)
// pipe is a circular buffer

#define NB_COEF 16  // numbers of coefficients of the filter
double x_buffer[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
double coef[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ptr_x_buffer=0;

double FiltreFIR(double x)
// x: Signal d'entrée
// y: Signal de sortie
{
  int n, y=0;
  x_buffer[ptr_x_buffer++] = x;
  ptr_x_buffer %= NB_COEF;

  for( n = (NB_COEF-1) ; n >= 0 ; n-- )
  {
    y += coef[n] * x_buffer[ptr_x_buffer++];
    ptr_x_buffer %= NB_COEF;
  }
  return(y);
}

-Can anybody tell me why do we need constantly to do this expression

ptr_x_buffer%= NB_COEFF.

Because for me it would mean the variable ptr_x_buffer always take the value 0 ?!
And it seems to me far from logic?!

And also can somebody explain to me the first comment about bit masking and modulo.

thank you in advance
:)

Body:
It is used to ensure that the ptr_x_buffer is always a valid index inside the x_buffer array which is used as a cyclic buffer. Whenever ptr_x_buffer would overflow the array size it gets reset to 0.

ptr_x_buffer gets incremented with each invocation of the function and on each iteration of the loop in x_buffer[ptr_x_buffer++].

You could also replace the lines ptr_x_buffer %= NB_COEF; with this:

 if( ptr_x_buffer == NB_COEF )
     ptr_x_buffer = 0;

Or if you are sure that NB_COEF is a power of 2 you could mask them with a bitmask if as is stated in the comment already: ptr_x_buffer &= NB_COEF-1;.


来源: stackexchange

问:
How to remove all duplicates from a array that was created with dynamic allocation?
I wrote a program that dynamically allocates for a new array that contains elements from two other arrays.
However the program dose not completely remove all duplicates from the new array. Instead of outputting 1 2 3 4 5, instead it outputs 1 2 3 3. I tried to fix the problem by first sorting the array, however that did not help at all.

```<code>int koko(int va, int vb, int *kar, int *a, int *b) {
    int *c;
    int kar2 = (*kar);
    c = (int)malloc(kar2 * sizeof(int));
    int i, j, u, temp;

    //takes all elements from the first array
    for (i = 0; i < va; i++) {
        c[i] = a[i];
    }

    //takes all elements from the second array
    for (i = 0, j = va; j < kar2 && i < vb; i++, j++) {
        c[j] = b[i];
    }

    //sorts the array
    for (i = 0; i < kar2; i++) {
        for (j = i + 1; j < kar2; j++) {
            if (c[i] > c[j]) {
                temp = c[i];
                c[i] = c[j];
                c[j] = temp;
            }
        }
    }

    //removes all duplicates(or it should at least)
    for (i = 0; i < kar2; i++) {
        for (j = i; j < kar2; j++) {
            if (c[j] == c[i]) {
                for (u = j; u < kar2; u++) {
                    c[u] = c[u + 1];
                }

                kar2--;
            }
            else {
                j++;
            }
        }
    }

    c = (int)realloc(c, sizeof(int) * kar2);
    (*kar) = kar2;
    return c;
}

int main() {
    int *s;
    int a[] = {1, 2, 3, 3, 3, 3, 5};
    int b[] = {1, 2, 2, 2, 3, 4};
    int va = sizeof(a) / sizeof a[0];
    int vb = sizeof(b) / sizeof b[0];
    int kar = va + vb;
    s = koko(va, vb, &kar, a, b);

    for (int q = 0; q < kar - 1; q++) {
        printf("%d\t", s[q]);
    }

    free(s);
}
</code>```

This my code that I wrote. Dose anyone by any chance see where the problem is?

答:
```<code>    // there were a few off-by-1 errors:
    // loops were accessing 1 element beyond the array (fixed with kar2 - 1)
    // after moving array elements, the current element wasn't being
    // re-tested with its new neighbor (fixed with i--)

    // remove duplicates
    for (i = 0; i < (kar2 - 1); i++) {
        // different, move onto the next pair
        if (c[i] != c[i + 1])
            continue;

        // duplicate, move array elements back by 1
        for (j = i + 1; j < (kar2 - 1); j++)
            c[j] = c[j + 1];

        // account for duplicate
        kar2--;

        // after the second loop, new next element could be another duplicate;
        // need to re-test the current element with the new next element
        i--;
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote a program that dynamically allocates for a new array that contains elements from two other arrays.
However the program dose not completely remove all duplicates from the new array. Instead of outputting 1 2 3 4 5, instead it outputs 1 2 3 3. I tried to fix the problem by first sorting the array, however that did not help at all.

int koko(int va, int vb, int *kar, int *a, int *b) {
    int *c;
    int kar2 = (*kar);
    c = (int)malloc(kar2 * sizeof(int));
    int i, j, u, temp;

    //takes all elements from the first array
    for (i = 0; i < va; i++) {
        c[i] = a[i];
    }

    //takes all elements from the second array
    for (i = 0, j = va; j < kar2 && i < vb; i++, j++) {
        c[j] = b[i];
    }

    //sorts the array
    for (i = 0; i < kar2; i++) {
        for (j = i + 1; j < kar2; j++) {
            if (c[i] > c[j]) {
                temp = c[i];
                c[i] = c[j];
                c[j] = temp;
            }
        }
    }

    //removes all duplicates(or it should at least)
    for (i = 0; i < kar2; i++) {
        for (j = i; j < kar2; j++) {
            if (c[j] == c[i]) {
                for (u = j; u < kar2; u++) {
                    c[u] = c[u + 1];
                }

                kar2--;
            }
            else {
                j++;
            }
        }
    }

    c = (int)realloc(c, sizeof(int) * kar2);
    (*kar) = kar2;
    return c;
}

int main() {
    int *s;
    int a[] = {1, 2, 3, 3, 3, 3, 5};
    int b[] = {1, 2, 2, 2, 3, 4};
    int va = sizeof(a) / sizeof a[0];
    int vb = sizeof(b) / sizeof b[0];
    int kar = va + vb;
    s = koko(va, vb, &kar, a, b);

    for (int q = 0; q < kar - 1; q++) {
        printf("%d\t", s[q]);
    }

    free(s);
}

This my code that I wrote. Dose anyone by any chance see where the problem is?


问:
Postgress INET to Snowflake Compatible
I need help in migrating a postgres function to snowflake function.

Currently, i have following function that takes an ip_address and returns the starting range of ip_address:

```<code>...
begin
  if (p_ip_address is not null) then
    return p_ip_address::inet - '0.0.0.0';
  else
    return null;
  end if;
end
...
</code>```

I know we have PARSE_IP in snowflake that give JSON file but i need just one piece of this json (ipv4_range_start)

For Example:

```<code>Input  = 192.168.242.188
Output = 3232297472
</code>```

答:
If you only want peice of information, select it.

```<code>select parse_ip('127.0.0.0/24','INET') as a
    ,a:ipv4_range_end;
</code>```

gives:

```<code>A   A:IPV4_RANGE_END
{    "family": 4,    "host": "127.0.0.0",    "ip_fields": [      2130706432,      0,      0,      0    ],    "ip_type": "inet",    "ipv4": 2130706432,    "ipv4_range_end": 2130706687,    "ipv4_range_start": 2130706432,    "netmask_prefix_length": 24,    "snowflake$type": "ip_address"  } 2130706687
</code>```

Title: Postgress INET to Snowflake Compatible

Body:
I need help in migrating a postgres function to snowflake function.

Currently, i have following function that takes an ip_address and returns the starting range of ip_address:

...
begin
  if (p_ip_address is not null) then
    return p_ip_address::inet - '0.0.0.0';
  else
    return null;
  end if;
end
...

I know we have PARSE_IP in snowflake that give JSON file but i need just one piece of this json (ipv4_range_start)

For Example:

Input  = 192.168.242.188
Output = 3232297472

Body:
If you only want peice of information, select it.

select parse_ip('127.0.0.0/24','INET') as a
    ,a:ipv4_range_end;

gives:

A   A:IPV4_RANGE_END
{    "family": 4,    "host": "127.0.0.0",    "ip_fields": [      2130706432,      0,      0,      0    ],    "ip_type": "inet",    "ipv4": 2130706432,    "ipv4_range_end": 2130706687,    "ipv4_range_start": 2130706432,    "netmask_prefix_length": 24,    "snowflake$type": "ip_address"  } 2130706687


问:
Spring Boot runnable Jar file for production?
Is spring boot runnable jar file meant for production environments with any optimizations needed for production or it is meant for testing/prototyping and we should generate and deploy WAR files on app servers in the prod machines?</p>

答:
You can use the .jar for production too. Jars are easy to create. Spring boot jar can simply be managed automatically by the production server, i.e. restart the jar and etc.

It also has embedded Tomcat and the Tomcat configuration can be modified and optimized using the .properties file or inside Java if you need that.

Generally, there are almost no reason to use .war over .jar, but it is up to you what you prefer.


问:
Ionic 4 AdMob-Plus Ads
Has anyone got AdMob-Plus to work successfully with Ionic 4? Using the code below nothing shows up and the promise terminates with error without a message.

```<code>import { AdMob } from '@ionic-native/admob-plus/ngx';
constructor(
adMob: AdMob,
platform: Platform){
  this.platform.ready()
  this.adMob.setDevMode(true);
  this.adMob.banner.show({
      id: {
        android: 'test',
        ios: 'test',
      }
  })
}
</code>```

I originally went with AdMob Free but didn't want to manually import the iOS SDK for AdMob. The current SDK version throws error ITMS-90809 when submitting to iOS app store.

***EDIT***

The comment below by Naga is the solution

答:
some of native plugins will work just on android and ios and this is one of them.
this plugin will not work on pc even with build it on the browser.
so you have to test it on a native device or an emulator.</p>

Title: Ionic 4 AdMob-Plus Ads

Body:
Has anyone got AdMob-Plus to work successfully with Ionic 4? Using the code below nothing shows up and the promise terminates with error without a message.

import { AdMob } from '@ionic-native/admob-plus/ngx';
constructor(
adMob: AdMob,
platform: Platform){
  this.platform.ready()
  this.adMob.setDevMode(true);
  this.adMob.banner.show({
      id: {
        android: 'test',
        ios: 'test',
      }
  })
}

I originally went with AdMob Free but didn't want to manually import the iOS SDK for AdMob. The current SDK version throws error ITMS-90809 when submitting to iOS app store.

***EDIT***

The comment below by Naga is the solution


问:
From n x k DataFrame, generate a (n over 2) x 2k DataFrame of all pairs of rows
Given a pandas DataFrame x of dimensions n x k, how can we efficiently generate a DataFrame y of dimensions (n over 2) x 2k, whose rows are all possible combinations of rows pairs of rows from x?
For example, if x is

```<code>[[1 11],
 [2,22],
 [3,33],
 [4,44]]
</code>```

then y should be

```<code>[[1,11,2,22],
 [1,11,3,33],
 [1,11,4,44],
 [2,22,3,33],
 [2,22,4,44],
 [3,33,4,44]]
</code>```

答:
My attempt

```<code>l=[[1,11], [2,22], [3,33], [4,44]]
</code>```

Full list

```<code>#lst=[x+y for x in [z for z in l[:3]] for y in [z for z in l[1:]] if x!=y]#Use + in list comprehension
</code>```

If you wanted to eliminate [3, 33, 2, 22]. initialize a  new list and append x+y only if y+x doesn't exist.

```<code>k=[]
lst=[k.append(x+y) for x in [z for z in l[:3]] for y in [z for z in l[1:]] if x!=y if y+x not in k]
print(k)
</code>```

Body:
Given a pandas DataFrame x of dimensions n x k, how can we efficiently generate a DataFrame y of dimensions (n over 2) x 2k, whose rows are all possible combinations of rows pairs of rows from x?
For example, if x is

[[1 11],
 [2,22],
 [3,33],
 [4,44]]

then y should be

[[1,11,2,22],
 [1,11,3,33],
 [1,11,4,44],
 [2,22,3,33],
 [2,22,4,44],
 [3,33,4,44]]

Body:
My attempt

l=[[1,11], [2,22], [3,33], [4,44]]

Full list

#lst=[x+y for x in [z for z in l[:3]] for y in [z for z in l[1:]] if x!=y]#Use + in list comprehension

If you wanted to eliminate [3, 33, 2, 22]. initialize a  new list and append x+y only if y+x doesn't exist.

k=[]
lst=[k.append(x+y) for x in [z for z in l[:3]] for y in [z for z in l[1:]] if x!=y if y+x not in k]
print(k)


问:
Calculate flag based on value of two other flags
I have three fields, client_id, flag_1 (0 or 1), and flag_2 (0 or 1). For every client, I need to calculate flag_3  which should equal 1 if both flag_1 == 1 and flag_2 ==1, otherwise 0.

I have tried:

```<code>df['flag_3'] = [1 if x==1 and y==1 else 0 for x in df['flag_1'] and y in df['flag_2']]

df['flag_3'] = np.where(df['flag_1'] == 1 and df['flag_2'] == 1, 1, 0)
</code>```

...getting errors like "The truth value of a Series is ambiguous."

答:
You are using boolean indexing to select rows and the index should be combined using binary "&"</p>

```<code>df['flag_3'] = np.where((df['flag_1'] == 1) & (df['flag_2'] == 1), 1, 0)
</code>```

Body:
I have three fields, client_id, flag_1 (0 or 1), and flag_2 (0 or 1). For every client, I need to calculate flag_3  which should equal 1 if both flag_1 == 1 and flag_2 ==1, otherwise 0.

I have tried:

df['flag_3'] = [1 if x==1 and y==1 else 0 for x in df['flag_1'] and y in df['flag_2']]

df['flag_3'] = np.where(df['flag_1'] == 1 and df['flag_2'] == 1, 1, 0)

...getting errors like "The truth value of a Series is ambiguous."

Body:
You are using boolean indexing to select rows and the index should be combined using binary "&"

df['flag_3'] = np.where((df['flag_1'] == 1) & (df['flag_2'] == 1), 1, 0)


问:
Why does random number generator not show on html page?
I am trying to get a random number of customers to "have gone on the website today". Why does the number not show on the page. I am sorry if this is something obvious but I am very new.

var customerNumber = document.getElementById("customer-number")
customerNumber.textcontent = randomCustomerNumber()

function randomCustomerNumber(){
    var i = Math.floor(Math.random() * 36)
    return(i)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="customers-today">
    <h4>You are customer number <span id="customer-number"></span> today.</h4>
</div></code>```

答:
element.textcontent => element.textContent

Also you should prob change return(i) to return i;, both work but the first one makes it seem like return is a function.

Body:
I am trying to get a random number of customers to "have gone on the website today". Why does the number not show on the page. I am sorry if this is something obvious but I am very new.

var customerNumber = document.getElementById("customer-number")
customerNumber.textcontent = randomCustomerNumber()

function randomCustomerNumber(){
    var i = Math.floor(Math.random() * 36)
    return(i)
}

You are customer number  today.


问:
Inverted mask swiftui with system image
I am trying to cut out a sf symbol from a circle shape in swiftUI.

I currently have the following code:

```<code>Circle()
   .fill(Color.white)
   .frame(width: 50, height: 50)
   .mask(
       Image(systemName: "play.fill")
           .font(.system(size: 24))
           .foregroundColor(Color.black)
           .frame(width: 50, height: 50)
   )
</code>```

Which generates:

However, what I want is to invert the effect of the mask: The symbol is cut out of the circle as in the image below:

Note that the actual background is not red as in the image but will be a user uploaded image, so setting the symbol foregroundColor to red is not possible.

Is there any way to invert the mask of the symbol/image such that the circle has a hole in it with the shape of the image?

答:
This answer by Vlad Lego works when applied here.

You create your mask using .black for the parts you want cut out, and .white for the parts you want preserved.

(assuming the background is red, this is what it would look like)

Rectangle()
  .foregroundColor(Color.white)
  .mask(
    ZStack {
      Circle()
        .fill(Color.white)
        .frame(width: 50, height: 50)
      Image(systemName: "play.fill")
        .font(.system(size: 24))
        .foregroundColor(Color.black)
    }
      .compositingGroup()
      .luminanceToAlpha()
  )
```

Title: Inverted mask swiftui with system image

Body:
I am trying to cut out a sf symbol from a circle shape in swiftUI.

I currently have the following code:

Circle()
   .fill(Color.white)
   .frame(width: 50, height: 50)
   .mask(
       Image(systemName: "play.fill")
           .font(.system(size: 24))
           .foregroundColor(Color.black)
           .frame(width: 50, height: 50)
   )

Which generates:

However, what I want is to invert the effect of the mask: The symbol is cut out of the circle as in the image below:

Note that the actual background is not red as in the image but will be a user uploaded image, so setting the symbol foregroundColor to red is not possible.

Is there any way to invert the mask of the symbol/image such that the circle has a hole in it with the shape of the image?


问:
Typescript export default: React.FunctionComponent
How would I go about this in typescript. I know I can do it with giving it a name but thats not what I'm asking. I'm asking how can I still just use default.

```<code>interface IProps {
  name: string,
  tag: string,
}

export default ({name, tag}: IProps) => {
 ..... my code
});
</code>```

Yes I know about this.

```<code>const MyComponent: React.FunctionComponent = () => {
...
export default MyComponent;
</code>```

答:
Um, exactly like you have it, except for the trailing ) syntax error

import React from "react"

interface IProps {
  name: string,
  tag: string,
}

export default ({name, tag}: IProps): JSX.Element => {
  return
hello { name }, some { tag }

} // <- no trailing `)`
```

<p>Or -</p>

<pre class="lang-js prettyprint-override"><code>import React from "react"

interface IProps {
  name: string,
  tag: string,
}

export default ({name, tag}: IProps): JSX.Element =>
  <p>hello { name }, some { tag }</p>
</code>```

TypeScript Playground Demo

That said, a named function is much better, especially for debugging purposes.

Body:
How would I go about this in typescript. I know I can do it with giving it a name but thats not what I'm asking. I'm asking how can I still just use default.

interface IProps {
  name: string,
  tag: string,
}

export default ({name, tag}: IProps) => {
 ..... my code
});

Yes I know about this.

const MyComponent: React.FunctionComponent = () => {
...
export default MyComponent;

Body:
Um, exactly like you have it, except for the trailing ) syntax error

import React from "react"

interface IProps {
  name: string,
  tag: string,
}

export default ({name, tag}: IProps): JSX.Element => {
  return <p>hello { name }, some { tag }</p>
} // <- no trailing `)`

Or -

import React from "react"

interface IProps {
  name: string,
  tag: string,
}

export default ({name, tag}: IProps): JSX.Element =>
  <p>hello { name }, some { tag }</p>

TypeScript Playground Demo

That said, a named function is much better, especially for debugging purposes.


问:
RequiredAttribute not preventing Empty string entries
I want to catch blank entries on a property I have in my model. I added the Required DataAnnotation above the property hoping that it would catch this when I try to update the value. However when I update it, it just sets the property to null and continues without any issues.
I also tried [RegularExpression] and [StringLength] validation attributes but these are also just bypassed.

The Model:

```<code>public class CaseDescriptionModel
{
    public int CaseId { get; set; }

    [Display(Name = "Description:")]
    [Required]
    public string CaseDescription { get; set; }

    public CaseDescriptionModel() { }

    public CaseDescriptionModel(Case case)
    {
        if (case == null)
        {
            throw new ArgumentNullException("case");
        }

        CaseId = case.ID;
        CaseDescription = case.Description;
    }
}
</code>```

The View:

```<code>@model Models.CaseDescriptionModel
@{
    Layout = null;
}
<div>
    @Html.StandardForm(this, "", false, true, "UpdateDescription", "Case",
     @<div>
         @Html.HiddenFor(m => m.CaseId)

         <table class="full-width">
             <tbody>
                 <tr>
                     <td class="ColumnOneStyle">
                         @Html.LabelFor(m => m.CaseDescription)
                     </td>
                     <td class="ColumnTwoStyle" style="float:right;">
                         @Html.TextBoxFor(m => m.CaseDescription)
                     </td>
                 </tr>
             </tbody>
         </table>

         @Html.ValidationSummary(false, "", new { @class = "" })

         <table style="float: right;">
             <tr>
                 <td>
                     @item.Submit("SUBMIT")
                 </td>
                 <td>
                     @Html.ButtonLinkAction("btnCancel", "CANCEL", "Return to case", "Details", "Case", "btnSecondary", new { id = Model.CaseId })
                 </td>
             </tr>
         </table>
     </div>
     )
</div>
</code>```

The Controller Method

```<code>public ActionResult UpdateCase(CaseDescriptionModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var case= DAL.GetCase(model.CaseId);

            DAL.UpdateCaseDescription(model.CaseId, model.CaseDescription);

            return RedirectToAction("Details", new { id = model.CaseId });
        }
</code>```

答:
A little bit of context first: You need to manually check if the model state is valid. The model state will be validated against the requirements you have in the ViewModel, like the Required attribute.

To check if the model is valid you'll need to add the following lines in your controller method

```<code>public ActionResult UpdateCase(CaseDescriptionModel model)
{
    if (model == null)
    {
        throw new ArgumentNullException("model");
    }

    if(!ModelState.IsValid)
    {
        // maybe do some dropdown list loading if you have before the view
        return View();
    }

    var case = DAL.GetCase(model.CaseId);

    DAL.UpdateCaseDescription(model.CaseId, model.CaseDescription);

    return RedirectToAction("Details", new { id = model.CaseId });
}

</code>```

What will happen here, if the model is not valid, the ModelState will already be populated with the error messages of the incorrect fields. By returning the View, you will display the user the same view that they were previously on, and the ValidationSummary control that you already have will be populated with the errors from the model state validation.

Hope this helps.

Body:
I want to catch blank entries on a property I have in my model. I added the Required DataAnnotation above the property hoping that it would catch this when I try to update the value. However when I update it, it just sets the property to null and continues without any issues.
I also tried [RegularExpression] and [StringLength] validation attributes but these are also just bypassed.

The Model:

public class CaseDescriptionModel
{
    public int CaseId { get; set; }

    [Display(Name = "Description:")]
    [Required]
    public string CaseDescription { get; set; }

    public CaseDescriptionModel() { }

    public CaseDescriptionModel(Case case)
    {
        if (case == null)
        {
            throw new ArgumentNullException("case");
        }

        CaseId = case.ID;
        CaseDescription = case.Description;
    }
}

The View:

@model Models.CaseDescriptionModel
@{
    Layout = null;
}

    @Html.StandardForm(this, "", false, true, "UpdateDescription", "Case",
     @

         @Html.HiddenFor(m => m.CaseId)

                         @Html.LabelFor(m => m.CaseDescription)

                         @Html.TextBoxFor(m => m.CaseDescription)

         @Html.ValidationSummary(false, "", new { @class = "" })

                     @item.Submit("SUBMIT")

                     @Html.ButtonLinkAction("btnCancel", "CANCEL", "Return to case", "Details", "Case", "btnSecondary", new { id = Model.CaseId })

     )

The Controller Method

public ActionResult UpdateCase(CaseDescriptionModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var case= DAL.GetCase(model.CaseId);

            DAL.UpdateCaseDescription(model.CaseId, model.CaseDescription);

            return RedirectToAction("Details", new { id = model.CaseId });
        }

Body:
A little bit of context first: You need to manually check if the model state is valid. The model state will be validated against the requirements you have in the ViewModel, like the Required attribute.

To check if the model is valid you'll need to add the following lines in your controller method

public ActionResult UpdateCase(CaseDescriptionModel model)
{
    if (model == null)
    {
        throw new ArgumentNullException("model");
    }

    if(!ModelState.IsValid)
    {
        // maybe do some dropdown list loading if you have before the view
        return View();
    }

    var case = DAL.GetCase(model.CaseId);

    DAL.UpdateCaseDescription(model.CaseId, model.CaseDescription);

    return RedirectToAction("Details", new { id = model.CaseId });
}

What will happen here, if the model is not valid, the ModelState will already be populated with the error messages of the incorrect fields. By returning the View, you will display the user the same view that they were previously on, and the ValidationSummary control that you already have will be populated with the errors from the model state validation.

Hope this helps.


问:
how to find ODBC driver-specific arguments
Is there a way to programmatically discover the named arguments for ODBC connections?

For instance, using the "ODBC Driver 17 for SQL Server", the ODBC Data Source Administrator (in Windows) allows for authentication using a "Login ID" and "Password", yet when connecting programmatically, we need to use uid= and pwd=, respectively. These two configuration points are clearly listed in configuration documentation (e.g., https://db.rstudio.com/databases/microsoft-sql-server/), but there are several other configuration options that the driver supports that are less- or un-documented.

(For SQL Server, there are more docs, including https://learn.microsoft.com/en-us/sql/connect/odbc/windows/driver-aware-connection-pooling-in-the-odbc-driver-for-sql-server?view=sql-server-ver15, that lists several other arguments (though not their possible values). That works for this driver, though since this page has not been updated for Driver 17 we have to assume that all options are unchanged.)

There are programmatic ways to learn what drivers are available, and what pre-defined data sources are available:

odbc::odbcListDrivers()
#                             name        attribute value
# ...truncated...
# 33 ODBC Driver 17 for SQL Server       UsageCount     1
# 34 ODBC Driver 17 for SQL Server         APILevel     2
# 35 ODBC Driver 17 for SQL Server ConnectFunctions   YYY
# 36 ODBC Driver 17 for SQL Server        CPTimeout    60
# 37 ODBC Driver 17 for SQL Server    DriverODBCVer 03.80
# 38 ODBC Driver 17 for SQL Server        FileUsage     0
# 39 ODBC Driver 17 for SQL Server         SQLLevel     1

odbc::odbcListDataSources()
#                 name                   description
# 1             somedb ODBC Driver 17 for SQL Server
# 2 SQLite3 Datasource           SQLite3 ODBC Driver
```

<p>but nothing to discover connection <em>arguments</em>. Perhaps something akin to this non-existent function:</p>

<pre class="lang-r prettyprint-override"><code>discover_odbc_arguments("ODBC Driver 17 for SQL Server")
# [1] "Address"                "AnsiNPW"                "App"
# [4] "Database"               "Encrypt"                "PWD"
# [7] "Trusted_Connection"     "TrustServerCertificate" "UID"
</code>```

(I used SQL Server as an example here, but I'm interested in more general methods. And since I'm looking for programmatic mechanisms, I'd prefer to avoid suggestions to read the docs for each driver.)

(I am not opposed to non-R methods.)

Some non-R attempts that did not work. Using a mssql odbc driver library as an example with known parameter patterns.

$ strings /opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.2.1  \
  | egrep -i 'Trusted.Conn|AnsiDPW|TrustServer'
### <no output>
$ grep -rli 'Trusted.Conn|AnsiDPW|TrustServer' /opt/microsoft/msodbcsql17/
### <no output>
```

答: You need to somehow call SQLBrowseConnect function to get all available parameters of connection string for specific ODBC driver or DSN. Unfortunately, as I can see this call isn’t implemented in R ODBC packages. See documentation and example code at the link for more information.</p>

Body:
Is there a way to programmatically discover the named arguments for ODBC connections?

For instance, using the "ODBC Driver 17 for SQL Server", the ODBC Data Source Administrator (in Windows) allows for authentication using a "Login ID" and "Password", yet when connecting programmatically, we need to use uid= and pwd=, respectively. These two configuration points are clearly listed in configuration documentation (e.g., https://db.rstudio.com/databases/microsoft-sql-server/), but there are several other configuration options that the driver supports that are less- or un-documented.

(For SQL Server, there are more docs, including https://learn.microsoft.com/en-us/sql/connect/odbc/windows/driver-aware-connection-pooling-in-the-odbc-driver-for-sql-server?view=sql-server-ver15, that lists several other arguments (though not their possible values). That works for this driver, though since this page has not been updated for Driver 17 we have to assume that all options are unchanged.)

There are programmatic ways to learn what drivers are available, and what pre-defined data sources are available:

odbc::odbcListDrivers()
#                             name        attribute value
# ...truncated...
# 33 ODBC Driver 17 for SQL Server       UsageCount     1
# 34 ODBC Driver 17 for SQL Server         APILevel     2
# 35 ODBC Driver 17 for SQL Server ConnectFunctions   YYY
# 36 ODBC Driver 17 for SQL Server        CPTimeout    60
# 37 ODBC Driver 17 for SQL Server    DriverODBCVer 03.80
# 38 ODBC Driver 17 for SQL Server        FileUsage     0
# 39 ODBC Driver 17 for SQL Server         SQLLevel     1

odbc::odbcListDataSources()
#                 name                   description
# 1             somedb ODBC Driver 17 for SQL Server
# 2 SQLite3 Datasource           SQLite3 ODBC Driver

but nothing to discover connection arguments. Perhaps something akin to this non-existent function:

discover_odbc_arguments("ODBC Driver 17 for SQL Server")
# [1] "Address"                "AnsiNPW"                "App"
# [4] "Database"               "Encrypt"                "PWD"
# [7] "Trusted_Connection"     "TrustServerCertificate" "UID"

(I used SQL Server as an example here, but I'm interested in more general methods. And since I'm looking for programmatic mechanisms, I'd prefer to avoid suggestions to read the docs for each driver.)

(I am not opposed to non-R methods.)

Some non-R attempts that did not work. Using a mssql odbc driver library as an example with known parameter patterns.

$ strings /opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.2.1  \
  | egrep -i 'Trusted.Conn|AnsiDPW|TrustServer'
### <no output>
$ grep -rli 'Trusted.Conn|AnsiDPW|TrustServer' /opt/microsoft/msodbcsql17/
### <no output>


答:
The expression ptr_x_buffer%=NB_COEFF means that ptr_x_buffer is resetted modulo NB_COEFF. Therefore it is not "always 0" but the modulus with respect to division by 16. Therefore it is guaranteed that the array access x_buffer[ptr_x_buffer] always lies within the bounds 0..NB_COEFF-1.

For powers of 2 the modulo operation can be replaced by a bitwise and with a mask of 2^n-1 (or N-1) where n is the log2 of your modulus.

ContentLicense: CC BY-SA 3.0

Title: Digital filter algorithm

Body:
I just found a fir algorithm on wikipedia

http://en.wikipedia.org/wiki/Digital_filter

// if the size of NB_COEF = 2^n use a bit mask instead of the modulo (%)
// %=NB_COEF => &=(NB_COEF-1)
// pipe is a circular buffer

#define NB_COEF 16  // numbers of coefficients of the filter
double x_buffer[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
double coef[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ptr_x_buffer=0;

double FiltreFIR(double x)
// x: Signal d'entrée
// y: Signal de sortie
{
  int n, y=0;
  x_buffer[ptr_x_buffer++] = x;
  ptr_x_buffer %= NB_COEF;

  for( n = (NB_COEF-1) ; n >= 0 ; n-- )
  {
    y += coef[n] * x_buffer[ptr_x_buffer++];
    ptr_x_buffer %= NB_COEF;
  }
  return(y);
}

-Can anybody tell me why do we need constantly to do this expression

ptr_x_buffer%= NB_COEFF.

Because for me it would mean the variable ptr_x_buffer always take the value 0 ?!
And it seems to me far from logic?!

And also can somebody explain to me the first comment about bit masking and modulo.

thank you in advance
:)


问:
Joomla website, iframe videos can not be displayed on Safari
When I use an iframe on my page to show a Vimeo video, it works in Chrome and Firefox but does not work in Safari Desktop.
Here is the error:

An SSL error has occurred and a secure connection to the server cannot
  be made.

I have checked all similar questions and can't see any solutions that work.
Specially this code:

```<code><object>
    <param name="movie" value="http://www.youtube.com/v/[VIDEO_ID]"></param>
    <embed src="http://www.youtube.com/v/[VIDEO_ID]" type="application/x-shockwave-flash"></embed>
</object>
</code>```

The above code is the most upvoted answer, however it shows the following error on the page:

Missing Plug-in

答:
The Missing Plugin error, is due to modern browsers no longer supporting Flash. A more modern solution is Media Element

http://www.mediaelementjs.com/

Body:
When I use an iframe on my page to show a Vimeo video, it works in Chrome and Firefox but does not work in Safari Desktop.
Here is the error:

An SSL error has occurred and a secure connection to the server cannot
  be made.

I have checked all similar questions and can't see any solutions that work.
Specially this code:

<object>
    <param name="movie" value="http://www.youtube.com/v/[VIDEO_ID]"></param>
    <embed src="http://www.youtube.com/v/[VIDEO_ID]" type="application/x-shockwave-flash"></embed>
</object>

The above code is the most upvoted answer, however it shows the following error on the page:

Missing Plug-in


答:
You need to use textContent instead of textcontent :

var customerNumber = document.getElementById("customer-number")
customerNumber.textContent = randomCustomerNumber()

function randomCustomerNumber(){
    var i = Math.floor(Math.random() * 36)
    return(i)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="customers-today">
  <h4>You are customer number <span id="customer-number"></span> today.</h4>
 </div></code>```

Title: Why does random number generator not show on html page?

Body:
You need to use textContent instead of textcontent :

var customerNumber = document.getElementById("customer-number")
customerNumber.textContent = randomCustomerNumber()

function randomCustomerNumber(){
    var i = Math.floor(Math.random() * 36)
    return(i)
}

 <div class="customers-today">
  <h4>You are customer number <span id="customer-number"></span> today.</h4>
 </div>


问:
Increase a variable number by 1
I have code in which I have a large number of characters all declared as being 1 higher than the other.
e.g. m1, m2, m3...

is there any way to increase the number I'm searching for by 1 in a for loop?
I have a long string of letters that I need to check to see if any of them match to the individual, but I cannot use strings due to situational limitations.

a1 is the particular character I'm looking for, m1 is the first in a long string of characters I am having to store as individuals

My attempt that wouldn't run:

```<code>for (a1 != m["%d"], &check, check++)
</code>```

Unfortunately due to the limits of my application I can only use stdio.h and stdlib.h in my solution. Any help would be greatly appreciated

答:
Variable names are used by the compiler, but are not part of the generated executable and therefore not accessible at runtime. You can simulate something like that by an array initialized with the addresses of the respective variables:

```<code>#include <stdio.h>
int main() {
    int a0=0,a1=10,a2=15;
    int *a[3] = { &a0, &a1, &a2 };
    for (int i=0; i<3; i++) {
      int val = *(a[i]);
      printf("a%d:%d\n",i,val);
    }
}
</code>```

Output:

```<code>a0:0
a1:10
a2:15
</code>```

Title: Increase a variable number by 1

Body:
I have code in which I have a large number of characters all declared as being 1 higher than the other.
e.g. m1, m2, m3...

is there any way to increase the number I'm searching for by 1 in a for loop?
I have a long string of letters that I need to check to see if any of them match to the individual, but I cannot use strings due to situational limitations.

a1 is the particular character I'm looking for, m1 is the first in a long string of characters I am having to store as individuals

My attempt that wouldn't run:

for (a1 != m["%d"], &check, check++)

Unfortunately due to the limits of my application I can only use stdio.h and stdlib.h in my solution. Any help would be greatly appreciated

Body:
Variable names are used by the compiler, but are not part of the generated executable and therefore not accessible at runtime. You can simulate something like that by an array initialized with the addresses of the respective variables:

#include <stdio.h>
int main() {
    int a0=0,a1=10,a2=15;
    int *a[3] = { &a0, &a1, &a2 };
    for (int i=0; i<3; i++) {
      int val = *(a[i]);
      printf("a%d:%d\n",i,val);
    }
}

Output:

a0:0
a1:10
a2:15


问:
Why am I getting a "call to member function null" in my logs when file uploading?
I'm not sure why I'm getting Call to a member function photos() on null error in the logs with the current code in my controller.  I'm calling it correctly but for some reason, it can't read my photos() function.  I've tried many ways to fix this but to no avail and hit a wall I just can't climb over.

I've tried inside my controller but still getting the aforementioned error.

```<code>$user = $request->session()->get("user");
$request->$user->photos()->create([
       'file_path' => $request->file('fileToUpload')->getClientOriginalName()
]);

return response()->json($user);
</code>```

Can anyone spot what I'm doing wrong?

Here's my controller:

```<code>if(Auth::user()) {
        $request->user()->photos()->create([
            'file_path' => $request->file('fileToUpload')->getClientOriginalName()
        ]);

        return response()->json($request->session()->get("user"));
    }
}
</code>```

Here's my User model:

```<code>public function photos() {
    return $this->hasMany(Photo::class,'user_id');
}
</code>```

Here's my Photo model

```<code>protected $fillable = ['file_path'];

public function user() {
    return $this->belongsTo(User::class,'user_id');
}
</code>```

Here's my migration table:

```<code>public function up() {
    Schema::create('photos', function (Blueprint $table) {
        $table->id();
        $table->string('file_path', 200);
        $table->unsignedBigInteger("user_id");
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}
</code>```

答:
The error is telling you that the $request object has a null value for user.  The code looks correct, and looks like it should be checking to see if there is an Auth::user()... but there is a weird gotcha that might be interfering.

I've seen times in logging where the $request object doesn't run a query to get the user.  Instead, it may have stale data. Whereas Auth::user() does query the database on every request, and thus you may have a non-null user in Auth::user(), but possibly nothing in the $request object.  Therefore, the if-check succeeds, but the call to $request->user() fails.

As a test, give this a try to see if it is any different:

```<code>if(Auth::user()) {
    Auth::user()->photos()->create([
        'file_path' => $request->file('fileToUpload')->getClientOriginalName()
    ]);

    //etc -- see if it breaks here as well using Auth::user()
  }
}
</code>```

Body:
I'm not sure why I'm getting Call to a member function photos() on null error in the logs with the current code in my controller.  I'm calling it correctly but for some reason, it can't read my photos() function.  I've tried many ways to fix this but to no avail and hit a wall I just can't climb over.

I've tried inside my controller but still getting the aforementioned error.

$user = $request->session()->get("user");
$request->$user->photos()->create([
       'file_path' => $request->file('fileToUpload')->getClientOriginalName()
]);

return response()->json($user);

Can anyone spot what I'm doing wrong?

Here's my controller:

if(Auth::user()) {
        $request->user()->photos()->create([
            'file_path' => $request->file('fileToUpload')->getClientOriginalName()
        ]);

        return response()->json($request->session()->get("user"));
    }
}

Here's my User model:

public function photos() {
    return $this->hasMany(Photo::class,'user_id');
}

Here's my Photo model

protected $fillable = ['file_path'];

public function user() {
    return $this->belongsTo(User::class,'user_id');
}

Here's my migration table:

public function up() {
    Schema::create('photos', function (Blueprint $table) {
        $table->id();
        $table->string('file_path', 200);
        $table->unsignedBigInteger("user_id");
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

Body:
The error is telling you that the $request object has a null value for user.  The code looks correct, and looks like it should be checking to see if there is an Auth::user()... but there is a weird gotcha that might be interfering.

I've seen times in logging where the $request object doesn't run a query to get the user.  Instead, it may have stale data. Whereas Auth::user() does query the database on every request, and thus you may have a non-null user in Auth::user(), but possibly nothing in the $request object.  Therefore, the if-check succeeds, but the call to $request->user() fails.

As a test, give this a try to see if it is any different:

if(Auth::user()) {
    Auth::user()->photos()->create([
        'file_path' => $request->file('fileToUpload')->getClientOriginalName()
    ]);

    //etc -- see if it breaks here as well using Auth::user()
  }
}


问:
How to wait a task to end before to close the processus?
Recently i'm working on a chess and for the AI i'm using Stockfish with the UCI Protocol.
Thanks to this 2 following links ( UCI Protocol : http://wbec-ridderkerk.nl/html/UCIProtocol.html and this post : Using Stockfish Chess AI in Unity ) i have done some progress but i have an issue.

Here is my code :

```<code>        var p = new System.Diagnostics.Process();

        p.StartInfo.FileName = "C:/stockfish/stockfish-11-win/Windows/stockfish_20011801_32bit";

        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;

        p.Start();

        StreamWriter myStreamWriter = p.StandardInput;
        myStreamWriter.WriteLine("position fen " + fen);
        myStreamWriter.WriteLine("go movetime 2000");
        myStreamWriter.Close();

        Thread.Sleep(2000);

        StreamReader reader = p.StandardOutput;
        String bestMoveInAlgebraicNotation = reader.ReadToEnd();
        reader.Close();

        p.Close();

        return bestMoveInAlgebraicNotation;
</code>```

When i ask Stockfish an evaluation with this following code : myStreamWriter.WriteLine("go movetime 2000");

He does it but stop it right away when  i ask the processus to close : p.Close();

So i would like for the processus to wait until the task is done, is there anyway to do it and how?

Thansk for reading me and have a nice day.

答:
use p.WaitForExit();

Sets the period of time to wait for the associated process to exit, and blocks the current thread of execution until the time has elapsed or the process has exited.

Body:
Recently i'm working on a chess and for the AI i'm using Stockfish with the UCI Protocol.
Thanks to this 2 following links ( UCI Protocol : http://wbec-ridderkerk.nl/html/UCIProtocol.html and this post : Using Stockfish Chess AI in Unity ) i have done some progress but i have an issue.

Here is my code :

        var p = new System.Diagnostics.Process();

        p.StartInfo.FileName = "C:/stockfish/stockfish-11-win/Windows/stockfish_20011801_32bit";

        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;

        p.Start();

        StreamWriter myStreamWriter = p.StandardInput;
        myStreamWriter.WriteLine("position fen " + fen);
        myStreamWriter.WriteLine("go movetime 2000");
        myStreamWriter.Close();

        Thread.Sleep(2000);

        StreamReader reader = p.StandardOutput;
        String bestMoveInAlgebraicNotation = reader.ReadToEnd();
        reader.Close();

        p.Close();

        return bestMoveInAlgebraicNotation;

When i ask Stockfish an evaluation with this following code : myStreamWriter.WriteLine("go movetime 2000");

He does it but stop it right away when  i ask the processus to close : p.Close();

So i would like for the processus to wait until the task is done, is there anyway to do it and how?

Thansk for reading me and have a nice day.


问:
How do I save form response as an object in Django's database?
I am unable to save my form responses to the database as an object in Django.
Everytime I click on submit to submit my form, I am just logged out of my website and the object isnt saved in the database either.
Can anyone tell me where I am going wrong?
This is my models in models.py.

```<code>class Chain(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    year = models.CharField(max_length=10, default="20XX")
    sem = models.CharField(max_length=30, default="Default Semester")
    code = models.CharField(max_length=10, default="SUB-CODE")
    slot = models.CharField(max_length=10, default="EX+EX")
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name
</code>```

This is my view in views.py file.

```<code>@login_required(login_url='/')
def create_course(request):
    if request.method == 'GET':
        return render(request, 'create_course.html', {})
    elif request.method == 'POST':
        name=request.POST['name']
        year=request.POST['year']
        sem=request.POST['sem']
        code=request.POST['code']
        slot=request.POST['slot']
        newchain = Chain(
            name=name,
            year=year,
            sem=sem,
            code=code,
            slot=slot,
        )
        newchain.user = request.user
        newchain.save()
        return redirect('success')
</code>```

This is my HTML code for the form.

```<code>{% extends 'authmain.html' %}

{% block content %}
<h3> <p class="text-center"> Create a new Course Blockchain: </p> </h3>

<div class="card border-dark mb-3 mx-auto" align="center" style="width: 40rem;">
  <div class="card-body">
    <h5 class="card-title">
      <form method='POST'>
        {% csrf_token %}
        <label for="year">Year: </label>
        <input type="text" id="year" name="year" value=""><br>
        <label for="code">Course Code: </label>
        <input type="text" id="code" name="code" value=""><br>
        <label for="name">Course Name: </label>
        <input type="text" id="name" name="name" value=""><br>
        <label for="slot">Slot: </label>
        <input type="text" id="slot" name="slot" value=""><br>
        <label for="sem">Semester: </label>
        <input type="text" id="sem" name="sem" value=""><br>
        <button class="btn btn-outline-primary" type="Submit"> Create </button>
      </form>
    </h5>
    </div>
</div>

{% endblock %}
</code>```

This is my urls.py.

```<code>from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('register/', views.register, name="register"),
    path('logout/', views.logoutuser, name="logoutuser"),
    path('dashboard/', views.dashboard, name="dashboard"),
    path('create_course/', views.create_course, name="create_course"),
    path('success', views.success, name="success"),
]
</code>```

This is the view function for success.

```<code>
@login_required(login_url='/')
def success(request):
    return render(request, 'success.html', {})
</code>```

答:
The issue is that you are not closing form tag in the authmain.html.

```<code><ul class="navbar-nav ml-auto">
  <li class="nav-item">
  <form action="{% url 'logoutuser' %}" method='POST'>
  {% csrf_token %}
    <button class="btn btn-outline-info mb-auto" type="submit">Logout</button>
  -----  CLOSING FORM TAG MISSING HERE ---
  </li>
</ul>
</code>```

and when you submit the form at Create Course, you actually trigger this form, which logs out the user. Add closing tag to the logout form and you'll fix your problem.

Sometimes debugging can be a bit tricky.

Body:
I am unable to save my form responses to the database as an object in Django.
Everytime I click on submit to submit my form, I am just logged out of my website and the object isnt saved in the database either.
Can anyone tell me where I am going wrong?
This is my models in models.py.

class Chain(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    year = models.CharField(max_length=10, default="20XX")
    sem = models.CharField(max_length=30, default="Default Semester")
    code = models.CharField(max_length=10, default="SUB-CODE")
    slot = models.CharField(max_length=10, default="EX+EX")
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

This is my view in views.py file.

@login_required(login_url='/')
def create_course(request):
    if request.method == 'GET':
        return render(request, 'create_course.html', {})
    elif request.method == 'POST':
        name=request.POST['name']
        year=request.POST['year']
        sem=request.POST['sem']
        code=request.POST['code']
        slot=request.POST['slot']
        newchain = Chain(
            name=name,
            year=year,
            sem=sem,
            code=code,
            slot=slot,
        )
        newchain.user = request.user
        newchain.save()
        return redirect('success')

This is my HTML code for the form.

{% extends 'authmain.html' %}

{% block content %}

 Create a new Course Blockchain:

      <form method='POST'>
        {% csrf_token %}
        Year:
        <input type="text" id="year" name="year" value="">

        Course Code:
        <input type="text" id="code" name="code" value="">

        Course Name:
        <input type="text" id="name" name="name" value="">

        Slot:
        <input type="text" id="slot" name="slot" value="">

        Semester:
        <input type="text" id="sem" name="sem" value="">

        <button class="btn btn-outline-primary" type="Submit"> Create </button>
      </form>

{% endblock %}

This is my urls.py.

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('register/', views.register, name="register"),
    path('logout/', views.logoutuser, name="logoutuser"),
    path('dashboard/', views.dashboard, name="dashboard"),
    path('create_course/', views.create_course, name="create_course"),
    path('success', views.success, name="success"),
]

This is the view function for success.

@login_required(login_url='/')
def success(request):
    return render(request, 'success.html', {})

Body:
The issue is that you are not closing form tag in the authmain.html.

<ul class="navbar-nav ml-auto">
  <li class="nav-item">
  <form action="{% url 'logoutuser' %}" method='POST'>
  {% csrf_token %}
    <button class="btn btn-outline-info mb-auto" type="submit">Logout</button>
  -----  CLOSING FORM TAG MISSING HERE ---
  </li>
</ul>

and when you submit the form at Create Course, you actually trigger this form, which logs out the user. Add closing tag to the logout form and you'll fix your problem.

Sometimes debugging can be a bit tricky.


问:
Parallel optimizations in SciPy
I have a simple function

```<code>def square(x, a=1):
    return [x**2 + a, 2*x]
</code>```

I want to minimize it over x, for several parameters a. I currently have loops that, in spirit, do something like this:

```<code>In [89]: from scipy import optimize

In [90]: res = optimize.minimize(square, 25, method='BFGS', jac=True)

In [91]: [res.x, res.fun]
Out[91]: [array([ 0.]), 1.0]

In [92]: l = lambda x: square(x, 2)

In [93]: res = optimize.minimize(l, 25, method='BFGS', jac=True)

In [94]: [res.x, res.fun]
Out[94]: [array([ 0.]), 2.0]
</code>```

Now, the function is already vectorized

```<code>In [98]: square(array([2,3]))
Out[98]: [array([ 5, 10]), array([4, 6])]

In [99]: square(array([2,3]), array([2,3]))
Out[99]: [array([ 6, 12]), array([4, 6])]
</code>```

Which means it would probably be much faster to run all the optimizations in parallel rather than looping. Is that something that's easily do-able with SciPy? Or any other 3rd party tool?

答:
I am a bit late to the party. But this may be interesting for people who want to reduce minimization time by parallel computing:

We implemented a parallel version of scipy.optimize.minimize(method='L-BFGS-B') in the package optimparallel available on PyPI. It can speedup the optimization by evaluating the objective function and the (approximate) gradient in parallel. Here is an example:

```<code>from optimparallel import minimize_parallel
def my_square(x, a=1):
    return (x - a)**2
minimize_parallel(fun=my_square, x0=1, args=11)
</code>```

Note that the parallel implementation only reduces the optimization time for objective functions with a long evaluation time (say, longer than 0.1 seconds). Here is an illustration of the possible parallel scaling:

Title: Parallel optimizations in SciPy

Body:
I have a simple function

def square(x, a=1):
    return [x**2 + a, 2*x]

I want to minimize it over x, for several parameters a. I currently have loops that, in spirit, do something like this:

In [89]: from scipy import optimize

In [90]: res = optimize.minimize(square, 25, method='BFGS', jac=True)

In [91]: [res.x, res.fun]
Out[91]: [array([ 0.]), 1.0]

In [92]: l = lambda x: square(x, 2)

In [93]: res = optimize.minimize(l, 25, method='BFGS', jac=True)

In [94]: [res.x, res.fun]
Out[94]: [array([ 0.]), 2.0]

Now, the function is already vectorized

In [98]: square(array([2,3]))
Out[98]: [array([ 5, 10]), array([4, 6])]

In [99]: square(array([2,3]), array([2,3]))
Out[99]: [array([ 6, 12]), array([4, 6])]

Which means it would probably be much faster to run all the optimizations in parallel rather than looping. Is that something that's easily do-able with SciPy? Or any other 3rd party tool?

Body:
I am a bit late to the party. But this may be interesting for people who want to reduce minimization time by parallel computing:

We implemented a parallel version of scipy.optimize.minimize(method='L-BFGS-B') in the package optimparallel available on PyPI. It can speedup the optimization by evaluating the objective function and the (approximate) gradient in parallel. Here is an example:

from optimparallel import minimize_parallel
def my_square(x, a=1):
    return (x - a)**2
minimize_parallel(fun=my_square, x0=1, args=11)

Note that the parallel implementation only reduces the optimization time for objective functions with a long evaluation time (say, longer than 0.1 seconds). Here is an illustration of the possible parallel scaling:


问:
How to access local assets from a remote URL in Android WebView?
To load an asset in HTML, I am using the URL file:///android_asset/my_image.png.
It works when I am loading HTML locally, for instance, using a WebView.loadData() method.

However, I am unable to load a local asset from a remote web site, for instance, when I load a page using WebView.loadUrl("http://example.com/my_page.html"). It shows the page, but the image is not loaded.

How can I fix this problem?

UPDATE:

tarkeshwar mentioned that it is not possible because of security reasons. I understand when you open a web page in a browser, then you as a user are unable to control what the web page is accessing. And it is also a bit different to access local file system when you may read sensitive data of the user. Here I would like just to access application assets.

A workaround could be, to download the page and load it into the WebView using loadData() method. But there might be some security switch to allow WebView to access local assets.

UPDATE2:
I need to support Android 2.3+.

答:
You can't link to a local resource from an external page. That is due to security reasons.

See Pekka's answer for a similar question: How to show local picture in web page?


答:
Try doing:</p>

```<code>var customerNumber = document.getElementById("customer-number");
customerNumber.innerHTML = randomCustomerNumber();

function randomCustomerNumber(){
    var i = Math.floor(Math.random() * 36);
    return i;
}
</code>```

Body:
I am trying to get a random number of customers to "have gone on the website today". Why does the number not show on the page. I am sorry if this is something obvious but I am very new.

var customerNumber = document.getElementById("customer-number")
customerNumber.textcontent = randomCustomerNumber()

function randomCustomerNumber(){
    var i = Math.floor(Math.random() * 36)
    return(i)
}

You are customer number  today.

Body:
Try doing:

var customerNumber = document.getElementById("customer-number");
customerNumber.innerHTML = randomCustomerNumber();

function randomCustomerNumber(){
    var i = Math.floor(Math.random() * 36);
    return i;
}


问:
Changing datetimepicker background color C#
I have a datetimepicker in my Windows form. This may sound like a silly question with a rather simple answer. However, I just can't find a solution to fit my purpose.

Question > Is there a way in which I can change the back colour of the datetimepicker in the form to a different colour other than the generic white?

Thanks for your help.

答:
Change the BackColor property

```<code>Public Class Form1

    Public Sub New()

        InitializeComponent()

        myDateTimePicker1.BackColor = Color.Red

        myDateTimePicker2.BackColor = Color.Yellow

        myDateTimePicker3.BackColor = Color.Green

    End Sub

End Class
</code>```

or Overrides OnPaint function

msdn with more details

Body:
Change the BackColor property

Public Class Form1

    Public Sub New()

        InitializeComponent()

        myDateTimePicker1.BackColor = Color.Red

        myDateTimePicker2.BackColor = Color.Yellow

        myDateTimePicker3.BackColor = Color.Green

    End Sub

End Class

or Overrides OnPaint function

msdn with more details


问:
IDX20803: Unable to obtain configuration from
I know this question has been answered, but I don't understand what people exactly do (about certificates, ssl) and they all use a localhost but not me.

I used this sample as my example OpenIdConnect

I'm using:

A web app

A web API

Both are using .Net Core 2.1. The Web App is using the Azure AD connection to get a JwtBearer token, that is sent to the API.

Seeing the route /api/information in the API, a request is sent from the Web App to the API, and the API is returning the error above.

The exact error is:

```<code>System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://<mycompany>.onmicrosoft.com/<big Guid of 72 chars>/.well-known/openid-configuration'.
</code>```

So I tried to solve this error, by adding certificates, adding the neccessary libraries (System.Net.Http v4.3.3), checked every permission in Azure AD but none of these worked.

If you need more information, I can provide them by adding them in this post.

答:
If anyone has this issue and is using the Azure B2C the instance is your root url for your azure b2c tenant. e.g. https://myroot.b2clogin.com/. The domain should be: myroot.onmicrosoft.com/

Make sure there is no https in the domain.

This worked for me.

```<code>{
    "AzureADB2C": {
        "CallbackPath": "/signin-oidc",
        "ClientId": "<app-registration-app-client-id>",
        "ClientSecret": "<secret-value>",
        "Domain": "<domain-name>.onmicrosoft.com/",
        "EditProfilePolicyId": "B2C_1_profile",
        "Instance": "https://<domain-name>.b2clogin.com/",
        "ResetPasswordPolicyId": "B2C_1_reset",
        "SignUpSignInPolicyId": "B2C_1_signupsignin"
    }
}
</code>```

Body:
I know this question has been answered, but I don't understand what people exactly do (about certificates, ssl) and they all use a localhost but not me.

I used this sample as my example OpenIdConnect

I'm using:

A web app

A web API

Both are using .Net Core 2.1. The Web App is using the Azure AD connection to get a JwtBearer token, that is sent to the API.

Seeing the route /api/information in the API, a request is sent from the Web App to the API, and the API is returning the error above.

The exact error is:

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://<mycompany>.onmicrosoft.com/<big Guid of 72 chars>/.well-known/openid-configuration'.

So I tried to solve this error, by adding certificates, adding the neccessary libraries (System.Net.Http v4.3.3), checked every permission in Azure AD but none of these worked.

If you need more information, I can provide them by adding them in this post.

Body:
If anyone has this issue and is using the Azure B2C the instance is your root url for your azure b2c tenant. e.g. https://myroot.b2clogin.com/. The domain should be: myroot.onmicrosoft.com/

Make sure there is no https in the domain.

This worked for me.

{
    "AzureADB2C": {
        "CallbackPath": "/signin-oidc",
        "ClientId": "<app-registration-app-client-id>",
        "ClientSecret": "<secret-value>",
        "Domain": "<domain-name>.onmicrosoft.com/",
        "EditProfilePolicyId": "B2C_1_profile",
        "Instance": "https://<domain-name>.b2clogin.com/",
        "ResetPasswordPolicyId": "B2C_1_reset",
        "SignUpSignInPolicyId": "B2C_1_signupsignin"
    }
}


问:
TailwindCSS + NextJS: Integrating with PostCSS and IE11 support (custom properties)
According to the docs, tailwind states it supports ie11.

...yet it uses custom properties that are not supported by ie11.

We're attempting to use this in a minimal nextjs project with the following postcss.config.js:

module.exports = {
  plugins: [
    'postcss-import',
    'tailwindcss',
    'autoprefixer',
    ['postcss-custom-properties', { preserve: false }]
  ]
};
```

<p>The only css file we're importing:</p>

<pre class="lang-css prettyprint-override"><code>@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
</code>```

The line ['postcss-custom-properties', { preserve: false }] appears to not be doing anything. Both with the defaults and that one.

Obviously, since ie 11 doesn't support custom properties, stuff like the transform utility are completely ignored.

Anyone have any suggestions for this? I've been spending way too much time on trying to get this to work :|

答:
I'm still experimenting which is the best value but the target attribute in your postcss.config.js is the responsible, set it to ie11 and all the custom css properties will be removed.

The target property isn't documented but I've found this issue explaining the situation. If you are using browserlist, try using

```<code>module.exports = {
  target: 'browserslist',
}
</code>```

Body:
According to the docs, tailwind states it supports ie11.

...yet it uses custom properties that are not supported by ie11.

We're attempting to use this in a minimal nextjs project with the following postcss.config.js:

module.exports = {
  plugins: [
    'postcss-import',
    'tailwindcss',
    'autoprefixer',
    ['postcss-custom-properties', { preserve: false }]
  ]
};

The only css file we're importing:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

The line ['postcss-custom-properties', { preserve: false }] appears to not be doing anything. Both with the defaults and that one.

Obviously, since ie 11 doesn't support custom properties, stuff like the transform utility are completely ignored.

Anyone have any suggestions for this? I've been spending way too much time on trying to get this to work :|

Body:
I'm still experimenting which is the best value but the target attribute in your postcss.config.js is the responsible, set it to ie11 and all the custom css properties will be removed.

The target property isn't documented but I've found this issue explaining the situation. If you are using browserlist, try using

module.exports = {
  target: 'browserslist',
}


问:
Using filter() with across() to keep all rows of a data frame that include a missing value for any variable
Sometimes I want to view all rows in a data frame that will be dropped if I drop all rows that have a missing value for any variable. In this case, I'm specifically interested in how to do this with dplyr 1.0's across() function used inside of the filter() verb.

Here is an example data frame:

```<code>df <- tribble(
  ~id, ~x, ~y,
  1, 1, 0,
  2, 1, 1,
  3, NA, 1,
  4, 0, 0,
  5, 1, NA
)
</code>```

Code for keeping rows that DO NOT include any missing values is provided on the tidyverse website. Specifically, I can use:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ !is.na(.x)
    )
  )
</code>```

Which returns:

```<code># A tibble: 3 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     1     1     0
2     2     1     1
3     4     0     0
</code>```

However, I can't figure out how to return the opposite -- rows with a missing value in any variable. The result I'm looking for is:

```<code># A tibble: 2 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     3    NA     1
2     5     1    NA
</code>```

My first thought was just to remove the !:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )
</code>```

But, that returns zero rows.

Of course, I can get the answer I want with this code if I know all variables that have a missing value ahead of time:

```<code>df %>%
  filter(is.na(x) | is.na(y))
</code>```

But, I'm looking for a solution that doesn't require me to know which variables have a missing value ahead of time. Additionally, I'm aware of how to do this with the filter_all() function:

```<code>df %>%
  filter_all(any_vars(is.na(.)))
</code>```

But, the filter_all() function has been superseded by the use of across() in an existing verb. See https://dplyr.tidyverse.org/articles/colwise.html

Other unsuccessful attempts I've made are:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.))
    )
  )
</code>```

答:
Here is my take on this. My understanding of the new across() function is that it operates on columns, not rows. So when you run this code you don't get anything becuase

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )

# A tibble: 0 x 3
# … with 3 variables: id <dbl>, x <dbl>, y <dbl>
```

<p>it essentially create three logical columns in the background to check the presence of element-wise <code>NA</code>, it then probably compute a final logical column on which it operates the filter command. Now this final column will have <code>TRUE</code> only if all the columns are <code>TRUE</code> for <code>is.na()</code>. To test my hypothesis, I added another row in your data that has all <code>NA</code> in all three columns. And when I run your code as is, I get that row as an output because now the corresponding row will generate a <code>TRUE</code> in that final logical vector. Now I don't know if this is how <code>across()</code> works exactly but this makes sense to me.</p>

<pre class="lang-r prettyprint-override"><code>library(tidyverse)
df <- tribble(
  ~id, ~x, ~y,
  1, 1, 0,
  2, 1, 1,
  3, NA, 1,
  4, 0, 0,
  5, 1, NA,
  NA,NA,NA
)

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )
#> # A tibble: 1 x 3
#>      id     x     y
#>   <dbl> <dbl> <dbl>
#> 1    NA    NA    NA
</code>```

so in order for this to work with your original data, I would use rowwise() and c_across() (rowwise version of across()) as follows

df %>% rowwise() %>%
  filter(
    is.na(sum(c_across(everything())))
  ) %>%
  ungroup()
#> # A tibble: 3 x 3
#>      id     x     y
#>   <dbl> <dbl> <dbl>
#> 1     3    NA     1
#> 2     5     1    NA

df %>% rowwise() %>%
  filter(
    any(is.na(c_across(everything())))
  ) %>%
  ungroup()
#> # A tibble: 3 x 3
#>      id     x     y
#>   <dbl> <dbl> <dbl>
#> 1     3    NA     1
#> 2     5     1    NA
```

Created on 2020-06-02 by the reprex package (v0.3.0)

Body:
Sometimes I want to view all rows in a data frame that will be dropped if I drop all rows that have a missing value for any variable. In this case, I'm specifically interested in how to do this with dplyr 1.0's across() function used inside of the filter() verb.

Here is an example data frame:

df <- tribble(
  ~id, ~x, ~y,
  1, 1, 0,
  2, 1, 1,
  3, NA, 1,
  4, 0, 0,
  5, 1, NA
)

Code for keeping rows that DO NOT include any missing values is provided on the tidyverse website. Specifically, I can use:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ !is.na(.x)
    )
  )

Which returns:

# A tibble: 3 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     1     1     0
2     2     1     1
3     4     0     0

However, I can't figure out how to return the opposite -- rows with a missing value in any variable. The result I'm looking for is:

# A tibble: 2 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     3    NA     1
2     5     1    NA

My first thought was just to remove the !:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )

But, that returns zero rows.

Of course, I can get the answer I want with this code if I know all variables that have a missing value ahead of time:

df %>%
  filter(is.na(x) | is.na(y))

But, I'm looking for a solution that doesn't require me to know which variables have a missing value ahead of time. Additionally, I'm aware of how to do this with the filter_all() function:

df %>%
  filter_all(any_vars(is.na(.)))

But, the filter_all() function has been superseded by the use of across() in an existing verb. See https://dplyr.tidyverse.org/articles/colwise.html

Other unsuccessful attempts I've made are:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.))
    )
  )

Body:
Here is my take on this. My understanding of the new across() function is that it operates on columns, not rows. So when you run this code you don't get anything becuase

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )

# A tibble: 0 x 3
# … with 3 variables: id <dbl>, x <dbl>, y <dbl>

it essentially create three logical columns in the background to check the presence of element-wise NA, it then probably compute a final logical column on which it operates the filter command. Now this final column will have TRUE only if all the columns are TRUE for is.na(). To test my hypothesis, I added another row in your data that has all NA in all three columns. And when I run your code as is, I get that row as an output because now the corresponding row will generate a TRUE in that final logical vector. Now I don't know if this is how across() works exactly but this makes sense to me.

library(tidyverse)
df <- tribble(
  ~id, ~x, ~y,
  1, 1, 0,
  2, 1, 1,
  3, NA, 1,
  4, 0, 0,
  5, 1, NA,
  NA,NA,NA
)

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )
#> # A tibble: 1 x 3
#>      id     x     y
#>   <dbl> <dbl> <dbl>
#> 1    NA    NA    NA

so in order for this to work with your original data, I would use rowwise() and c_across() (rowwise version of across()) as follows

df %>% rowwise() %>%
  filter(
    is.na(sum(c_across(everything())))
  ) %>%
  ungroup()
#> # A tibble: 3 x 3
#>      id     x     y
#>   <dbl> <dbl> <dbl>
#> 1     3    NA     1
#> 2     5     1    NA

df %>% rowwise() %>%
  filter(
    any(is.na(c_across(everything())))
  ) %>%
  ungroup()
#> # A tibble: 3 x 3
#>      id     x     y
#>   <dbl> <dbl> <dbl>
#> 1     3    NA     1
#> 2     5     1    NA

Created on 2020-06-02 by the reprex package (v0.3.0)


问:
why isn't 0.1235 * 10 equals 1.235 in python?
I am using python 3.6.8 and tried to multiply 0.1235 with 10 and the answer is 1.2349999999999999 rather than 1.235.
After importing the decimal module, when we multiply decimal.Decimal(0.1235) with 10 we get Decimal('1.234999999999999986677323704') rather than Decimal('1.235').
So How to do precision float calculations with python?

答: The value 0.1235 is a decimal fraction that needs to be converted to a binary fraction in memory, resulting in not a 100 percent accuracy. please refer to Floating Point Arithmetic: Issues and Limitations</p>


问:
How do I toggle boolean values in JSON object using express?
I am a beginner and have just finished my first MERN CRUD app. I've thought about a few ways to improve the app. The app is a todo list and has a complete button. The complete button will score a line through an item in the todo list. The complete button triggers a function which will make a post request (shown below) to the nodejs/express backend server. When the "isCompleted" field in the Mongo model is set to "true" (by default it's false), the item will be scored out. I tried to find a way to toggle the boolean values in the "isCompleted" field, whenever the complete button is clicked. This way you can unscore an item. But I just couldn't figure out how to implement this. Any ideas?</p>

```<code>exports.updateEntry = async (req, res, next) => {
try {
    const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: true});

    return res.status(200).json({
        success: true,
        data: entry
    });

} catch (err) {
    return res.status(500).json({
        success: false,
        error: 'Server Error'
    });
}
</code>```

答:
before the

const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: true});

you need to fetch the current value of the variable, should be something like this (been a long time since i worked with mongo):

const isCompleted = await Entry.findById({_id:req.params.id}).select('isCompleted')

then use !isCompleted to get the toggled value, like this:
const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: !isCompleted});

Body:
I am a beginner and have just finished my first MERN CRUD app. I've thought about a few ways to improve the app. The app is a todo list and has a complete button. The complete button will score a line through an item in the todo list. The complete button triggers a function which will make a post request (shown below) to the nodejs/express backend server. When the "isCompleted" field in the Mongo model is set to "true" (by default it's false), the item will be scored out. I tried to find a way to toggle the boolean values in the "isCompleted" field, whenever the complete button is clicked. This way you can unscore an item. But I just couldn't figure out how to implement this. Any ideas?

exports.updateEntry = async (req, res, next) => {
try {
    const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: true});

    return res.status(200).json({
        success: true,
        data: entry
    });

} catch (err) {
    return res.status(500).json({
        success: false,
        error: 'Server Error'
    });
}


答:
You can use body-parser middleware at top of your function (maybe you need it at a general level, so you can use it at index.js of your express project).

Then you can do this:

```<code>exports.updateEntry = async (req, res, next) => {
try {
    const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: req.body.isCompleted});
      return res.status(200).json({
       success: true,
      data: entry
      });
} catch (err) {
   return res.status(500).json({
      success: false,
      error: 'Server Error'
});}
</code>```

Title: How do I toggle boolean values in JSON object using express?

Body:
You can use body-parser middleware at top of your function (maybe you need it at a general level, so you can use it at index.js of your express project).

Then you can do this:

exports.updateEntry = async (req, res, next) => {
try {
    const entry = await Entry.findByIdAndUpdate({_id:req.params.id}, {isCompleted: req.body.isCompleted});
      return res.status(200).json({
       success: true,
      data: entry
      });
} catch (err) {
   return res.status(500).json({
      success: false,
      error: 'Server Error'
});}


问:
Unity UI text not displayed?
Why is the text displayed on the stage but not in the game?

答:
To me this looks like a Canvas issue:

Make sure the canvas scale dynamically, "Scale with Screen Size"

Check Reference Resolution

Make sure the Text Anchor Preset's is correct

You should probably using "Best Fit" in the UI Text Components to make sure the text is dynamically aligned

Title: Unity UI text not displayed?


问:
why is it showing "type object 'CourseInstructor' has no attribute 'objects' "
i'm using class based views because classes can't be defined in function based views. i have two models (Course, CourseInstructor) when i created the first model and checked it there was no such error but when i created the second model, it displayed that error.</p>

```<code>-- models.py --
from django.db import models

class Course(models.Model):
    courseNumber = models.CharField(max_length=10)
    courseName = models.CharField(max_length=100)
    maxNumbOfStudents = models.CharField(max_length=200)

    def __str__(self):
        return self.courseName, self.courseNumber, self.maxNumbOfStudents

class CourseInstructor(models.Model):
    courseNumber = models.CharField(max_length=200)
    instructorNumber = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = "CourseInstructor"

    def __str__(self):
        return self.instructorNumber + " - " + self.courseNumber

-- views.py --
from django.shortcuts import HttpResponse, render
from django.views import View
from .models import Course, CourseInstructor

class Course(View):
    def get(self, request):
        courses = Course.objects.all()
        return render(request, 'examscheduling.html', {'courses': courses})

class CourseInstructor(View):
    def get(self, request):
        coursesInstructor = CourseInstructor.objects.all()
        return render(request, 'examscheduling.html', {'coursesInstructor': coursesInstructor})
</code>```

答:
Edit your both models like this

models.py

```<code>class Course(models.Model):

    """your other fields"""
    objects = models.Manager()
</code>```

Body:
i'm using class based views because classes can't be defined in function based views. i have two models (Course, CourseInstructor) when i created the first model and checked it there was no such error but when i created the second model, it displayed that error.

-- models.py --
from django.db import models

class Course(models.Model):
    courseNumber = models.CharField(max_length=10)
    courseName = models.CharField(max_length=100)
    maxNumbOfStudents = models.CharField(max_length=200)

    def __str__(self):
        return self.courseName, self.courseNumber, self.maxNumbOfStudents

class CourseInstructor(models.Model):
    courseNumber = models.CharField(max_length=200)
    instructorNumber = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = "CourseInstructor"

    def __str__(self):
        return self.instructorNumber + " - " + self.courseNumber

-- views.py --
from django.shortcuts import HttpResponse, render
from django.views import View
from .models import Course, CourseInstructor

class Course(View):
    def get(self, request):
        courses = Course.objects.all()
        return render(request, 'examscheduling.html', {'courses': courses})

class CourseInstructor(View):
    def get(self, request):
        coursesInstructor = CourseInstructor.objects.all()
        return render(request, 'examscheduling.html', {'coursesInstructor': coursesInstructor})

Body:
Edit your both models like this

models.py

class Course(models.Model):

    """your other fields"""
    objects = models.Manager()


问:
XML Tag grouping in RTF Template to suppress duplicates
My XML Tag generated is as follows-

```<code><P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>
</code>```

When I am using these tag like below in the RTF template-

```<code>DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>
</code>```

This is giving an output like -

```<code>DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1
</code>```

I want the repeated values in division and district to be suppressed and the output to look like -

```<code>DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
                                                      Laboratory Services                11
                                                      Corporate                          3
                      S District                      Corporate Administration           6
                                                      Corporate Technology               1
</code>```

How can this be achieved ? I am not being able to use for-each-group properly to group the tags. Can someone please help ?

答:
You can also use variables. Something like this:

RTF

Make sure you put your "if" logic in the alt-text/field properties, else, it may not work. I took it out so you could see it better here.

Output

Body:
My XML Tag generated is as follows-

<P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>

When I am using these tag like below in the RTF template-

DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>

This is giving an output like -

DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1

I want the repeated values in division and district to be suppressed and the output to look like -

DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
                                                      Laboratory Services                11
                                                      Corporate                          3
                      S District                      Corporate Administration           6
                                                      Corporate Technology               1

How can this be achieved ? I am not being able to use for-each-group properly to group the tags. Can someone please help ?


问:
Error: AttributeError: 'DataFrame' object has no attribute '_jdf'
I want to perform k-fold cross validation using pyspark to finetune the parameters and I'm using pyspark.ml.
I am getting Attribute Error.

AttributeError: 'DataFrame' object has no attribute '_jdf'

I have tried initially using pyspark.mllib but was not able to succeed in performing k-fold cross validation

```<code>import pandas as pd
from pyspark import SparkConf, SparkContext
from pyspark.ml.classification import DecisionTreeClassifier

data=pd.read_csv("file:///SparkCourse/wdbc.csv", header=None)
type(data)
print(data)

conf = SparkConf().setMaster("local").setAppName("SparkDecisionTree")
sc = SparkContext(conf = conf)

# Create initial Decision Tree Model
dt = DecisionTreeClassifier(labelCol="label", featuresCol="features",
maxDepth=3)

# Train model with Training Data
dtModel = dt.fit(data)

# I expect the model to be trained but I'm getting the following error
AttributeError: 'DataFrame' object has no attribute '_jdf'
</code>```

Note: I'm able to print the data. Error is in dtModel

答:
Convert Panadas to Spark</p>

```<code>from pyspark.sql import SQLContext
sc = SparkContext.getOrCreate()
sqlContext = SQLContext(sc)

spark_dff = sqlContext.createDataFrame(panada_df)
</code>```

Body:
I want to perform k-fold cross validation using pyspark to finetune the parameters and I'm using pyspark.ml.
I am getting Attribute Error.

AttributeError: 'DataFrame' object has no attribute '_jdf'

I have tried initially using pyspark.mllib but was not able to succeed in performing k-fold cross validation

import pandas as pd
from pyspark import SparkConf, SparkContext
from pyspark.ml.classification import DecisionTreeClassifier

data=pd.read_csv("file:///SparkCourse/wdbc.csv", header=None)
type(data)
print(data)

conf = SparkConf().setMaster("local").setAppName("SparkDecisionTree")
sc = SparkContext(conf = conf)

# Create initial Decision Tree Model
dt = DecisionTreeClassifier(labelCol="label", featuresCol="features",
maxDepth=3)

# Train model with Training Data
dtModel = dt.fit(data)

# I expect the model to be trained but I'm getting the following error
AttributeError: 'DataFrame' object has no attribute '_jdf'

Note: I'm able to print the data. Error is in dtModel

Body:
Convert Panadas to Spark

from pyspark.sql import SQLContext
sc = SparkContext.getOrCreate()
sqlContext = SQLContext(sc)

spark_dff = sqlContext.createDataFrame(panada_df)


问:
How to share a Git index between 2 OSes, avoid index refresh

What I'm trying to achieve

I have a Git repository on the host system, which is shared with a docker container.
Inside the docker container, I would like to get the files that have been changed/staged. I also want to be able to add files to be staged in the host system.

Essentially, a pre-commit hook on the host is going to call a program inside the docker image, which will then check/change files that are going to be committed.

What I've tried

From this question: git forces refresh index after switching between windows and linux

I've tried adding the GIT_INDEX_FILE argument, but at best, it results in separate staging areas, so the docker image doesn't end up working with the host's staging areas.

Without that argument, I need to run git status in the container each time, which then refreshes the index every time.

Notes

This will likely only be running on a Mac OS X host system, and Linux docker container.

答:
As mentioned in the question you linked, this isn't recommended.  Git stores a lot of metadata about the files in the index, including things like the device and inode number.  Those items are necessarily going to differ between macOS and the Linux kernel that runs the container.

Git is not designed around sharing working trees between systems because its security model treats anything that isn't a fetch or clone from an untrusted repository as unsafe.  It's therefore not intended to share non-bare repositories, even across operating systems on the same computer.

You can try setting core.checkStat to minimal and, if that isn't sufficient, core.trustctime to false.  If those don't work, then you'll probably need to do a git update-index --refresh in your hook, which is the plumbing (scripting) command for updating the index.  That wouldn't be avoidable if those config options don't work for you.

Note that setting these options means that you run the risk of Git not detecting changes, so they are not magical solutions, but instead a workaround.


问:
Last object in a list isn't deleted after deleting it. When is it effectively deleted?
The following code should delete each of the n Human objects, then print the last line, but it deletes only 4 of them, the 5th gets deleted (I think) after execution stops.

class Human():
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f'{self.name} is dead')

n = 5
humans = []
for i in range(n):
    human = Human('Bob')
    humans.append(human)

for i in reversed(range(n)):
    del humans[i]

print('DEATH')
```

<p>The output is the following (Powershell and Python 3.8.1):</p>

```Bob is dead
Bob is dead
Bob is dead
Bob is dead
DEATH
Bob is dead
```

After the 2nd for-loop humans is empty, so it's not possible to delete the last item by del humans[0]. Other ways of deleting contents (del humans[:] or humans.clear) of the list also don't fix the issue, the output stays the same.

So, is this how the code should behave or is there some issue?

答:
One of the objects isn't being garbage-collected because there's still a reference to it:

```<code>class Human():
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f'{self.name} is dead')

n = 5
humans = []
for i in range(n):
    human = Human(f'Bob {i}')
    humans.append(human)

for i in reversed(range(n)):
    print(f'Die, {humans[i].name}!')
    del humans[i]

print('DEATH')
print(f"(except for {human.name} whom we haven't forgotten about!)")
</code>```

If you want to avoid that dangling reference, an easy fix is not to create it in the first place:

```<code>n = 5
humans = []
for i in range(n):
    humans.append(Human(f'Bob {i}'))
</code>```

or better yet:

```<code>n = 5
humans = [Human(f'Bob {i}') for i in range(n)]
</code>```

Body:
The following code should delete each of the n Human objects, then print the last line, but it deletes only 4 of them, the 5th gets deleted (I think) after execution stops.

class Human():
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f'{self.name} is dead')

n = 5
humans = []
for i in range(n):
    human = Human('Bob')
    humans.append(human)

for i in reversed(range(n)):
    del humans[i]

print('DEATH')

The output is the following (Powershell and Python 3.8.1):

Bob is dead
Bob is dead
Bob is dead
Bob is dead
DEATH
Bob is dead

After the 2nd for-loop humans is empty, so it's not possible to delete the last item by del humans[0]. Other ways of deleting contents (del humans[:] or humans.clear) of the list also don't fix the issue, the output stays the same.

So, is this how the code should behave or is there some issue?

Body:
One of the objects isn't being garbage-collected because there's still a reference to it:

class Human():
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f'{self.name} is dead')

n = 5
humans = []
for i in range(n):
    human = Human(f'Bob {i}')
    humans.append(human)

for i in reversed(range(n)):
    print(f'Die, {humans[i].name}!')
    del humans[i]

print('DEATH')
print(f"(except for {human.name} whom we haven't forgotten about!)")

If you want to avoid that dangling reference, an easy fix is not to create it in the first place:

n = 5
humans = []
for i in range(n):
    humans.append(Human(f'Bob {i}'))

or better yet:

n = 5
humans = [Human(f'Bob {i}') for i in range(n)]


问:
How to disable the android wear back swipe?
I am creating a Android Wear app that has an touch area. The user is suppose to be able to move it's finger in all directions over the screen (Think touchpad on your laptop). However the back swipe makes this a bit problematic. Any help with getting around this issue would be a great help.

How to disable the android wear back swipe?

/Jakob

答:
If you want the whole app to override Swipe, place the theme property under your Manifest's <application> tag. If you want it to apply only to a certain activity, then place the property under that activity's <activity> tag.

So:

create or update styles.xml in the res/values folder with the android:windowSwipeToDismiss property, such as:

    ...
    false

If you want to override swipe in the whole app, Update your Manifest as such:

```<code>    <application
            ...
            android:theme="@style/AppTheme">
</code>```

If you want to override swipe in a specific activity, Update your Manifest as such:

```<code>    <activity
        ...
        android:theme="@style/AppTheme">
    </activity>
</code>```

where ... represents all your other settings you already have. Remember you will need to give alternative ways out of the activity and/or app depending on which level you overrode

Body:
If you want the whole app to override Swipe, place the theme property under your Manifest's <application> tag. If you want it to apply only to a certain activity, then place the property under that activity's <activity> tag.

So:

create or update styles.xml in the res/values folder with the android:windowSwipeToDismiss property, such as:

    ...
    false

If you want to override swipe in the whole app, Update your Manifest as such:

    <application
            ...
            android:theme="@style/AppTheme">

If you want to override swipe in a specific activity, Update your Manifest as such:

    <activity
        ...
        android:theme="@style/AppTheme">
    </activity>

where ... represents all your other settings you already have. Remember you will need to give alternative ways out of the activity and/or app depending on which level you overrode