问:
Static variable across multiple, different subclasses - corrected
I was wondering what happened if I define a base Activity object with all my activities as subclasses of that. Then I declare a static variable in the base class, will all the subclasses use the SAME static or will there be one per subclass.

For example. My base class:

```<code>public class MyBaseActivity extends Activity{

   static int myStatic;

   ...
   ....

}
</code>```

Then:

```<code>public class MyActivity1 extends MyBaseActivity {

   private void someMethod1(){
         myStatic = 1;
    }

   ...
   ....

}
</code>```

and

```<code>public class MyActivity1 extends MyBaseActivity {

   private void someMethod2(){
          if (myStatic == 1)
            doSomething();
    }

   ...
   ....

}
</code>```

If I now start MyActivity1 and it sets a value in "myStatic". It then exits and then I start MyActivity2 - should I still have the value set by the first activity?
In the example above, would the "if" statement be true or false?

I know that if I instantiate Activity1 more than once then obviously I would get the same static variable. However, here I am instantiating a different subclass each time.

I am getting the impression that that is what is happening to me but want to be sure.

答:
Static variables belong to the Class object, not instances. There is only one Class object (for that class), so there is only one instance of the static variable, so "yes they all see the same variable".

Subclasses have visibility of the variable if it's protected or public.

Body:
I was wondering what happened if I define a base Activity object with all my activities as subclasses of that. Then I declare a static variable in the base class, will all the subclasses use the SAME static or will there be one per subclass.

For example. My base class:

public class MyBaseActivity extends Activity{

   static int myStatic;

   ...
   ....

}

Then:

public class MyActivity1 extends MyBaseActivity {

   private void someMethod1(){
         myStatic = 1;
    }

   ...
   ....

}

and

public class MyActivity1 extends MyBaseActivity {

   private void someMethod2(){
          if (myStatic == 1)
            doSomething();
    }

   ...
   ....

}

If I now start MyActivity1 and it sets a value in "myStatic". It then exits and then I start MyActivity2 - should I still have the value set by the first activity?
In the example above, would the "if" statement be true or false?

I know that if I instantiate Activity1 more than once then obviously I would get the same static variable. However, here I am instantiating a different subclass each time.

I am getting the impression that that is what is happening to me but want to be sure.


来源: stackexchange

问:
Need to display the vet number when the number of consultations by the vet is greater than 1
SELECT vetno, COUNT(vetno) AS NumberOfConsultations FROM consultation GROUP BY vetno ;</p>

答:
Please use below query, when ever you aggregate and you wanted to filter out using aggregated column, you have to use having clause

```<code>SELECT vetno, COUNT(vetno) AS NumberOfConsultations FROM consultation GROUP BY vetno having  COUNT(vetno) > 1;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Please use below query, when ever you aggregate and you wanted to filter out using aggregated column, you have to use having clause

SELECT vetno, COUNT(vetno) AS NumberOfConsultations FROM consultation GROUP BY vetno having  COUNT(vetno) > 1;


问:
python subprocess git clone
I'm using subprocess() on AWS lambda
And using this layer: https://github.com/lambci/git-lambda-layer

Here is code:

```<code>import json
import os

import subprocess

def lambda_handler(event, context):

    os.chdir('/tmp')

    subprocess.Popen(["git", "clone", "https:/github.com/hongmingu/requirements"], shell=True)
    subprocess.Popen(["touch word.txt"], shell=True)

    word = str(subprocess.check_output(["ls"], shell=True))
    return {
        'statusCode': 200,
        'body': json.dumps(word)
    }
</code>```

And it returns:

```<code>Response:
{
  "statusCode": 200,
  "body": "\"b'word.txt\\\\n'\""
}
</code>```

So there is something wrong on subprocess.Popen(["git", "clone", "https:/github.com/hongmingu/requirements"], shell=True)

I checked there is git by subprocess.check_output(["git --version"], shell=True) and it works well.

How to solve it?

答:
There are a few problems.

First, you need to wait for the git process to exit. To do this with subprocess.Popen, call .wait() on the returned Popen object. However, I'd recommend using subprocess.check_call() instead to automatically wait for the process to exit and to raise an error if the process returns a non-zero exit status.

Second, there's no need to specify shell=True since you're not using any shell expansions or built-ins. In fact, when passing an argument list when using shell=True, the first item is the command string, and the remaining items are arguments to the shell itself, not the command.

Lastly, you're missing a slash in your GitHub URL.

Try this instead:

subprocess.check_call(["git", "clone", "https://github.com/hongmingu/requirements"])
```

Title: python subprocess git clone

Body:
I'm using subprocess() on AWS lambda
And using this layer: https://github.com/lambci/git-lambda-layer

Here is code:

import json
import os

import subprocess

def lambda_handler(event, context):

    os.chdir('/tmp')

    subprocess.Popen(["git", "clone", "https:/github.com/hongmingu/requirements"], shell=True)
    subprocess.Popen(["touch word.txt"], shell=True)

    word = str(subprocess.check_output(["ls"], shell=True))
    return {
        'statusCode': 200,
        'body': json.dumps(word)
    }

And it returns:

Response:
{
  "statusCode": 200,
  "body": "\"b'word.txt\\\\n'\""
}

So there is something wrong on subprocess.Popen(["git", "clone", "https:/github.com/hongmingu/requirements"], shell=True)

I checked there is git by subprocess.check_output(["git --version"], shell=True) and it works well.

How to solve it?


问:
What is the use of SlugField in django?
Note: Please dont consider it as duplicate post, all the existing posts are not giving clear understanding of SlugField.

My question is "we can sluggify and store the value in a CharField right? then why do we need SlugField for something that can be done easily using CharField?"

For example, in my model, I have a field called

```<code>url = models.CharField(max_length=30)
def save(self, ...):
    self.url = slugify(self.url)
    .......
</code>```

Won't the url be saved in slugified format in database? I can use this slugified value in browser right, then what is the use of creating models.SlugFIeld(max_length=30)? What advantage SlugField will add over slugified CharField?

In above code, how replacing "CharField" with "SlugField" be advantageous?

答:
We can slugify and store the value in a CharField right? then why do we need SlugField for something that can be done easily using CharField?

A SlugField is a CharField, but a special CharField. It is a field that contains a validator that will, if you for example enter data through a form, validate if the entered string is indeed a slug. For example a slug does not contain whitespace, so if you would use the SlugField in a form, such that an author can specify the slug themselve, it will reject such slugs.

By default it uses the django.core.validators.validate_slug validator [GitHub]. The SlugField has an extra parameter allow_unicode. If this is set to True, it will use the django.core.validators.validate_unicode_slug validator [GitHub].

So in essence it is indeed a CharField, but with a validator that is determined by the **allow_unicode=… parameter [Django-doc]. This thus makes it more convenient.

Often you do not want to slugify the content of the slug field itself, but from another field, for example the title of a blog post entry. You thus still want to preserve the title, but make a slugified variant.

The django-autoslug package [readthedocs] provides an AutoSlugField [readthedocs] which is more convenient, since you can define how to populate the field, and thus it will automatically slugify:

```<code>from autoslug import AutoSlugField

class MyModel(models.Model):
    title = models.CharField(max_length=128)
    slug = <b>AutoSlugField(populate_from='title')</b></code>```

Title: What is the use of SlugField in django?

Body:
Note: Please dont consider it as duplicate post, all the existing posts are not giving clear understanding of SlugField.

My question is "we can sluggify and store the value in a CharField right? then why do we need SlugField for something that can be done easily using CharField?"

For example, in my model, I have a field called

url = models.CharField(max_length=30)
def save(self, ...):
    self.url = slugify(self.url)
    .......

Won't the url be saved in slugified format in database? I can use this slugified value in browser right, then what is the use of creating models.SlugFIeld(max_length=30)? What advantage SlugField will add over slugified CharField?

In above code, how replacing "CharField" with "SlugField" be advantageous?

Body:
We can slugify and store the value in a CharField right? then why do we need SlugField for something that can be done easily using CharField?

A SlugField is a CharField, but a special CharField. It is a field that contains a validator that will, if you for example enter data through a form, validate if the entered string is indeed a slug. For example a slug does not contain whitespace, so if you would use the SlugField in a form, such that an author can specify the slug themselve, it will reject such slugs.

By default it uses the django.core.validators.validate_slug validator [GitHub]. The SlugField has an extra parameter allow_unicode. If this is set to True, it will use the django.core.validators.validate_unicode_slug validator [GitHub].

So in essence it is indeed a CharField, but with a validator that is determined by the **allow_unicode=… parameter [Django-doc]. This thus makes it more convenient.

Often you do not want to slugify the content of the slug field itself, but from another field, for example the title of a blog post entry. You thus still want to preserve the title, but make a slugified variant.

The django-autoslug package [readthedocs] provides an AutoSlugField [readthedocs] which is more convenient, since you can define how to populate the field, and thus it will automatically slugify:

from autoslug import AutoSlugField

class MyModel(models.Model):
    title = models.CharField(max_length=128)
    slug = AutoSlugField(populate_from='title')


问:
How to encode array elements in javascript?
How can I encode javascript arrays in url?

eg: The following is my query param

```<code>/query?colors=['red','blue','green',]
</code>```

expected output

```<code>%5B%27red%27%2C%27blue%27%2C%27green%27%2C%5D
</code>```

I've tried encodeURI and encodeURIComponent, but the comma is not getting transformed in to %2C.

UPDATE
I tried this

```<code>let colors = ['red','green']
encodeURIComponent(JSON.stringify(colors))
</code>```

colors=%255B%2522red%2522%252C%2522green%2522%255D.

But when I does so additional characters 25 is getting added. How Can I prevent that?

答:
var test = ['red','blue','green'];

console.log('colors='+encodeURIComponent(JSON.stringify(test)));```

Body:
How can I encode javascript arrays in url?

eg: The following is my query param

/query?colors=['red','blue','green',]

expected output

%5B%27red%27%2C%27blue%27%2C%27green%27%2C%5D

I've tried encodeURI and encodeURIComponent, but the comma is not getting transformed in to %2C.

UPDATE
I tried this

let colors = ['red','green']
encodeURIComponent(JSON.stringify(colors))

colors=%255B%2522red%2522%252C%2522green%2522%255D.

But when I does so additional characters 25 is getting added. How Can I prevent that?


问:
reuse of same object of chart in highcharts to minimize coding
I am creating a dashboard and atleats 10 PIE charts are displayed on the page. Each PIE chart is different by some values only and remaining ALL other things are same.

Angular 7 + HighCharts I am using. Below is the code. If I try to use chart2 2 times in HTML, it appears only once. If I use a different variable for same code copy pasted, it works good.

How can I minimize code or reuse the same chart object by passing different values?

In the constructor let keyword is needed and outside constructor it works without using it

for 10 different PIE charts, all are differed by only series in the chart object. How one object can be used for all 10?.

```<code>@ Component({
 selector: 'app-chart',
 templateUrl: './chart.Component.html',
 styleUrls: ['./chart.Component.css'],
 providers: [LotoService],
})

export class ChartComponent implements OnInit {

constructor(private http: HttpClient) {

    let chart8: any;
    let chart2: any;

}

CP_A2A = 10;
CP_A2CA = 10;

ngOnInit() {}

chart2 = new Chart({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie',
            backgroundColor: '#fff',
            marginTop: 20,
            height: 300
        },
        credits: {
            enabled: false
        },
        title: {
            text: null,
            style: {
                color: '#858585',
                fontSize: '14px'
            }
        },
        tooltip: {
            pointFormat: '{point.y}'
        },
        series: [{
                type: 'pie',
                name: 'Share',
                data: [{
                        name: 'Approved',
                        y: 500
                    }, {
                        name: 'Conditionally Approved',
                        y: 300
                    }, {
                        name: 'Not Approved',
                        y: 200
                    }
                ]
            }
        ],
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: false,
                colors: ['#00366E', '#3693F8', '#C8E7FB'],
                center: ['50%', '37%']
            }
        },
    });
</code>```

答:
Quick Fix will be

You can actually keep the configuration in a default config variable, as below

```<code>defaultChartConfig = {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie',
            backgroundColor: '#fff',
            marginTop: 20,
            height: 300
        },
        credits: {
            enabled: false
        },
        title: {
            text: null,
            style: {
                color: '#858585',
                fontSize: '14px'
            }
        },
        tooltip: {
            pointFormat: '{point.y}'
        },
        series: [{
                type: 'pie',
                name: 'Share',
                data: [ ]
            }
        ],
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: false,
                colors: ['#00366E', '#3693F8', '#C8E7FB'],
                center: ['50%', '37%']
            }
        },
    }
</code>```

then forEach chart you should reuse the config and change the data as below

```<code>for (i = 0; i < 10; i++) {
     const chart = new Chart(this. defaultChartConfig);
     chart.series.data = ____/// whatever data
     this.charts.push(chart)
}
</code>```

use ngFor in the UI for displaying the charts

Better approach will be create a generic pie-chart component with a selector app-pie-chart using the highcharts and accept the series object as Input() from a parent component use this new chart with it's selector

Body:
I am creating a dashboard and atleats 10 PIE charts are displayed on the page. Each PIE chart is different by some values only and remaining ALL other things are same.

Angular 7 + HighCharts I am using. Below is the code. If I try to use chart2 2 times in HTML, it appears only once. If I use a different variable for same code copy pasted, it works good.

How can I minimize code or reuse the same chart object by passing different values?

In the constructor let keyword is needed and outside constructor it works without using it

for 10 different PIE charts, all are differed by only series in the chart object. How one object can be used for all 10?.

@ Component({
 selector: 'app-chart',
 templateUrl: './chart.Component.html',
 styleUrls: ['./chart.Component.css'],
 providers: [LotoService],
})

export class ChartComponent implements OnInit {

constructor(private http: HttpClient) {

    let chart8: any;
    let chart2: any;

}

CP_A2A = 10;
CP_A2CA = 10;

ngOnInit() {}

chart2 = new Chart({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie',
            backgroundColor: '#fff',
            marginTop: 20,
            height: 300
        },
        credits: {
            enabled: false
        },
        title: {
            text: null,
            style: {
                color: '#858585',
                fontSize: '14px'
            }
        },
        tooltip: {
            pointFormat: '{point.y}'
        },
        series: [{
                type: 'pie',
                name: 'Share',
                data: [{
                        name: 'Approved',
                        y: 500
                    }, {
                        name: 'Conditionally Approved',
                        y: 300
                    }, {
                        name: 'Not Approved',
                        y: 200
                    }
                ]
            }
        ],
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: false,
                colors: ['#00366E', '#3693F8', '#C8E7FB'],
                center: ['50%', '37%']
            }
        },
    });

Body:
Quick Fix will be

You can actually keep the configuration in a default config variable, as below

defaultChartConfig = {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie',
            backgroundColor: '#fff',
            marginTop: 20,
            height: 300
        },
        credits: {
            enabled: false
        },
        title: {
            text: null,
            style: {
                color: '#858585',
                fontSize: '14px'
            }
        },
        tooltip: {
            pointFormat: '{point.y}'
        },
        series: [{
                type: 'pie',
                name: 'Share',
                data: [ ]
            }
        ],
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: false,
                colors: ['#00366E', '#3693F8', '#C8E7FB'],
                center: ['50%', '37%']
            }
        },
    }

then forEach chart you should reuse the config and change the data as below

for (i = 0; i < 10; i++) {
     const chart = new Chart(this. defaultChartConfig);
     chart.series.data = ____/// whatever data
     this.charts.push(chart)
}

use ngFor in the UI for displaying the charts

Better approach will be create a generic pie-chart component with a selector app-pie-chart using the highcharts and accept the series object as Input() from a parent component use this new chart with it's selector


问:
How to constrain two columns in SQL to have a value in one column only be allowed to appear in combination with the value in the other column?
I have two columns in a table:

- For one row all two columns need to be filled.

- In col1 any ID is allowed.

- In col2 a specific ID once set is only allowed to appear for further rows in combination with the ID in col1 when it was set for the first time.

Example:

```<code> col1 | col2
------|------
   1  |  1        OK
   1  |  1        OK
   1  |  2        OK
   2  |  3        OK
   2  |  1        NOK because 1 in col2 is already associated with 1 in col1.
   1  |  3        NOK because 3 in col2 is already associated with 2 in col1.
</code>```

I want to apply this rule to a table using a constraint. (Without having to use a second table)

Can someone help me? Thanks!

答:
As you want to allow only one col1 value per col2 value you need a col2 table:

```<code>create table tcol2
(
  col2 int,
  col1 int,
  primary key (col2)
);
</code>```

Then you could just add a count column to this table (so you'd have col1, col2, and counter instead of multiple rows per col1 and col2) or you use your existing table with a constraint:

```<code>alter table mytable add constraint
  fk_mytable_tcol2 foreign key (col1, col2) references tcol2 (col1, col2);
</code>```

Body:
I have two columns in a table:

- For one row all two columns need to be filled.

- In col1 any ID is allowed.

- In col2 a specific ID once set is only allowed to appear for further rows in combination with the ID in col1 when it was set for the first time.

Example:

 col1 | col2
------|------
   1  |  1        OK
   1  |  1        OK
   1  |  2        OK
   2  |  3        OK
   2  |  1        NOK because 1 in col2 is already associated with 1 in col1.
   1  |  3        NOK because 3 in col2 is already associated with 2 in col1.

I want to apply this rule to a table using a constraint. (Without having to use a second table)

Can someone help me? Thanks!

Body:
As you want to allow only one col1 value per col2 value you need a col2 table:

create table tcol2
(
  col2 int,
  col1 int,
  primary key (col2)
);

Then you could just add a count column to this table (so you'd have col1, col2, and counter instead of multiple rows per col1 and col2) or you use your existing table with a constraint:

alter table mytable add constraint
  fk_mytable_tcol2 foreign key (col1, col2) references tcol2 (col1, col2);


问:
Making a get request to a Discord text file to get the file contents
I am trying to get the contents of a text file through get requests however I am receiving a strange response with Greek letters and spaces between each character.

Link:

```<code>https://cdn.discordapp.com/attachments/651144916944027658/717426226255495208/my_file.txt
</code>```

Headers:

```<code>Content-Type: text/plain
</code>```

My text file contents:

```<code>123.456.789
</code>```

Response after doing the get request:

```<code>ÿþ1 2 3 . 4 5 6 . 7 8 9
</code>```

I'm not sure if there are some headers that I am missing but I can't seem to get this to work, I've tried in C# and Python and have received the same response each time.

答:
If the file is being attached to a message, you'll be able to save() it:

@bot.command()
async def savefile(ctx):
    await ctx.message.attachments[0].save("my_file.txt")
    await ctx.send("Saved the file!")
```

<p>You can also add checks for certain file extensions and such.<br>
If you want to save it with the same file name it was uploaded with:</p>

<pre class="lang-py prettyprint-override"><code>@bot.command()
async def savefile(ctx):
    attachment = ctx.message.attachments[0]
    # this will save it with the correct file extension
    await attachment.save(attachment.filename)
    await ctx.send("Saved the file!")
</code>```

References:

Message.attachments

Attachment.save()

Body:
I am trying to get the contents of a text file through get requests however I am receiving a strange response with Greek letters and spaces between each character.

Link:

https://cdn.discordapp.com/attachments/651144916944027658/717426226255495208/my_file.txt

Headers:

Content-Type: text/plain

My text file contents:

123.456.789

Response after doing the get request:

ÿþ1 2 3 . 4 5 6 . 7 8 9

I'm not sure if there are some headers that I am missing but I can't seem to get this to work, I've tried in C# and Python and have received the same response each time.

Body:
If the file is being attached to a message, you'll be able to save() it:

@bot.command()
async def savefile(ctx):
    await ctx.message.attachments[0].save("my_file.txt")
    await ctx.send("Saved the file!")

You can also add checks for certain file extensions and such.

If you want to save it with the same file name it was uploaded with:

@bot.command()
async def savefile(ctx):
    attachment = ctx.message.attachments[0]
    # this will save it with the correct file extension
    await attachment.save(attachment.filename)
    await ctx.send("Saved the file!")

References:

Message.attachments

Attachment.save()


问:
How to print this array elements in table format using ReactJS in Visual Studio Code Application
const people = [ { name: 'James', age: 31, }, { name: 'John', age: 45, }, { name: 'Paul', age: 65, }, { name: 'Ringo', age: 49, }, { name: 'George', age: 34, } ];</p>

答:
You can show json array to any sort of table. Here I provided an example using material-ui

Code Sandbox

Example:

```<code>import React from "react";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";

const rows = [
  { name: "James", age: 31 },
  { name: "John", age: 45 },
  { name: "Paul", age: 65 },
  { name: "Ringo", age: 49 },
  { name: "George", age: 34 }
];

export default function TableExample() {
  return (
    <TableContainer component={Paper}>
      <Table aria-label="simple table">
        <TableHead>
          <TableRow>
            <TableCell>Name</TableCell>
            <TableCell align="right">Age</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map(row => (
            <TableRow key={row.name}>
              <TableCell component="th" scope="row">
                {row.name}
              </TableCell>
              <TableCell align="right">{row.age}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
</code>```

Body:
You can show json array to any sort of table. Here I provided an example using material-ui

Code Sandbox

Example:

import React from "react";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";

const rows = [
  { name: "James", age: 31 },
  { name: "John", age: 45 },
  { name: "Paul", age: 65 },
  { name: "Ringo", age: 49 },
  { name: "George", age: 34 }
];

export default function TableExample() {
  return (
    <TableContainer component={Paper}>
      <Table aria-label="simple table">
        <TableHead>
          <TableRow>
            <TableCell>Name</TableCell>
            <TableCell align="right">Age</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map(row => (
            <TableRow key={row.name}>
              <TableCell component="th" scope="row">
                {row.name}
              </TableCell>
              <TableCell align="right">{row.age}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}


问:
Shadows clipped by ScrollView
Is there a way I can get shadows applied to an image to also show outside of the parent view? Below you can see a sample, where I list out some images in a ScrollView and HStack. The image/artwork has a shadow applied to it, but this gets clipped by the ScrollView.

Screenshot for reference:

```<code>ScrollView(.horizontal, showsIndicators: false) {
                                        HStack {
                                            ForEach(stationsFeed.items.sorted(by: { $0.updatedAt > $1.updatedAt }).prefix(15)) { item in

                                                NavigationLink(destination: StationDetailView(station: item)) {
                                                    VStack(alignment: .leading) {

                                                        if item.artwork != nil {
                                                            KFImage(self.artworkURLForStation(item)!)
                                                                .resizable()
                                                                .frame(width: 130, height: 130)
                                                                .scaledToFit()
                                                                .cornerRadius(6)
                                                                .shadow(radius: 5)
                                                        } else {
                                                            RoundedRectangle(cornerRadius: 6)
                                                                .background(Color.purple)
                                                                .shadow(radius: 5)
                                                        }

                                                        Text(item.name)
                                                            .font(.callout)
                                                            .foregroundColor(.primary)

                                                        Text(item.categories.first?.name ?? "N/A")
                                                            .font(.callout)
                                                            .foregroundColor(.secondary)
                                                    }
                                                    .frame(minWidth: 0, maxWidth: 130, alignment: .leading)
                                                }
                                                .buttonStyle(PlainButtonStyle())
                                            }
                                        }
                                    }
</code>```

答:
To make shadow uncut, add padding to HStack

```<code>ScrollView(.horizontal, showsIndicators: false) {
   HStack {
      ForEach(stationsFeed.items.sorted(by: { $0.updatedAt > $1.updatedAt }).prefix(15)) { item in
       // ... other code
   }.padding()        // << here !!
}
</code>```

Title: Shadows clipped by ScrollView

Body:
Is there a way I can get shadows applied to an image to also show outside of the parent view? Below you can see a sample, where I list out some images in a ScrollView and HStack. The image/artwork has a shadow applied to it, but this gets clipped by the ScrollView.

Screenshot for reference:

ScrollView(.horizontal, showsIndicators: false) {
                                        HStack {
                                            ForEach(stationsFeed.items.sorted(by: { $0.updatedAt > $1.updatedAt }).prefix(15)) { item in

                                                NavigationLink(destination: StationDetailView(station: item)) {
                                                    VStack(alignment: .leading) {

                                                        if item.artwork != nil {
                                                            KFImage(self.artworkURLForStation(item)!)
                                                                .resizable()
                                                                .frame(width: 130, height: 130)
                                                                .scaledToFit()
                                                                .cornerRadius(6)
                                                                .shadow(radius: 5)
                                                        } else {
                                                            RoundedRectangle(cornerRadius: 6)
                                                                .background(Color.purple)
                                                                .shadow(radius: 5)
                                                        }

                                                        Text(item.name)
                                                            .font(.callout)
                                                            .foregroundColor(.primary)

                                                        Text(item.categories.first?.name ?? "N/A")
                                                            .font(.callout)
                                                            .foregroundColor(.secondary)
                                                    }
                                                    .frame(minWidth: 0, maxWidth: 130, alignment: .leading)
                                                }
                                                .buttonStyle(PlainButtonStyle())
                                            }
                                        }
                                    }

Body:
To make shadow uncut, add padding to HStack

ScrollView(.horizontal, showsIndicators: false) {
   HStack {
      ForEach(stationsFeed.items.sorted(by: { $0.updatedAt > $1.updatedAt }).prefix(15)) { item in
       // ... other code
   }.padding()        // << here !!
}


问:
Trying to get property 'name' of non-object in Laravel (View: D:\...\resources\views\home.blade.php
I have this little problem here where the code isn't getting the proper form of the name I guess...
This is the place where it shows me a mistake:

```<code>                <div class="rank-label-container">
                    <span class="label label-default rank-label">{{$user ?? ''->name}}</span>
                </div>
</code>```

Someone tried to convince me that my mistake is here in the create_user_table:

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('avatar')->default('user.jpg');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
</code>```

But I didn't find any problem in here.
Any suggestions on how to fix it?
And if you need something else from the code tell me please, I didn't know what else should I give you so you can help me.
Thanks in advance!

答:
Try this, i sure it will work
{{$user->name}}
Or
{{$user['name']}}</p>

Body:
I have this little problem here where the code isn't getting the proper form of the name I guess...
This is the place where it shows me a mistake:

                    {{$user ?? ''->name}}

Someone tried to convince me that my mistake is here in the create_user_table:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('avatar')->default('user.jpg');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

But I didn't find any problem in here.
Any suggestions on how to fix it?
And if you need something else from the code tell me please, I didn't know what else should I give you so you can help me.
Thanks in advance!


问:
Get and Set a Single Cookie with Node.js HTTP Server
I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

```<code>var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');
</code>```

Just trying to take the above code directly from nodejs.org, and work a cookie into it.

答:
Let me repeat this part of question that answers here are ignoring:

Can it be done in a few lines of code, without the need to pull in a third party lib?

Reading Cookies

Cookies are read from requests with the Cookie header. They only include a name and value. Because of the way paths work, multiple cookies of the same name can be sent. In NodeJS, all Cookies in as one string as they are sent in the Cookie header. You split them with ;. Once you have a cookie, everything to the left of the equals (if present) is the name, and everything after is the value. Some browsers will accept a cookie with no equal sign and presume the name blank. Whitespaces do not count as part of the cookie. Values can also be wrapped in double quotes ("). Values can also contain =. For example, formula=5+3=8 is a valid cookie.

```<code>/**
 * @param {string} [cookieString='']
 * @return {[string,string][]} String Tuple
 */
function getEntriesFromCookie(cookieString = '') {
  return cookieString.split(';').map((pair) => {
    const indexOfEquals = pair.indexOf('=');
    let name;
    let value;
    if (indexOfEquals === -1) {
      name = '';
      value = pair.trim();
    } else {
      name = pair.substr(0, indexOfEquals).trim();
      value = pair.substr(indexOfEquals + 1).trim();
    }
    const firstQuote = value.indexOf('"');
    const lastQuote = value.lastIndexOf('"');
    if (firstQuote !== -1 && lastQuote !== -1) {
      value = value.substring(firstQuote + 1, lastQuote);
    }
    return [name, value];
  });
}

const cookieEntries = getEntriesFromCookie(request.headers.Cookie);
const object = Object.fromEntries(cookieEntries.slice().reverse());
</code>```

If you're not expecting duplicated names, then you can convert to an object which makes things easier. Then you can access like object.myCookieName to get the value. If you are expecting duplicates, then you want to do iterate through cookieEntries. Browsers feed cookies in descending priority, so reversing ensures the highest priority cookie appears in the object. (The .slice() is to avoid mutation of the array.)

Settings Cookies

"Writing" cookies is done by using the Set-Cookie header in your response. The response.headers['Set-Cookie'] object is actually an array, so you'll be pushing to it. It accepts a string but has more values than just name and value. The hardest part is writing the string, but this can be done in one line.

```<code>/**
 * @param {Object} options
 * @param {string} [options.name='']
 * @param {string} [options.value='']
 * @param {Date} [options.expires]
 * @param {number} [options.maxAge]
 * @param {string} [options.domain]
 * @param {string} [options.path]
 * @param {boolean} [options.secure]
 * @param {boolean} [options.httpOnly]
 * @param {'Strict'|'Lax'|'None'} [options.sameSite]
 * @return {string}
 */
function createSetCookie(options) {
  return (`${options.name || ''}=${options.value || ''}`)
    + (options.expires != null ? `; Expires=${options.expires.toUTCString()}` : '')
    + (options.maxAge != null ? `; Max-Age=${options.maxAge}` : '')
    + (options.domain != null ? `; Domain=${options.domain}` : '')
    + (options.path != null ? `; Path=${options.path}` : '')
    + (options.secure ? '; Secure' : '')
    + (options.httpOnly ? '; HttpOnly' : '')
    + (options.sameSite != null ? `; SameSite=${options.sameSite}` : '');
}

const newCookie = createSetCookie({
  name: 'cookieName',
  value: 'cookieValue',
  path:'/',
});
response.headers['Set-Cookie'].push(newCookie);
</code>```

Remember you can set multiple cookies, because you can actually set multiple Set-Cookie headers in your request. That's why it's an array.

Note on external libraries:

If you decide to use the express, cookie-parser, or cookie, note they have defaults that are non-standard. Cookies parsed are always URI Decoded (percent-decoded). That means if you use a name or value that has any of the following characters: !#$%&'()*+/:<=>?@[]^`{|} they will be handled differently with those libraries. If you're setting cookies, they are encoded with %{HEX}. And if you're reading a cookie you have to decode them.

For example, while email=name@domain.com is a valid cookie, these libraries will encode it as email=name%40domain.com. Decoding can exhibit issues if you are using the % in your cookie. It'll get mangled. For example, your cookie that was: secretagentlevel=50%007and50%006 becomes secretagentlevel=507and506. That's an edge case, but something to note if switching libraries.

Also, on these libraries, cookies are set with a default path=/ which means they are sent on every url request to the host.

If you want to encode or decode these values yourself, you can use encodeURIComponent or decodeURIComponent, respectively.

References:

Cookie Syntax

Set-Cookie Syntax

Additional information:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

ContentLicense: CC BY-SA 2.5

Body:
I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

Just trying to take the above code directly from nodejs.org, and work a cookie into it.

Body:
Let me repeat this part of question that answers here are ignoring:

Can it be done in a few lines of code, without the need to pull in a third party lib?

Reading Cookies

Cookies are read from requests with the Cookie header. They only include a name and value. Because of the way paths work, multiple cookies of the same name can be sent. In NodeJS, all Cookies in as one string as they are sent in the Cookie header. You split them with ;. Once you have a cookie, everything to the left of the equals (if present) is the name, and everything after is the value. Some browsers will accept a cookie with no equal sign and presume the name blank. Whitespaces do not count as part of the cookie. Values can also be wrapped in double quotes ("). Values can also contain =. For example, formula=5+3=8 is a valid cookie.

/**
 * @param {string} [cookieString='']
 * @return {[string,string][]} String Tuple
 */
function getEntriesFromCookie(cookieString = '') {
  return cookieString.split(';').map((pair) => {
    const indexOfEquals = pair.indexOf('=');
    let name;
    let value;
    if (indexOfEquals === -1) {
      name = '';
      value = pair.trim();
    } else {
      name = pair.substr(0, indexOfEquals).trim();
      value = pair.substr(indexOfEquals + 1).trim();
    }
    const firstQuote = value.indexOf('"');
    const lastQuote = value.lastIndexOf('"');
    if (firstQuote !== -1 && lastQuote !== -1) {
      value = value.substring(firstQuote + 1, lastQuote);
    }
    return [name, value];
  });
}

const cookieEntries = getEntriesFromCookie(request.headers.Cookie);
const object = Object.fromEntries(cookieEntries.slice().reverse());

If you're not expecting duplicated names, then you can convert to an object which makes things easier. Then you can access like object.myCookieName to get the value. If you are expecting duplicates, then you want to do iterate through cookieEntries. Browsers feed cookies in descending priority, so reversing ensures the highest priority cookie appears in the object. (The .slice() is to avoid mutation of the array.)

Settings Cookies

"Writing" cookies is done by using the Set-Cookie header in your response. The response.headers['Set-Cookie'] object is actually an array, so you'll be pushing to it. It accepts a string but has more values than just name and value. The hardest part is writing the string, but this can be done in one line.

/**
 * @param {Object} options
 * @param {string} [options.name='']
 * @param {string} [options.value='']
 * @param {Date} [options.expires]
 * @param {number} [options.maxAge]
 * @param {string} [options.domain]
 * @param {string} [options.path]
 * @param {boolean} [options.secure]
 * @param {boolean} [options.httpOnly]
 * @param {'Strict'|'Lax'|'None'} [options.sameSite]
 * @return {string}
 */
function createSetCookie(options) {
  return (`${options.name || ''}=${options.value || ''}`)
    + (options.expires != null ? `; Expires=${options.expires.toUTCString()}` : '')
    + (options.maxAge != null ? `; Max-Age=${options.maxAge}` : '')
    + (options.domain != null ? `; Domain=${options.domain}` : '')
    + (options.path != null ? `; Path=${options.path}` : '')
    + (options.secure ? '; Secure' : '')
    + (options.httpOnly ? '; HttpOnly' : '')
    + (options.sameSite != null ? `; SameSite=${options.sameSite}` : '');
}

const newCookie = createSetCookie({
  name: 'cookieName',
  value: 'cookieValue',
  path:'/',
});
response.headers['Set-Cookie'].push(newCookie);

Remember you can set multiple cookies, because you can actually set multiple Set-Cookie headers in your request. That's why it's an array.

Note on external libraries:

If you decide to use the express, cookie-parser, or cookie, note they have defaults that are non-standard. Cookies parsed are always URI Decoded (percent-decoded). That means if you use a name or value that has any of the following characters: !#$%&'()*+/:<=>?@[]^`{|} they will be handled differently with those libraries. If you're setting cookies, they are encoded with %{HEX}. And if you're reading a cookie you have to decode them.

For example, while email=name@domain.com is a valid cookie, these libraries will encode it as email=name%40domain.com. Decoding can exhibit issues if you are using the % in your cookie. It'll get mangled. For example, your cookie that was: secretagentlevel=50%007and50%006 becomes secretagentlevel=507and506. That's an edge case, but something to note if switching libraries.

Also, on these libraries, cookies are set with a default path=/ which means they are sent on every url request to the host.

If you want to encode or decode these values yourself, you can use encodeURIComponent or decodeURIComponent, respectively.

References:

Cookie Syntax

Set-Cookie Syntax

Additional information:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie


问:
filter for rows with n largest values for each group

Context

I want, for each team, the rows of the data frame that contains the top three scoring players.

In my head, it is a combination of Dataframe.nlargest() and Dataframe.groupby() but I don't think this is supported.
My ideal solution is:

performed directly on df without having to create other dataframes

legible, and

relatively performant (real df shape is 7M rows and 5 col)

Input

import pandas as pd
df = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"A","4":"A","5":"B","6":"B","7":"B","8":"B","9":"B","10":"C","11":"C","12":"C","13":"C","14":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Donna","4":"Elizabeth","5":"Fran","6":"Greta","7":"Heather","8":"Iris","9":"Jackie","10":"Kelly","11":"Lucy","12":"Molly","13":"Nina","14":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":8,"4":10,"5":28,"6":29,"7":18,"8":25,"9":9,"10":12,"11":23,"12":18,"13":10,"14":15}}')
```

```| team | player    | points |
|------|-----------|--------|
| A    | Alice     | 15     |
| A    | Becky     | 11     |
| A    | Carmen    | 13     |
| A    | Donna     | 8      |
| A    | Elizabeth | 10     |
| B    | Fran      | 28     |
| B    | Greta     | 29     |
| B    | Heather   | 18     |
| B    | Iris      | 25     |
| B    | Jackie    | 9      |
| C    | Kelly     | 12     |
| C    | Lucy      | 23     |
| C    | Molly     | 18     |
| C    | Nina      | 10     |
| C    | Ophelia   | 15     |
```

<h3>Desired Output</h3>

<pre class="lang-py prettyprint-override"><code>df_output = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"B","4":"B","5":"B","6":"C","7":"C","8":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Fran","4":"Greta","5":"Iris","6":"Lucy","7":"Molly","8":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":28,"4":29,"5":25,"6":23,"7":18,"8":15}}')
df_output
</code>```

```<code>| team | player  | points |
|------|---------|--------|
| A    | Alice   | 15     |
| A    | Becky   | 11     |
| A    | Carmen  | 13     |
| B    | Fran    | 28     |
| B    | Greta   | 29     |
| B    | Iris    | 25     |
| C    | Lucy    | 23     |
| C    | Molly   | 18     |
| C    | Ophelia | 15     |
</code>```

答:
You can use df.groupby with df.nlargest

```<code>df.groupby('team').apply(lambda x:x.nlargest(3,'points')).reset_index(drop=True)

  team   player  points
0    A    Alice      15
1    A   Carmen      13
2    A    Becky      11
3    B    Greta      29
4    B     Fran      28
5    B     Iris      25
6    C     Lucy      23
7    C    Molly      18
8    C  Ophelia      15
</code>```

Body:
Context

I want, for each team, the rows of the data frame that contains the top three scoring players.

In my head, it is a combination of Dataframe.nlargest() and Dataframe.groupby() but I don't think this is supported.
My ideal solution is:

performed directly on df without having to create other dataframes

legible, and

relatively performant (real df shape is 7M rows and 5 col)

Input

import pandas as pd
df = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"A","4":"A","5":"B","6":"B","7":"B","8":"B","9":"B","10":"C","11":"C","12":"C","13":"C","14":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Donna","4":"Elizabeth","5":"Fran","6":"Greta","7":"Heather","8":"Iris","9":"Jackie","10":"Kelly","11":"Lucy","12":"Molly","13":"Nina","14":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":8,"4":10,"5":28,"6":29,"7":18,"8":25,"9":9,"10":12,"11":23,"12":18,"13":10,"14":15}}')

| team | player    | points |
|------|-----------|--------|
| A    | Alice     | 15     |
| A    | Becky     | 11     |
| A    | Carmen    | 13     |
| A    | Donna     | 8      |
| A    | Elizabeth | 10     |
| B    | Fran      | 28     |
| B    | Greta     | 29     |
| B    | Heather   | 18     |
| B    | Iris      | 25     |
| B    | Jackie    | 9      |
| C    | Kelly     | 12     |
| C    | Lucy      | 23     |
| C    | Molly     | 18     |
| C    | Nina      | 10     |
| C    | Ophelia   | 15     |

Desired Output

df_output = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"B","4":"B","5":"B","6":"C","7":"C","8":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Fran","4":"Greta","5":"Iris","6":"Lucy","7":"Molly","8":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":28,"4":29,"5":25,"6":23,"7":18,"8":15}}')
df_output

| team | player  | points |
|------|---------|--------|
| A    | Alice   | 15     |
| A    | Becky   | 11     |
| A    | Carmen  | 13     |
| B    | Fran    | 28     |
| B    | Greta   | 29     |
| B    | Iris    | 25     |
| C    | Lucy    | 23     |
| C    | Molly   | 18     |
| C    | Ophelia | 15     |

Body:
You can use df.groupby with df.nlargest

df.groupby('team').apply(lambda x:x.nlargest(3,'points')).reset_index(drop=True)

  team   player  points
0    A    Alice      15
1    A   Carmen      13
2    A    Becky      11
3    B    Greta      29
4    B     Fran      28
5    B     Iris      25
6    C     Lucy      23
7    C    Molly      18
8    C  Ophelia      15


问:
Swift - Changing background color to transparent
I noticed one of my buttons has a value for the background color = 'default'

When the button is highlighted I want to change a different button to also have a 'default' background color, here is my code so far:

```<code>@IBAction func buttonTouchUpInside(_ sender: UIButton) {

    registerBtn.setTitleColor(UIColor.white, for: UIControlState.highlighted);
}
</code>```

How do I achieve this so registerBtn has a background color which is basically transparent?

答:
Use UIColor.clear to make a color transparent.

It is very confusing that Apple calls it "default" instead of "clear."

ContentLicense: CC BY-SA 3.0

Body:
I noticed one of my buttons has a value for the background color = 'default'

When the button is highlighted I want to change a different button to also have a 'default' background color, here is my code so far:

@IBAction func buttonTouchUpInside(_ sender: UIButton) {

    registerBtn.setTitleColor(UIColor.white, for: UIControlState.highlighted);
}

How do I achieve this so registerBtn has a background color which is basically transparent?


问:
Is there a way to detect if MS Visio, MS Word, or any MS Office app is installed on computer from IE & Chrome?
I have a SharePoint 2019 document library wherein I have a custom JavaScript code to open the MS documents (Word, Excel, Ppt, Visio) in the client application. I am using Office URI schemes for opening the documents in client apps. However, if there is no client application installed on the computer, the Office URI scheme fails without throwing up any error. I want to know if there is a way to check from the browser (IE and Chrome) if a particular MS application (Visio, Word, etc.) is installed on the computer.

P.S. I have tried the ActiveXObject approach, but for some reason, it didn't work for me and, also I want a solution that will be cross-browser compatible and afaik ActiveXObject is supported only on IE.

答: You can try using ActiveX technology to instantiate Office application as described on the detect microsoft office version using javascript thread. But Chrome is not aware of COM technology. So, any code for creating an Office application instance will fail.</p>


问:
Dockerized Python Project - Best way to manage dependencies: Dockerfile or requirements.txt
What is the best practice for handling dependencies of a dockerized python project? Would I declare all of them in the Dockerfile or in the requirements.txt?</p>

答:
The best way to handle the dependencies is using requirements.txt

Try this dockerfile

```<code>FROM python:3.8-slim-buster
COPY . /work
WORKDIR /work
RUN apt-get update
RUN apt-get upgrade -y
RUN pip install -r requirements.txt
</code>```

Body:
The best way to handle the dependencies is using requirements.txt

Try this dockerfile

FROM python:3.8-slim-buster
COPY . /work
WORKDIR /work
RUN apt-get update
RUN apt-get upgrade -y
RUN pip install -r requirements.txt


问:
Sharepoint custom web part property does not show up in the toolbox
I have defined a boolean property as follows:

```<code> [Browsable(true), Category("Display"), DefaultValue(false),
  WebPartStorage(Storage.Shared), FriendlyName("Obey Workflow"),
  Description("")]
  public bool ObeyWorkflow { get; set; }
</code>```

I'm expecting it to render as a checkbox in the webpart's properties toolbox, however it doesn't show up. My web part is derived from the Sharepoint WebPart base class.

答:
You are on the right track. You just need to use different attributes.</p>

```<code>[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[Category("Display")]
[WebDisplayName("Obey Workflow")]
[Description("")]
public bool ObeyWorkflow { get; set; }
</code>```

Body:
I have defined a boolean property as follows:

 [Browsable(true), Category("Display"), DefaultValue(false),
  WebPartStorage(Storage.Shared), FriendlyName("Obey Workflow"),
  Description("")]
  public bool ObeyWorkflow { get; set; }

I'm expecting it to render as a checkbox in the webpart's properties toolbox, however it doesn't show up. My web part is derived from the Sharepoint WebPart base class.

Body:
You are on the right track. You just need to use different attributes.

[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[Category("Display")]
[WebDisplayName("Obey Workflow")]
[Description("")]
public bool ObeyWorkflow { get; set; }

OwnerDisplayName: Rob Windsor - MVP


问:
How call validate before Devise sign in?
I would like to disable user's authorization where the date the account was created_at is in 2010.

How can I use callbacks for this task and how can I use it with Devise?

答:
Are you using the lockable strategy in Devise?

If so, in the controller that is redirected to after logging in, you can add a before_filter that does something like this:

current_user.lock_access! if current_user && current_user.created_at.year == "2010"
```

<p>And you also need to manually sign the user out, possibly with something like this:</p>

<pre class="lang-rb prettyprint-override"><code>sign_out current_user
</code>```

Body:
Are you using the lockable strategy in Devise?

If so, in the controller that is redirected to after logging in, you can add a before_filter that does something like this:

current_user.lock_access! if current_user && current_user.created_at.year == "2010"

And you also need to manually sign the user out, possibly with something like this:

sign_out current_user


问:
How do I check if an input is in fact in a column in pandas?
Example of the dataFrame:

```<code>df = {'column': 'hello'}
</code>```

The input should be an entry in the dataFrame

```<code>if 'hello' in df['column']:
   print("hello")
else:
  print("Couldn't find entry)
</code>```

What I would want as the output would be:

```<code>Hello
</code>```

However, the output comes out as:

```<code>Couldn't find entry
</code>```

I've checked and the value entered in the input is definitely inside that column of the dataFrame
I don't know if im doing anything incorrectly or why it is not working

答:
Try this and comment whether it gives the correct output</p>

```<code>df = {'column': 'hello'}
if 'hello' == df['column']:
   print("hello")
else:
  print("Couldn't find entry")
</code>```

Body:
Example of the dataFrame:

df = {'column': 'hello'}

The input should be an entry in the dataFrame

if 'hello' in df['column']:
   print("hello")
else:
  print("Couldn't find entry)

What I would want as the output would be:

Hello

However, the output comes out as:

Couldn't find entry

I've checked and the value entered in the input is definitely inside that column of the dataFrame
I don't know if im doing anything incorrectly or why it is not working

Body:
Try this and comment whether it gives the correct output

df = {'column': 'hello'}
if 'hello' == df['column']:
   print("hello")
else:
  print("Couldn't find entry")


问:
Change console print color in python 3.8 with ANSI escape codes (Windows)
I'm trying to print colored code in the python shell with ANSI escape codes.
My code looks like this:

```<code>print("\033[031m" + "Hello" + "\033[0m")
</code>```

When I run the code in Visual Studio Code it works perfectly fine but if I open it directly in Python 3.8 my output is:[031mHello[0m

答:
try to use colorama:</p>

```<code>from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
</code>```

Body:
I'm trying to print colored code in the python shell with ANSI escape codes.
My code looks like this:

print("\033[031m" + "Hello" + "\033[0m")

When I run the code in Visual Studio Code it works perfectly fine but if I open it directly in Python 3.8 my output is:[031mHello[0m

Body:
try to use colorama:

from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')