答:
Perl to the rescue!

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

sub output {
    my ($cluster, @buffer) = @_;
    for my $line (@buffer) {
        say join "\t", $cluster, @$line;
    }
}

my $cluster = "";
my @buffer;

while (<>) {
    my ($chromosome, $start, $stop, $strand, $position, $coverage) = split;
    if ($chromosome ne $cluster) {
        output($cluster, @buffer) if @buffer;
        @buffer = ([$start, $stop, $strand, $position, $coverage]);
        $cluster = $chromosome;
    } elsif ($coverage >= $buffer[-1][-1]) {
        @buffer = () if $coverage > $buffer[-1][-1];
        push @buffer, [$start, $stop, $strand, $position, $coverage];
    }
}

# Don't forget to output the last accumulated cluster!
output($cluster, @buffer);
```

It reads the input line by line. It stores the lines with the maximal coverage in a buffer: if the next line has a greater coverage, it will clear the buffer, if it's less, it's skipped (if coverage can oscillate, the code is wrong!) Once a new cluster starts, the previous one is printed.

Title: Collapsing duplicate lines using scores in particular column

Body:
I have a file that looks like this:

chr1    74347681    74347709    +   1   11
chr1    74347681    74347709    +   2   12
chr1    74347681    74347709    +   3   12
chr1    74347681    74347709    +   4   12
chr1    74347681    74347709    +   5   14
chr1    74347681    74347709    +   6   14
chr1    74347681    74347709    +   7   14
chr1    74347681    74347709    +   8   14
chr1    74347681    74347709    +   9   14
chr1    74347681    74347709    +   10  14
chr1    74347681    74347709    +   11  14
chr1    74347681    74347709    +   12  14
chr1    74347681    74347709    +   13  14
chr1    74347681    74347709    +   14  14
chr1    74347681    74347709    +   15  14
chr1    74347681    74347709    +   16  14
chr1    74347681    74347709    +   17  14
chr1    74347681    74347709    +   18  14
chr1    74347681    74347709    +   19  14
chr1    74347681    74347709    +   20  14
chr1    74347681    74347709    +   21  14
chr1    74347681    74347709    +   22  14
chr1    74347681    74347709    +   23  14
chr1    74347681    74347709    +   24  13
chr1    74347681    74347709    +   25  12
chr1    74347681    74347709    +   26  10
chr1    74347681    74347709    +   27  10
chr1    74347681    74347709    +   28  10
chr11   32284342    32284363    +   1   10
chr11   32284342    32284363    +   2   10
chr11   32284342    32284363    +   3   10
chr11   32284342    32284363    +   4   10
chr11   32284342    32284363    +   5   10
chr11   32284342    32284363    +   6   10
chr11   32284342    32284363    +   7   10
chr11   32284342    32284363    +   8   11
chr11   32284342    32284363    +   9   11
chr11   32284342    32284363    +   10  11
chr11   32284342    32284363    +   11  11
chr11   32284342    32284363    +   12  11
chr11   32284342    32284363    +   13  11
chr11   32284342    32284363    +   14  11
chr11   32284342    32284363    +   15  11
chr11   32284342    32284363    +   16  11
chr11   32284342    32284363    +   17  11
chr11   32284342    32284363    +   18  11
chr11   32284342    32284363    +   19  11
chr11   32284342    32284363    +   20  10
chr11   32284342    32284363    +   21  10

Where the columns represent

chromosome   start   stop   strand   position   coverage

I would like to collapse the file so that I have the coordinates of the maximum coverage for each cluster. The maximum coverage for the first cluster (chr1    74347681    74347709    +) is 14 and the maximum coverage of the second cluster (chr11    32284342    32284363    +) is 11:

chr1    74347681    74347709    +   5   14
chr1    74347681    74347709    +   6   14
chr1    74347681    74347709    +   7   14
chr1    74347681    74347709    +   8   14
chr1    74347681    74347709    +   9   14
chr1    74347681    74347709    +   10  14
chr1    74347681    74347709    +   11  14
chr1    74347681    74347709    +   12  14
chr1    74347681    74347709    +   13  14
chr1    74347681    74347709    +   14  14
chr1    74347681    74347709    +   15  14
chr1    74347681    74347709    +   16  14
chr1    74347681    74347709    +   17  14
chr1    74347681    74347709    +   18  14
chr1    74347681    74347709    +   19  14
chr1    74347681    74347709    +   20  14
chr1    74347681    74347709    +   21  14
chr1    74347681    74347709    +   22  14
chr1    74347681    74347709    +   23  14
chr11   32284342    32284363    +   8   11
chr11   32284342    32284363    +   9   11
chr11   32284342    32284363    +   10  11
chr11   32284342    32284363    +   11  11
chr11   32284342    32284363    +   12  11
chr11   32284342    32284363    +   13  11
chr11   32284342    32284363    +   14  11
chr11   32284342    32284363    +   15  11
chr11   32284342    32284363    +   16  11
chr11   32284342    32284363    +   17  11
chr11   32284342    32284363    +   18  11
chr11   32284342    32284363    +   19  11

So the maximum coverage for the first cluster starts at position 5 and ends at position 23 and for the second cluster it starts at position 8 and ends at position 19. How do I get a final output of:

chr1    74347685    74347703    +
chr11   32284349    32284360    +

The start position is position 1 so you are really adding (5-1) and (23-1) to the start position for the first cluster and adding (8-1) and (19-1) to the start position of the second cluster.

I could only think to start by sorting the file using:

sort -k1,1 -k2,2n -k6,6nr -k5,5n

Previously, I had then taken a list of unique clusters (columns 1-4) and used a for loop to one-by-one add the positions of maximum coverage to the original start positions of the cluster but this takes a very long time. I was wondering if there is a way to do it in the file without processing it line-by-line.

Body:
Perl to the rescue!

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

sub output {
    my ($cluster, @buffer) = @_;
    for my $line (@buffer) {
        say join "\t", $cluster, @$line;
    }
}

my $cluster = "";
my @buffer;

while (<>) {
    my ($chromosome, $start, $stop, $strand, $position, $coverage) = split;
    if ($chromosome ne $cluster) {
        output($cluster, @buffer) if @buffer;
        @buffer = ([$start, $stop, $strand, $position, $coverage]);
        $cluster = $chromosome;
    } elsif ($coverage >= $buffer[-1][-1]) {
        @buffer = () if $coverage > $buffer[-1][-1];
        push @buffer, [$start, $stop, $strand, $position, $coverage];
    }
}

# Don't forget to output the last accumulated cluster!
output($cluster, @buffer);

It reads the input line by line. It stores the lines with the maximal coverage in a buffer: if the next line has a greater coverage, it will clear the buffer, if it's less, it's skipped (if coverage can oscillate, the code is wrong!) Once a new cluster starts, the previous one is printed.


来源: stackexchange

问:
Building opencv from source in Mac m1
I'm using the following Make to build OpenCV from source,

```<code> cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
  -D OPENCV_EXTRA_MODULES_PATH=/Users/Tools/opencv_contrib/modules \
  -D PYTHON3_EXECUTABLE=/miniforge/base/envs/envname/bin/python3 \
    -D BUILD_opencv_python2=OFF \
    -D BUILD_opencv_python3=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D WITH_TBB=ON \
    -D WITH_V4L=ON \
    -D INSTALL_C_EXAMPLES=OFF \
    -D OPENCV_ENABLE_NONFREE=ON \
    -D WITH_OPENGL=ON \
     -DBUILD_ZLIB=OFF \
  -D OPENCV_EXTRA_MODULES_PATH=/Users/Tools/opencv_contrib/modules \
    -D BUILD_EXAMPLES=ON ..
</code>```

Unfortunately it doesn't build. It throws the following error,

```<code>: error: unknown type name 'AVBSFContext'; did you mean 'AVIOContext'?
</code>```

I have of course installed FFmpeg. what am I still missing?

答:
I think that you've installed ffmpeg 5 and OpenCV is not yet compatible with it. Please try the following:

```<code>brew install ffmpeg@4
brew unlink ffmpeg
brew link ffmpeg@4
</code>```

and then recompile OpenCV again.

ContentLicense: CC BY-SA 4.0

Title: Building opencv from source in Mac m1

Body:
I'm using the following Make to build OpenCV from source,

 cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
  -D OPENCV_EXTRA_MODULES_PATH=/Users/Tools/opencv_contrib/modules \
  -D PYTHON3_EXECUTABLE=/miniforge/base/envs/envname/bin/python3 \
    -D BUILD_opencv_python2=OFF \
    -D BUILD_opencv_python3=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D WITH_TBB=ON \
    -D WITH_V4L=ON \
    -D INSTALL_C_EXAMPLES=OFF \
    -D OPENCV_ENABLE_NONFREE=ON \
    -D WITH_OPENGL=ON \
     -DBUILD_ZLIB=OFF \
  -D OPENCV_EXTRA_MODULES_PATH=/Users/Tools/opencv_contrib/modules \
    -D BUILD_EXAMPLES=ON ..

Unfortunately it doesn't build. It throws the following error,

: error: unknown type name 'AVBSFContext'; did you mean 'AVIOContext'?

I have of course installed FFmpeg. what am I still missing?

Body:
I think that you've installed ffmpeg 5 and OpenCV is not yet compatible with it. Please try the following:

brew install ffmpeg@4
brew unlink ffmpeg
brew link ffmpeg@4

and then recompile OpenCV again.


问:
<Link to=> not switching pages
I've been working on this dropdown menu for a while but I can't seem to get the dropdown menu to change the page I'm on and I don't understand what's wrong with it I am really new to ReactJs, I have a module called DropDownMenu it is calling DropDownItem and when DropDownItem is clicked is called a function called handle click but in the HandleClick it is not switching the page to the current Props.Route clicked on and i don't know enough of whats going on to really figure it out

```<code>import React from "react";
import { Link } from "react-router-dom";

function DropdownItem(props) {
  const handleClick = () => {
    <Link to={props.route}></Link>;
    console.log(props.route);
  };

  return (
    <a href="#" className="menu-item" onClick={handleClick}>
      <span className="icon-button">{props.leftIcon}</span>
      <span className="Route">{props.route}</span>

      {props.children}
      <span className="icon-right">{props.rightIcon}</span>
    </a>
  );
}

export default DropdownItem;
</code>```

答:
You can't just throw a <Link> in the middle of a callback function and expect it to do anything when called.

Use the <Link> element instead of the  element.

Make use of useNavigate if you need to trigger navigation from a callback (which you don't in this case).

Title: <Link to=> not switching pages

Body:
I've been working on this dropdown menu for a while but I can't seem to get the dropdown menu to change the page I'm on and I don't understand what's wrong with it I am really new to ReactJs, I have a module called DropDownMenu it is calling DropDownItem and when DropDownItem is clicked is called a function called handle click but in the HandleClick it is not switching the page to the current Props.Route clicked on and i don't know enough of whats going on to really figure it out

import React from "react";
import { Link } from "react-router-dom";

function DropdownItem(props) {
  const handleClick = () => {
    <Link to={props.route}></Link>;
    console.log(props.route);
  };

  return (

      {props.leftIcon}
      {props.route}

      {props.children}
      {props.rightIcon}

  );
}

export default DropdownItem;

Body:
You can't just throw a <Link> in the middle of a callback function and expect it to do anything when called.

Use the <Link> element instead of the <a> element.

Make use of useNavigate if you need to trigger navigation from a callback (which you don't in this case).


问:
ARM inline assembly, registers are read in an incorrect order
I am trying to read ARM registers via C using inline assembly but it doesn't follow the order of execution as it should.

```<code>volatile uint32_t var1 = 0;
volatile uint32_t var2 = 0;
volatile uint32_t var3 = 0;
volatile uint32_t var4 = 0;

__asm volatile(
    "mov r0, #5\n\t"
    "mov r1, #6\n\t"
    "mov r2, #7\n\t"
    "mov r3, #8\n\t"

    "mov %0, r0\n\t"
    "mov %0, r1\n\t"
    "mov %0, r2\n\t"
    "mov %0, r3\n\t"

    : "=r" (var1),
    "=r" (var2),
    "=r" (var3),
    "=r" (var4));
</code>```

What happens is that the output is;

```<code>var1 = 8
var2 = 5
var3 = 6
var4 = 7
</code>```

What I expect is;

```<code>var1 = 5
var2 = 6
var3 = 7
var4 = 8
</code>```

It seems r0 is read last and it starts with r1. Why is that happening?

Note: Ignore the purpose of the code or how variables are defined, it's a copy/paste from a bigger application. It's just this specific register behavior in question.

答:
The arguments passed into the inline assembly need to be incremented;</p>
```<code>"mov %0, r0\n\t"
"mov %1, r1\n\t"
"mov %2, r2\n\t"
"mov %3, r3\n\t"
</code>```

Body:
I am trying to read ARM registers via C using inline assembly but it doesn't follow the order of execution as it should.

volatile uint32_t var1 = 0;
volatile uint32_t var2 = 0;
volatile uint32_t var3 = 0;
volatile uint32_t var4 = 0;

__asm volatile(
    "mov r0, #5\n\t"
    "mov r1, #6\n\t"
    "mov r2, #7\n\t"
    "mov r3, #8\n\t"

    "mov %0, r0\n\t"
    "mov %0, r1\n\t"
    "mov %0, r2\n\t"
    "mov %0, r3\n\t"

    : "=r" (var1),
    "=r" (var2),
    "=r" (var3),
    "=r" (var4));

What happens is that the output is;

var1 = 8
var2 = 5
var3 = 6
var4 = 7

What I expect is;

var1 = 5
var2 = 6
var3 = 7
var4 = 8

It seems r0 is read last and it starts with r1. Why is that happening?

Note: Ignore the purpose of the code or how variables are defined, it's a copy/paste from a bigger application. It's just this specific register behavior in question.

Body:
The arguments passed into the inline assembly need to be incremented;

"mov %0, r0\n\t"
"mov %1, r1\n\t"
"mov %2, r2\n\t"
"mov %3, r3\n\t"


问:
How to compare individual properties of an array of objects

I have a single array of objects.

The objects are different variations of this:

```<code>{
    "animals": {
        "name": "elephant",
        "diet": "herbivore",
        "color": "spotted",
        "age": "12",
        "numbers": ["11", "10", "24", "9"]
    }
}
</code>```

How to iterate through the collection and determine if there are differences between the "numbers" properties or "diet" properties? As in:

In the array, 50 elephant object's "diet" property read "herbivore", but one it reads "omnivore". Break out because it's different and report it.

Or as in:

In the array, 70 elephant object's "numbers" property are the same (even if some are out of order). Report they are the same.

What did I try?:

Stringifying the objects and comparing them, but that won't work because I'm not trying to compare whole objects (just a few individual properties).

I can make this work with a for loop, but it seems stupid overkill and not very efficient for a collection that potentially has hundreds of objects in it.

This is pseudo code, don't freak out:

```<code>var isValid = true;

//go through each element in the array
for(let i = 0, i < array.length, i++) {
    //check if you have exceeded length of the array
    if(i + 1 <= array.length) {

        //sort the numbers
        var sortedLowerNumbers = sortFunction(array[i].numbers);
        var sortedhigherNumbers = sortFunction(array[i+1].numbers);
        //compare equality
       isValid = json.stringify(sortedLowerNumbers) === json.stringify(sortedhigherNumbers);

       if(!isValid) {
         break
       }
    }
}
</code>```

My research

None of the questions seem applicable. They're seem to be either comparing multiple arrays rather than one or comparing entire JSON objects for equality rather than comparing individual properties.

Is there a smarter way to do this?

答:
Although a for loop is the best and most simple way to do it. if you are looking for brevity you can use .every():

let arr = [{
        name: "elephant",
        diet: "herbivore",
        color: "spotted",
        age: "12",
       numbers: ["11", "10", "24","9"]
},{             name: "elephant",
        diet: "herbivore",
        color: "spotted",
        age: "12",
       numbers: ["11", "10", "24","9"]
},{
                name: "elephant",
        diet: "herbivore",
        color: "spotted",
        age: "12",
       numbers: ["11", "10", "24","9" , "23"]
}];
let arrSort = arr[0].numbers.sort();
let JSONarrSort = JSON.stringify(arrSort);
console.log(arr.every(x => JSON.stringify(x.numbers.sort()) === JSONarrSort));
console.log(arr.every(x => x.diet === arr[0].diet));```

Body:
I have a single array of objects.

The objects are different variations of this:

{
    "animals": {
        "name": "elephant",
        "diet": "herbivore",
        "color": "spotted",
        "age": "12",
        "numbers": ["11", "10", "24", "9"]
    }
}

How to iterate through the collection and determine if there are differences between the "numbers" properties or "diet" properties? As in:

In the array, 50 elephant object's "diet" property read "herbivore", but one it reads "omnivore". Break out because it's different and report it.

Or as in:

In the array, 70 elephant object's "numbers" property are the same (even if some are out of order). Report they are the same.

What did I try?:

Stringifying the objects and comparing them, but that won't work because I'm not trying to compare whole objects (just a few individual properties).

I can make this work with a for loop, but it seems stupid overkill and not very efficient for a collection that potentially has hundreds of objects in it.

This is pseudo code, don't freak out:

var isValid = true;

//go through each element in the array
for(let i = 0, i < array.length, i++) {
    //check if you have exceeded length of the array
    if(i + 1 <= array.length) {

        //sort the numbers
        var sortedLowerNumbers = sortFunction(array[i].numbers);
        var sortedhigherNumbers = sortFunction(array[i+1].numbers);
        //compare equality
       isValid = json.stringify(sortedLowerNumbers) === json.stringify(sortedhigherNumbers);

       if(!isValid) {
         break
       }
    }
}

My research

None of the questions seem applicable. They're seem to be either comparing multiple arrays rather than one or comparing entire JSON objects for equality rather than comparing individual properties.

Is there a smarter way to do this?


问:
Django No Reverse Match Error - Nothing is working
When rendering a new page, the html form action on that new page is stopping the page from being rendered... even though it has nothing to do with the page itself being rendered (if I remove that one line of HTML code, the page loads just fine). I've been working on solving this problem for over 3 days, tried hundreds of possible solutions, nothing works. Please help

This is the error:

```<code>NoReverseMatch at /newgallery/rodneyadmin
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Request Method: GET
Request URL:    http://127.0.0.1:8000/newgallery/rodneyadmin
Django Version: 4.0
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/urls/resolvers.py, line 729, in _reverse_with_prefix
Python Executable:  /Library/Frameworks/Python.framework/Versions/3.9/bin/python3
Python Version: 3.9.7
Python Path:
['/Users/rodneyrussell/Desktop/github/Capstone/Capstone',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
 '/Users/rodneyrussell/Library/Python/3.9/lib/python/site-packages',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']
Server time:    Thu, 10 Feb 2022 16:41:21 -0500
Error during template rendering

In template /Users/rodneyrussell/Desktop/github/Capstone/Capstone/templates/galleries/newgallery.html, error at line 21
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
11        Create new gallery
12      </h1>
13    </div>
14  </div>
15
16
17  <div class="row mb-3 d-flex justify-content-center">
18
19      <div class="col-lg-4 col-med-8 col-sm-8 text-primary" style="height: fit-content;">
20
21        <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
22
23          {% csrf_token %}
24
25
26          <div class="form-group mb-5">
27            <label style="margin-right: 20px;">Public Gallery</label>
28            {{form.public_gallery}}
29        </div>
30
31          <div class="form-group mb-5">
</code>```

This is the line of code being highlighted as cause for error (form action):

```<code><form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
</code>```

Views.py:

```<code>@login_required
def newgallery(request, username):

    if request.method == 'GET':

        form = NewGalleryForm

        context = {
        'form': form,
        'username': username,
        }

        return render(request, 'galleries/newgallery.html', context)

def editgallery(request, username):

    if request.method == "POST":

        form = NewGalleryForm(request.POST)

        if form.is_valid():

            new_gallery = form.save(commit = False)
            ## connect the new gallery with the user (foreign key)
            new_gallery.user = request.user
            new_gallery.save()
            url = "https://api.opensea.io/api/v1/assets?order_direction=desc&offset=0&limit=5"

            params={'owner': new_gallery.wallett_address}
            headers = {
                "Accept": "application/json",
                "X-API-KEY": ""
            }
            response = requests.request("GET", url, headers=headers, params=params)
            response = response.json()["assets"]

            list_of_nfts =  []
            for dictionary in response:
                token_id = dictionary["token_id"]
                token_address = dictionary["asset_contract"]["address"]
                contract_address = 'https://api.opensea.io/api/v1/asset/' + token_address + '/' + token_id + '/'
                name = dictionary["name"]
                if len(name) > 50:
                    name = (name[:50] + '...')
                nft_created_date = dictionary["asset_contract"]["created_date"]
                nft_created_date = nft_created_date[:10]
                nft_created_date = datetime.strptime(nft_created_date, '%Y-%m-%d').strftime('%m/%d/%Y')
                image = dictionary["image_url"]
                description = dictionary["description"]
                if description is not None and '*' in description:
                    head, sep, tail = description.partition('*')
                    description = head
                if description is not None and len(description) > 50:
                    description = (description[:150] + '...')
                if isinstance(description, str) != True:
                    description = 'No description provided'
                link = dictionary["permalink"]
                nft_dict = {
                'contract_address': contract_address,
                'name': name,
                'image': image,
                'description': description,
                'link': link,
                'nft_created_date': nft_created_date,
                }
                list_of_nfts.append(nft_dict)

            context = {
            'new_gallery': new_gallery,
            'list_of_nfts': list_of_nfts,
            'raw_nft_data': json.dumps(list_of_nfts),
            'new_gallery_name': new_gallery.gallery_name,
            'user': new_gallery.user,
            username:username,
            }

            return render(request, 'galleries/editgallery.html', context)
</code>```

New Gallery HTML (page where user enters basic information regarding New Gallery that he or she is creating... when this form is submitted, the user is brought to a page where they can edit the gallery that was just created (by edit, I mean add new NFT's to that gallery):

```<code>
<div class="row mb-3">
  <div class="col-lg-12 col-sm-12 text-primary  d-flex justify-content-center align-items-center">
    <h1
      class="homepagetitle mt-4 mb-5"
      style="font-size: 2.4rem; color: rgb(231, 114, 208)"
    >
      Create new gallery
    </h1>
  </div>
</div>

<div class="row mb-3 d-flex justify-content-center">

    <div class="col-lg-4 col-med-8 col-sm-8 text-primary" style="height: fit-content;">

      <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>

        {% csrf_token %}

        <div class="form-group mb-5">
          <label style="margin-right: 20px;">Public Gallery</label>
          {{form.public_gallery}}
      </div>

        <div class="form-group mb-5">
            <label>Gallery Name </label>
            {{form.gallery_name}}
        </div>

        <div class="form-group mb-5">

          <label>Wallett Address</label>

          <span class="hovertext" style="color: rgb(231, 114, 208); font-weight: normal;" data-hover="You will be adding NFT's from this wallet. Max wallet size: 50 NFT's">?</span>
          {{form.wallett_address}}
      </div>

        <div class="form-group mb-5">
            <label style="margin-right: 20px;">Category </label>
            {{form.gallery_category}}
        </div>

          <button
          type="submit"
          class="btn btn-dark mt-4 mb-4"

          style="
          font-size: 1.1rem;
            height: 50px;
            width:fit-content;
          "
        >
          Add NFT's &nbsp <i class="far fa-arrow-alt-circle-right"></i>
        </button>

    </form>

</div>

</div>

</code>```

User Profile HTML (page where user clicks on an a tag to bring them to the the New Gallery HTML (the other HTML I have listed above). That is when the code breaks and gives that error. The url in that a tag is href="{% url 'gallery_app:newgallery' user.username %}":

```<code><h1 class="homepagetitle mt-4 mb-5 d-flex justify-content-center align-items-center" style="font-size: 2.4rem; color: rgb(231, 114, 208);">
  Hello&nbsp
  <span style="font-size: 2.4rem; color: rgb(231, 114, 208);"
    >{{user.username}}&nbsp<i class="far fa-hand-paper" style="font-size: 2.4rem; color: rgb(231, 114, 208);"></i></span
  >
</h1>
{% endif %}

<div class="row col-12">
  <div class="col-lg-6">
    <div class="pt-3 profile-image">
      <img
        src="{% static user.avatar.url %}"
        alt="{{user.username}}'s avatar"
        class="rounded-circle shadow"
        height="300"
        width="275"
      />
    </div>
    {% if request.user == user %}
    <span>
      <div class="editicon">
        <a
          href="{% url 'users_app:update' user.username %}"
          style="
            color: rgb(226, 81, 197);
            -webkit-text-stroke: 1px black;
            text-decoration: none;
          "
        >
          <i class="fas fa-user-edit"></i>
        </a>
      </div>
    </span>
    {% endif %}

    <!-- 'users_app:update' user.username -->

    <table class="table profile-margin">
      <tbody>
        {% if request.user == user %}
        <tr>
          <th scope="row"></th>
          <td>Name:</td>
          <td>{{user.first_name}} {{user.last_name}}</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Email:</td>
          <td>{{user.email}}</td>
        </tr>
        {% endif %}
        <tr>
          <th scope="row"></th>
          <td>Username:</td>
          <td>{{user.username}}</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Profile created:</td>
          <td>{{user.date_joined|date}}</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Galleries:</td>
          <td>0</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Followers:</td>
          <td>0</td>
        </tr>

        <tr>
          <th scope="row"></th>
          <td>Following:</td>
          <td>0</td>
        </tr>
      </tbody>
    </table>
  </div>

  <div class="col-lg-6">
    {% if request.user.is_authenticated %}

      <h3 class=" d-flex homepagetitle" style="justify-content:center; margin-top: 30px; margin-bottom: 0px; padding:10px; height: 75px; font-size: 2.2rem; color: rgb(231, 114, 208);">
        <i><a class="homepagetitle far fa-plus-square" href="{% url 'gallery_app:newgallery' user.username %}" style="text-decoration: none; font-size: 2.2rem; color: rgb(231, 114, 208); position:relative; left: -70px; font-size: 2rem;"></i></a>
           Your Galleries:
      </h3>

    {% else %}
    <h3 class=" d-flex justify-content-center homepagetitle" style="margin-top: 30px; margin-bottom: 0px; padding:10px; height: 75px; font-size: 2.2rem; color: rgb(231, 114, 208);">
        {{user.username}}'s Galleries:
    </h3>

    {% endif %}

    <div class='user-galleries d-flex justify-content-center'  style="background-color: rgb(247, 229, 243); border-radius: 8px;">

      <div class="gallery-posts py-3">
        <table class="table profile-margin" style="color:rgb(231, 114, 208); font-weight: bolder;">
          <tbody>

    {% for gallery in user.newgallery.all %}

    <tr>
      <th scope="row"></th>
      <td>{{ gallery.gallery_name }}</td>
      <td>NFT's: 0</td>
    </tr>

    {% endfor %}

      </tbody>
        </table>
      </div>

      </div>

    </div>

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

Urls.py:

```<code>app_name = 'gallery_app'

urlpatterns = [
    path('newgallery/<str:username>', views.newgallery, name='newgallery'),
    path('editgallery/<str:username>/<int:gallery_id>', views.editgallery, name='editgallery'),
    path('galleryview/<str:username>/<int:gallery_id>', views.galleryview, name='galleryview'),
]
</code>```

答:
It looks like the url argument new_gallery.id is empty when you render the html template.

update: so the template is called from view newgallery.

In your original code there is 2 things to change:

to instantiate the form please add () after NewGalleryForm. Without you just handover a link to the class.

in this view/template you do not yet have an instance of newgallery (just the form). So you can not use newgaller.id. Implement a POST branch in newgallery to save it and remove newgallery.id from the form action and point the action back to newgallery view.

after saving you have a newgallery instance with an id and you can call the edit view if you need to with newgallery in the context

```<code>def newgallery(request, username):
    if request.method == 'POST':
       # save newgallery here

    if request.method == 'GET':

        form = NewGalleryForm()

        context = {
        'form': form,
        'username': username,
        }

        return render(request, 'galleries/newgallery.html', context)
</code>```
```<code><form action="{% url 'gallery_app:newgallery' user.username %} " style .... >
</code>```

Body:
When rendering a new page, the html form action on that new page is stopping the page from being rendered... even though it has nothing to do with the page itself being rendered (if I remove that one line of HTML code, the page loads just fine). I've been working on solving this problem for over 3 days, tried hundreds of possible solutions, nothing works. Please help

This is the error:

NoReverseMatch at /newgallery/rodneyadmin
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Request Method: GET
Request URL:    http://127.0.0.1:8000/newgallery/rodneyadmin
Django Version: 4.0
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/urls/resolvers.py, line 729, in _reverse_with_prefix
Python Executable:  /Library/Frameworks/Python.framework/Versions/3.9/bin/python3
Python Version: 3.9.7
Python Path:
['/Users/rodneyrussell/Desktop/github/Capstone/Capstone',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
 '/Users/rodneyrussell/Library/Python/3.9/lib/python/site-packages',
 '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']
Server time:    Thu, 10 Feb 2022 16:41:21 -0500
Error during template rendering

In template /Users/rodneyrussell/Desktop/github/Capstone/Capstone/templates/galleries/newgallery.html, error at line 21
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
11        Create new gallery
12

13

14

15
16
17

18
19

20
21        <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
22
23          {% csrf_token %}
24
25
26

27            Public Gallery
28            {{form.public_gallery}}
29

30
31

This is the line of code being highlighted as cause for error (form action):

<form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>

Views.py:

@login_required
def newgallery(request, username):

    if request.method == 'GET':

        form = NewGalleryForm

        context = {
        'form': form,
        'username': username,
        }

        return render(request, 'galleries/newgallery.html', context)

def editgallery(request, username):

    if request.method == "POST":

        form = NewGalleryForm(request.POST)

        if form.is_valid():

            new_gallery = form.save(commit = False)
            ## connect the new gallery with the user (foreign key)
            new_gallery.user = request.user
            new_gallery.save()
            url = "https://api.opensea.io/api/v1/assets?order_direction=desc&offset=0&limit=5"

            params={'owner': new_gallery.wallett_address}
            headers = {
                "Accept": "application/json",
                "X-API-KEY": ""
            }
            response = requests.request("GET", url, headers=headers, params=params)
            response = response.json()["assets"]

            list_of_nfts =  []
            for dictionary in response:
                token_id = dictionary["token_id"]
                token_address = dictionary["asset_contract"]["address"]
                contract_address = 'https://api.opensea.io/api/v1/asset/' + token_address + '/' + token_id + '/'
                name = dictionary["name"]
                if len(name) > 50:
                    name = (name[:50] + '...')
                nft_created_date = dictionary["asset_contract"]["created_date"]
                nft_created_date = nft_created_date[:10]
                nft_created_date = datetime.strptime(nft_created_date, '%Y-%m-%d').strftime('%m/%d/%Y')
                image = dictionary["image_url"]
                description = dictionary["description"]
                if description is not None and '*' in description:
                    head, sep, tail = description.partition('*')
                    description = head
                if description is not None and len(description) > 50:
                    description = (description[:150] + '...')
                if isinstance(description, str) != True:
                    description = 'No description provided'
                link = dictionary["permalink"]
                nft_dict = {
                'contract_address': contract_address,
                'name': name,
                'image': image,
                'description': description,
                'link': link,
                'nft_created_date': nft_created_date,
                }
                list_of_nfts.append(nft_dict)

            context = {
            'new_gallery': new_gallery,
            'list_of_nfts': list_of_nfts,
            'raw_nft_data': json.dumps(list_of_nfts),
            'new_gallery_name': new_gallery.gallery_name,
            'user': new_gallery.user,
            username:username,
            }

            return render(request, 'galleries/editgallery.html', context)

New Gallery HTML (page where user enters basic information regarding New Gallery that he or she is creating... when this form is submitted, the user is brought to a page where they can edit the gallery that was just created (by edit, I mean add new NFT's to that gallery):

      Create new gallery

      <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>

        {% csrf_token %}

          Public Gallery
          {{form.public_gallery}}

            Gallery Name
            {{form.gallery_name}}

          Wallett Address

          ?
          {{form.wallett_address}}

            Category
            {{form.gallery_category}}

          <button
          type="submit"
          class="btn btn-dark mt-4 mb-4"

          style="
          font-size: 1.1rem;
            height: 50px;
            width:fit-content;
          "
        >
          Add NFT's &nbsp
        </button>

    </form>

User Profile HTML (page where user clicks on an a tag to bring them to the the New Gallery HTML (the other HTML I have listed above). That is when the code breaks and gives that error. The url in that a tag is href="{% url 'gallery_app:newgallery' user.username %}":

  Hello&nbsp
  {{user.username}}&nbsp

{% endif %}

    {% if request.user == user %}

    {% endif %}

        {% if request.user == user %}

          Name:
          {{user.first_name}} {{user.last_name}}

          Email:
          {{user.email}}

        {% endif %}

          Username:
          {{user.username}}

          Profile created:
          {{user.date_joined|date}}

          Galleries:
          0

          Followers:
          0

          Following:
          0

    {% if request.user.is_authenticated %}

           Your Galleries:

    {% else %}

        {{user.username}}'s Galleries:

    {% endif %}

    {% for gallery in user.newgallery.all %}

      {{ gallery.gallery_name }}
      NFT's: 0

    {% endfor %}

Urls.py:

app_name = 'gallery_app'

urlpatterns = [
    path('newgallery/<str:username>', views.newgallery, name='newgallery'),
    path('editgallery/<str:username>/<int:gallery_id>', views.editgallery, name='editgallery'),
    path('galleryview/<str:username>/<int:gallery_id>', views.galleryview, name='galleryview'),
]

Body:
It looks like the url argument new_gallery.id is empty when you render the html template.

update: so the template is called from view newgallery.

In your original code there is 2 things to change:

to instantiate the form please add () after NewGalleryForm. Without you just handover a link to the class.

in this view/template you do not yet have an instance of newgallery (just the form). So you can not use newgaller.id. Implement a POST branch in newgallery to save it and remove newgallery.id from the form action and point the action back to newgallery view.

after saving you have a newgallery instance with an id and you can call the edit view if you need to with newgallery in the context

def newgallery(request, username):
    if request.method == 'POST':
       # save newgallery here

    if request.method == 'GET':

        form = NewGalleryForm()

        context = {
        'form': form,
        'username': username,
        }

        return render(request, 'galleries/newgallery.html', context)

<form action="{% url 'gallery_app:newgallery' user.username %} " style .... >


答:
GCC-style assembly inserts are designed to insert a single instruction per asm("..."), and they require you to give accurate information about all of the registers involved.  In this case, you have not notified the compiler that registers r0, r1, r2, and r3 are used internally, so it probably thinks it's OK to reuse some of those for var1 through var4.  You have also reused %0 as the destination of all four of the final mov instructions, so all four of them are actually writing to var1.

Also, it may or may not be your immediate problem, but volatile doesn't do what you think it does and probably isn't accomplishing anything useful here.

How to fix it?  Well, first off, there needs to be a really strong reason why you can't just write

uint32_t var1 = 5;
uint32_t var2 = 6;
uint32_t var3 = 7;
uint32_t var4 = 8;
```
<p>Assuming there <em>is</em> such a reason, then you should instead try writing one instruction per <code>asm</code>, and not using any scratch registers at all...</p>
```asm ("mov %0, #5" : "=r" (var1));
asm ("mov %0, #6" : "=r" (var2));
asm ("mov %0, #7" : "=r" (var3));
asm ("mov %0, #8" : "=r" (var4));
```
<p>If you really absolutely have to do a whole bunch of work in a single <code>asm</code> then the first thing you should consider is putting it in a separate .S file and making it conform to the ABI so that you can call it like a normal function:</p>
```    .text
    .globl do_the_thing
    .type do_the_thing, @function
_do_the_thing:
    ; all your actual code here
    bx r14
.size do_the_thing, .-do_the_thing
```
<p>and then in your C</p>
```   rv = do_the_thing(arg1, arg2, ...);
```

If there's no way to make that work, then, and only then, should you sit down and read the entire "Extended Asm" chapter of the GCC manual and work out how to wedge the complete register-usage behavior of your insert into the constraints.  If you need help with that, post a new question in which you show the real assembly language construct you need to insert, rather than a vague example, because every little detail matters.

Title: ARM inline assembly, registers are read in an incorrect order

Body:
GCC-style assembly inserts are designed to insert a single instruction per asm("..."), and they require you to give accurate information about all of the registers involved.  In this case, you have not notified the compiler that registers r0, r1, r2, and r3 are used internally, so it probably thinks it's OK to reuse some of those for var1 through var4.  You have also reused %0 as the destination of all four of the final mov instructions, so all four of them are actually writing to var1.

Also, it may or may not be your immediate problem, but volatile doesn't do what you think it does and probably isn't accomplishing anything useful here.

How to fix it?  Well, first off, there needs to be a really strong reason why you can't just write

uint32_t var1 = 5;
uint32_t var2 = 6;
uint32_t var3 = 7;
uint32_t var4 = 8;

Assuming there is such a reason, then you should instead try writing one instruction per asm, and not using any scratch registers at all...

asm ("mov %0, #5" : "=r" (var1));
asm ("mov %0, #6" : "=r" (var2));
asm ("mov %0, #7" : "=r" (var3));
asm ("mov %0, #8" : "=r" (var4));

If you really absolutely have to do a whole bunch of work in a single asm then the first thing you should consider is putting it in a separate .S file and making it conform to the ABI so that you can call it like a normal function:

    .text
    .globl do_the_thing
    .type do_the_thing, @function
_do_the_thing:
    ; all your actual code here
    bx r14
.size do_the_thing, .-do_the_thing

and then in your C

   rv = do_the_thing(arg1, arg2, ...);

If there's no way to make that work, then, and only then, should you sit down and read the entire "Extended Asm" chapter of the GCC manual and work out how to wedge the complete register-usage behavior of your insert into the constraints.  If you need help with that, post a new question in which you show the real assembly language construct you need to insert, rather than a vague example, because every little detail matters.


问:
How should my own server verify a web client signed in with firebase?
Web client signs in successfully directly with firebase.
Now it wants to talk to my own nodejs (non-firebase) server.
How does my server verify the web-client is really signed in with firebase? Note: my server doesn't manage any user account passwords.

https://firebase.google.com/docs/auth/admin/custom-claims
Seems to use this flow:

For simplicity, let me call my good web client Bob.

Step 1: Bob needs to send password + email to my own (non-firebase) server. Now my server knows Bob is Bob, and gives Bob client-side a token "bob-token"

Step 2: Bob on client-side calls firebase firebaseTokenFromFirebase = firebaseFunction.signInWithToken("bob-token")

Step 3: Bob sends firebaseToken to my own server

Step 4: On my own server, I can make a verification request directly to firebase bobReallySignedIntoFirebase = firebaseAdmin.verify(firebaseTokenFromFirebase). And if ok, now my server knows Bob really signed into Firebase.

But question: My server doesn't manage passwords at all. So my server cannot verify "Bob is Bob" in Step 1. Is there a way for my server to only rely on Firebase?

Ideally, Bob signs in directly with firebase, and receives an asymmetrically signed JWT (containing Bob's basic info) that can be independently verified by my own server (my server only needs the public key; firebase produces the JWT with the private key).

答:
There is no way to sign a specific user in to Firebase from the Admin SDKs, as the Admin SDK doesn't have the concept of a current user.

The idiomatic approach is to sign in your users in their client-side code with a Firebase SDK, and then pass the ID token to your server when you need to establish identity/authority. This is what most Firebase SDKs and services also do under the hood.

If you want to sign your users in on your server, you'll have to call the Firebase Authentication REST API.

Also see:

Firebase: How to generate access token from username and password on the server?

Firebase authentication for private server


问:
Accessing another repository with GitHub CLI in GitHub Actions
I'm trying to access another github repo with gh cli as a part of a workflow.
I am using the gh release view command as below

```<code>run: |
    echo "::set-output name=description::$(gh release view --repo <owner/repo>)"
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
</code>```

The workflow is failing with 404, I understand it's because the repo is private, even though both repositories have the same owner.
When authenticated locally, the command works just fine.

Is there any way to access that repo in the workflow?

答:
The GITHUB_TOKEN is scoped only to the triggering repository. If you need to access any resources in other repositories or in other accounts then you need to pass a token with a wider scope to the checkout step. This can be a GitHub App token, a Personal Access Token etc.

Store the token in the Secrets/Actions and pass it to the checkout task's token parameter.

Alternatively you can pass in an ssh key through the ssh-key parameter.

```<code>- uses: actions/checkout@v2
  with:
    # Repository name with owner. For example, actions/checkout
    # Default: ${{ github.repository }}
    repository: ''

    # Personal access token (PAT) used to fetch the repository. The PAT is configured
    # with the local git config, which enables your scripts to run authenticated git
    # commands. The post-job step removes the PAT.
    #
    # We recommend using a service account with the least permissions necessary. Also
    # when generating a new PAT, select the least scopes necessary.
    #
    # [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets)
    #
    # Default: ${{ github.token }}
    token: ''

    # SSH key used to fetch the repository. The SSH key is configured with the local
    # git config, which enables your scripts to run authenticated git commands. The
    # post-job step removes the SSH key.
    #
    # We recommend using a service account with the least permissions necessary.
    #
    # [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets)
    ssh-key: ''
</code>```

The same applies to calling resources in other repositories through an API or GitHub CLI.

Body:
I'm trying to access another github repo with gh cli as a part of a workflow.
I am using the gh release view command as below

run: |
    echo "::set-output name=description::$(gh release view --repo <owner/repo>)"
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

The workflow is failing with 404, I understand it's because the repo is private, even though both repositories have the same owner.
When authenticated locally, the command works just fine.

Is there any way to access that repo in the workflow?

Body:
The GITHUB_TOKEN is scoped only to the triggering repository. If you need to access any resources in other repositories or in other accounts then you need to pass a token with a wider scope to the checkout step. This can be a GitHub App token, a Personal Access Token etc.

Store the token in the Secrets/Actions and pass it to the checkout task's token parameter.

Alternatively you can pass in an ssh key through the ssh-key parameter.

- uses: actions/checkout@v2
  with:
    # Repository name with owner. For example, actions/checkout
    # Default: ${{ github.repository }}
    repository: ''

    # Personal access token (PAT) used to fetch the repository. The PAT is configured
    # with the local git config, which enables your scripts to run authenticated git
    # commands. The post-job step removes the PAT.
    #
    # We recommend using a service account with the least permissions necessary. Also
    # when generating a new PAT, select the least scopes necessary.
    #
    # [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets)
    #
    # Default: ${{ github.token }}
    token: ''

    # SSH key used to fetch the repository. The SSH key is configured with the local
    # git config, which enables your scripts to run authenticated git commands. The
    # post-job step removes the SSH key.
    #
    # We recommend using a service account with the least permissions necessary.
    #
    # [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets)
    ssh-key: ''

The same applies to calling resources in other repositories through an API or GitHub CLI.


问:
How to add dynamic List to flutter nested map
Need a help!

This is my data from firebase

```<code>{
  "Engineering" : ["EEE", "CSE", "EE"],
  "Marketing" : [ "SEO", "Online Marketing", "Digital Marketing"],
}
</code>```

I am using a nested dropdown to show these data to users, receiving data is something like this

```<code>Map<String, List<String>>
</code>```

after selecting the dropdown, individual selection is something like this-

```<code>String _selectedCategory = "Engineering" ;
String _selectedSkill = "EEE" ;
</code>```

at a time a user can select a category with a skill,

I want to create a dynamic map like this

```<code>{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}
</code>```

I tried to achieve this-

```<code>  List<String> addedSkills = [];
  Map<String, List<String>> addedData = {};
</code>```

inside dropdown

```<code>setState((){
   addedSkills.add(_selectedSkill);
   addedData.addAll({_selectedCategory: _addedSkills})
});
</code>```

data is showing like this

```<code>{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from
   Category 2", "Selected Skill 3 from Category 2"],

}
</code>```

but I want data something like this

```<code>{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}
</code>```

答:
There was some logical error on my code so finally i did this way</p>
```<code>     setState(() {
                        _selectedSkill = newValue.toString();
                        if (addedData.isNotEmpty) {
                          if (addedData
                              .containsKey(_selectedSkillCategory)) {
                            List<String> _tmpValue =
                                addedData[_selectedSkillCategory];
                            if (_tmpValue
                                .contains(_selectedSkill.toString())) {
                            } else {
                              _tmpValue.add(_selectedSkill.toString());
                            }
                          } else {
                            addedData[_selectedSkillCategory.toString()] = [
                              _selectedSkill.toString()
                            ];
                          }
                        } else {
                          //start a brand new map
                          addedData[_selectedSkillCategory.toString()] = [
                            _selectedSkill.toString()
                          ];
                        }
</code>```

Body:
Need a help!

This is my data from firebase

{
  "Engineering" : ["EEE", "CSE", "EE"],
  "Marketing" : [ "SEO", "Online Marketing", "Digital Marketing"],
}

I am using a nested dropdown to show these data to users, receiving data is something like this

Map<String, List<String>>

after selecting the dropdown, individual selection is something like this-

String _selectedCategory = "Engineering" ;
String _selectedSkill = "EEE" ;

at a time a user can select a category with a skill,

I want to create a dynamic map like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}

I tried to achieve this-

  List<String> addedSkills = [];
  Map<String, List<String>> addedData = {};

inside dropdown

setState((){
   addedSkills.add(_selectedSkill);
   addedData.addAll({_selectedCategory: _addedSkills})
});

data is showing like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from
   Category 2", "Selected Skill 3 from Category 2"],

}

but I want data something like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}

Body:
There was some logical error on my code so finally i did this way

     setState(() {
                        _selectedSkill = newValue.toString();
                        if (addedData.isNotEmpty) {
                          if (addedData
                              .containsKey(_selectedSkillCategory)) {
                            List<String> _tmpValue =
                                addedData[_selectedSkillCategory];
                            if (_tmpValue
                                .contains(_selectedSkill.toString())) {
                            } else {
                              _tmpValue.add(_selectedSkill.toString());
                            }
                          } else {
                            addedData[_selectedSkillCategory.toString()] = [
                              _selectedSkill.toString()
                            ];
                          }
                        } else {
                          //start a brand new map
                          addedData[_selectedSkillCategory.toString()] = [
                            _selectedSkill.toString()
                          ];
                        }


问:
react-native not updating MapView initialRegion with react-native-geolocation-service
I would like to update my map to show the user location. Using the code below, I get a world map not a map of the UK, which is what the latitude and longitude should show, can anyone help?</p>
```<code>  const [location, setLocation] = useState({
    initialPosition: {
      latitude: 0,
      longitude: 0,
      latitudeDelta: 0,
      longitudeDelta: 0,
    },
  });

  const getLocationPermissions = async () => {
    const granted = await request(
      Platform.select({
        android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
        ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
      }),
      {
        title: 'DemoApp',
        message: 'App would like access to your location ',
      }
    );

    return granted === RESULTS.GRANTED;
  };

  useEffect(() => {
    //  check permission
    const isGranted = getLocationPermissions();

    if (isGranted) {
   // get location
      Geolocation.getCurrentPosition((info) => {
        let lat = info.coords.latitude;
        let long = info.coords.longitude;
   // update state with location,latitude: 52.62869394486038
   //longitude: -1.9794797216434805
        var initialRegion = {
          latitude: lat,
          longitude: long,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        };
      });
    } else {
      console.log('error');
    }
  }, []);

  return (
    <View style={styles.container}>
      <MapView style={styles.map} initialRegion={location.initialPosition} />
    </View>
  );
</code>```

答:
After retrieve user location from device, animate map to that region.

import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import MapView from "react-native-maps";

const App = () => {
  const mapRef = React.useRef(null);

  React.useEffect(() => {
    // Below are mocked location in UK. Retrieve real location
    // from device with Geoocation API

    // latitude: 52.62869394486038
    //longitude: -1.9794797216434805
    const userRegion = {
      latitude: 52.62869394486038,
      longitude: -1.9794797216434805,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421,
    };

    mapRef.current?.animateToRegion(userRegion);
  }, []);

  return (
    <View style={styles.container}>
      <MapView
        ref={mapRef}
        initialRegion={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
        style={styles.mapStyle}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    paddingTop: 10,
    backgroundColor: "#ecf0f1",
  },
  mapStyle: {
    ...StyleSheet.absoluteFillObject,
  },
});

export default App;

```

Working example snack.

https://snack.expo.dev/@emmbyiringiro/9f04a3

Body:
I would like to update my map to show the user location. Using the code below, I get a world map not a map of the UK, which is what the latitude and longitude should show, can anyone help?

  const [location, setLocation] = useState({
    initialPosition: {
      latitude: 0,
      longitude: 0,
      latitudeDelta: 0,
      longitudeDelta: 0,
    },
  });

  const getLocationPermissions = async () => {
    const granted = await request(
      Platform.select({
        android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
        ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
      }),
      {
        title: 'DemoApp',
        message: 'App would like access to your location ',
      }
    );

    return granted === RESULTS.GRANTED;
  };

  useEffect(() => {
    //  check permission
    const isGranted = getLocationPermissions();

    if (isGranted) {
   // get location
      Geolocation.getCurrentPosition((info) => {
        let lat = info.coords.latitude;
        let long = info.coords.longitude;
   // update state with location,latitude: 52.62869394486038
   //longitude: -1.9794797216434805
        var initialRegion = {
          latitude: lat,
          longitude: long,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        };
      });
    } else {
      console.log('error');
    }
  }, []);

  return (
    <View style={styles.container}>
      <MapView style={styles.map} initialRegion={location.initialPosition} />
    </View>
  );

Body:
After retrieve user location from device, animate map to that region.

import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import MapView from "react-native-maps";

const App = () => {
  const mapRef = React.useRef(null);

  React.useEffect(() => {
    // Below are mocked location in UK. Retrieve real location
    // from device with Geoocation API

    // latitude: 52.62869394486038
    //longitude: -1.9794797216434805
    const userRegion = {
      latitude: 52.62869394486038,
      longitude: -1.9794797216434805,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421,
    };

    mapRef.current?.animateToRegion(userRegion);
  }, []);

  return (
    <View style={styles.container}>
      <MapView
        ref={mapRef}
        initialRegion={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
        style={styles.mapStyle}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    paddingTop: 10,
    backgroundColor: "#ecf0f1",
  },
  mapStyle: {
    ...StyleSheet.absoluteFillObject,
  },
});

export default App;

Working example snack.

https://snack.expo.dev/@emmbyiringiro/9f04a3


问:
How to set a property value based on a variable in Javascript
The problem is I have this piece of code (Jquery UI):

```<code>    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "Remove": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });
</code>```

and now I have to internationalize it by giving to each button a word translation. I have the translation on the variables STR_REMOVE and STR_CANCEL, but if I do something like

```<code>        buttons: {
            STR_REMOVE: function() {
                $(this).dialog("close");
            },
            STR_CANCEL: function() {
                $(this).dialog("close");
            }
        }
</code>```

the buttons (the properties) take the value "STR_REMOVE" and "STR_CANCEL", not its content. So, the question is, what can I do?

答:
Try this.

```<code>var STR_REMOVE = "my delete",  STR_CANCEL = "my cancel";

$("#dialog-confirm").dialog({
    resizable: false,
    modal: true,
    buttons: [{
        text: STR_REMOVE,
        click: function () {
            $(this).dialog("close");
        }
    },
    {
        text: STR_CANCEL,
        click: function () {
            $(this).dialog("close");
        }
    }]
});
</code>```

have a look at the jquery ui doc: http://jqueryui.com/demos/dialog/#option-buttons

ContentLicense: CC BY-SA 3.0

Body:
The problem is I have this piece of code (Jquery UI):

    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "Remove": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });

and now I have to internationalize it by giving to each button a word translation. I have the translation on the variables STR_REMOVE and STR_CANCEL, but if I do something like

        buttons: {
            STR_REMOVE: function() {
                $(this).dialog("close");
            },
            STR_CANCEL: function() {
                $(this).dialog("close");
            }
        }

the buttons (the properties) take the value "STR_REMOVE" and "STR_CANCEL", not its content. So, the question is, what can I do?

Body:
Try this.

var STR_REMOVE = "my delete",  STR_CANCEL = "my cancel";

$("#dialog-confirm").dialog({
    resizable: false,
    modal: true,
    buttons: [{
        text: STR_REMOVE,
        click: function () {
            $(this).dialog("close");
        }
    },
    {
        text: STR_CANCEL,
        click: function () {
            $(this).dialog("close");
        }
    }]
});

have a look at the jquery ui doc: http://jqueryui.com/demos/dialog/#option-buttons


问:
Extrating data within database on the base of the datatime
I have one dataset with several columns: id, Unixtime, X, Y, etc....
Unixtime is one sequence of date: 01-01-2010 00:00:00, 02-01-2010 00:00:00...etc up to 31-12-2021 23:59:59.

I would like to get data within specific range, between 01-01-2019 00:00:00 until 31-12-2019 23:59:59.
I tried with this script but I have had some problem, because I am not sure if python take all data.

```<code>import pandas as pd
data = pd.read_csv('name.csv', sep=';')
data.info()
start_time = '01-01-2010 00:00:00'
end_time = '31-12-2019 23:59:59'
mask =(data['Unixtime']>start_time)&(data['Unixtime']<=end_time]
x=data.loc[mask]
</code>```

There is another solution?

Body:
I have one dataset with several columns: id, Unixtime, X, Y, etc....
Unixtime is one sequence of date: 01-01-2010 00:00:00, 02-01-2010 00:00:00...etc up to 31-12-2021 23:59:59.

I would like to get data within specific range, between 01-01-2019 00:00:00 until 31-12-2019 23:59:59.
I tried with this script but I have had some problem, because I am not sure if python take all data.

import pandas as pd
data = pd.read_csv('name.csv', sep=';')
data.info()
start_time = '01-01-2010 00:00:00'
end_time = '31-12-2019 23:59:59'
mask =(data['Unixtime']>start_time)&(data['Unixtime']<=end_time]
x=data.loc[mask]

There is another solution?

Body: f_date = data [(data['Unixtime Date'] < '23-03-21') & (data['Unixtime Date'] > '03-03-21')]


问:
Dynamically using the first frame as poster in HTML5 video?
I'm wondering if there's any straightforward way to achieve this effect, without needing backend code to extract a frame, save it as a jpg and database it somewhere.

An effect whereby the first frame of the video just shows up as the poster when the video loads would be so helpful (it would only work if the browser can play back the video obviously, which might be a little different from how poster traditionally works, but that is not a concern.

答:
I found a great way to dynamically add poster to a video!

To show the desired frame from video (in my case it's the frame at 1.75 seconds) - add preload="metadata" to the video element and #t=1.75 to the end of source URL.

Add eventListener to the video element that will listen for play event only once.
Once the event is emitted reset the video time.

<video width="100%" controls="controls" preload="metadata" id="myVid">
    <source src="path/to/your/video#t=1.75" type="video/mp4">
</video>

```

Body:
I found a great way to dynamically add poster to a video!

To show the desired frame from video (in my case it's the frame at 1.75 seconds) - add preload="metadata" to the video element and #t=1.75 to the end of source URL.

Add eventListener to the video element that will listen for play event only once.
Once the event is emitted reset the video time.

<video width="100%" controls="controls" preload="metadata" id="myVid">
    <source src="path/to/your/video#t=1.75" type="video/mp4">
</video>

<script>
    var el = document.getElementById('myVid');
    el.addEventListener('play', () => {
        el.currentTime = 0;
    }, { once: true });
</script>


问:
Military Time Form Validation msAccess Form View
I'm having a difficult time doing military time or short time in the form view. I caught an error where the user put in 15:83 which shouldn't be allowed because the minutes are over 59, as well hours being over 23. However, I'm not sure how to create a form validation for something like that and I can't seem to find any documentation for it online surrounding this type of formatting.</p>

答:
in the validation rule property of the text box control on the form enter this expression

=Right([Text6],2)<60 Or Left([Text6],2)<24

i have assumed name of control is Text6


答:
You need to pass the gallery as context into the view that has the edit form. I don't see in the views that you posted that you have a detail view but I do see a detail view url. So I'm assuming you're passing the edit form to your create view instead? That view doesn't return a context with new_gallery as a context variable. I would create a detail view for your gallery instead and pass the edit form, user and gallery as context to the template.

```<code>Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found.
</code>```

New context

```<code>def galleryview(request, username, gallery_id):
    # Logic
    gallery = get_object_or_404(Gallery, pk=gallery_id)
    context = {
    'form': form,
    'username': username,
    'new_gallery': gallery,
    }
    # return an html response with context
</code>```

Also, when you instantiate an unbound form you should add parenthesis after it.

```<code>form = NewGalleryForm()
</code>```

Title: Django No Reverse Match Error - Nothing is working

Body:
You need to pass the gallery as context into the view that has the edit form. I don't see in the views that you posted that you have a detail view but I do see a detail view url. So I'm assuming you're passing the edit form to your create view instead? That view doesn't return a context with new_gallery as a context variable. I would create a detail view for your gallery instead and pass the edit form, user and gallery as context to the template.

Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found.

New context

def galleryview(request, username, gallery_id):
    # Logic
    gallery = get_object_or_404(Gallery, pk=gallery_id)
    context = {
    'form': form,
    'username': username,
    'new_gallery': gallery,
    }
    # return an html response with context

Also, when you instantiate an unbound form you should add parenthesis after it.

form = NewGalleryForm()


问:
cleaner way to check whether or not a the current window.location.href is equal to any of the strings in the array
Im trying to do a redirect if the url is equal to any of the strings in the following array of urls:

So I did the following

```<code>function redirectUser() {
  if (window.location.href === 'https://swish.com/login' || window.location.href === 'https://swish.com/register' || window.location.href === 'https://swish.com/overview') {
    window.location.replace('https://swish.com/onboard');
  }
}
</code>```

But this is a bit ugly, so I thought of putting the urls in an array and doing something like this:

```<code>function redirectUser() {
  const urls = ['https://swish.com/login', 'https://swish.com/register', 'https://swish.com/overview' ]
for(let url of urls) {
  if (window.location.href === url) {
    window.location.replace('https://swish.com/onboard');
  }
 }
}
</code>```

Is there any other way to do this? If not, which would be the better option in your opinion? Thanks!

答:
i think it will help you</p>
```<code>   function redirectUser() {
     const urls = ['https://swish.com/login', 'https://swish.com/register',
      'https://swish.com/overview' ]
         if(urls.includes(window.location.href)){
         window.location.replace('https://swish.com/onboard');
        }
     }
</code>```

Body:
Im trying to do a redirect if the url is equal to any of the strings in the following array of urls:

So I did the following

function redirectUser() {
  if (window.location.href === 'https://swish.com/login' || window.location.href === 'https://swish.com/register' || window.location.href === 'https://swish.com/overview') {
    window.location.replace('https://swish.com/onboard');
  }
}

But this is a bit ugly, so I thought of putting the urls in an array and doing something like this:

function redirectUser() {
  const urls = ['https://swish.com/login', 'https://swish.com/register', 'https://swish.com/overview' ]
for(let url of urls) {
  if (window.location.href === url) {
    window.location.replace('https://swish.com/onboard');
  }
 }
}

Is there any other way to do this? If not, which would be the better option in your opinion? Thanks!

Body:
i think it will help you

   function redirectUser() {
     const urls = ['https://swish.com/login', 'https://swish.com/register',
      'https://swish.com/overview' ]
         if(urls.includes(window.location.href)){
         window.location.replace('https://swish.com/onboard');
        }
     }


问:
Trying to inject dependency into IIS hosted WCF service using MEF
I'm trying to inject specific class into my WCF service but it doesn't work and I can't understand why. I'm VERY NEW to MEF and patterns, just trying to make it work. Watched series of videos to understand what it is about but bootstraping won't work in my case since it is not Silverlight
http://channel9.msdn.com/blogs/mtaulty/mef--silverlight-4-beta-part-1-introduction

Here is my Web application's Global.asax code. This is non MVC, just regular ASP.NET app:

```<code>private void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes();

            var catalog = new WebScopedCatalog(new DirectoryCatalog(Server.MapPath("~\\bin")));
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }
</code>```

FIRST, I'm not sure I even bootrstrap it properly.. SECOND, I'm using http://www.timjroberts.com/2011/02/web-scoped-mef-parts/ as a guidance for web-scoped parts. I need that because some injected objects supposed to live during request only.

Now, I have following class:

```<code>    [Export(typeof(ITest))]
    [WebPartCreationPolicy(WebCreationPolicy.Session)]
    public class Test : ITest
    {
        public string TestMe()
        {
            return "Hello!";
        }
    }
</code>```

And my service looks like:

```<code>[ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MobileService
    {
        [Import]
        public ITest MyTestClass { get; set; }

        public MobileService()
        {
            int i = 10;
        }
</code>```

When breakpoint hits at i=10 - I have NULL inside MyTestClass. Clearly, MEF does not initialize this class for me. Am I missing something?

EDIT:

When I examine catalog - I see my class Exported but I don't see it imported anywhere...

EDIT 2:
Daniel, Thank you. It makes sense. It still feels litle like a magic for me at this point. Yes, WCF creates this service. Than I have MembershipProvider and various Utility classes that ALL need the same import. And I'm not creating neither of those classes so I can't have Mef creating them. (Service created by WCF, MembershipProvider created by who-knows-what, Utility classes have static methods..) I wanted to use Mef instead of storing my stuff in HttpContext.Current.  My container object doesn't have SatisfyImports. It has SatisfyImportsOnce. What if I do it in many different constructors? Will Mef share same singleton or it will be creating new instance every time?

At this point I wonder if I should even use Mef in this particular scenario..

答:
The web-scoped part creation policy that I wrote won't help with WCF services.

I've posted a new blog post that documents an approach to composeable WCF services:
http://www.timjroberts.com/2011/08/wcf-services-with-mef/

Basically, you need to implement a custom Instance Provider that is MEF-aware and can compose the WCF service object when it is created.

Body:
I'm trying to inject specific class into my WCF service but it doesn't work and I can't understand why. I'm VERY NEW to MEF and patterns, just trying to make it work. Watched series of videos to understand what it is about but bootstraping won't work in my case since it is not Silverlight
http://channel9.msdn.com/blogs/mtaulty/mef--silverlight-4-beta-part-1-introduction

Here is my Web application's Global.asax code. This is non MVC, just regular ASP.NET app:

private void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes();

            var catalog = new WebScopedCatalog(new DirectoryCatalog(Server.MapPath("~\\bin")));
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

FIRST, I'm not sure I even bootrstrap it properly.. SECOND, I'm using http://www.timjroberts.com/2011/02/web-scoped-mef-parts/ as a guidance for web-scoped parts. I need that because some injected objects supposed to live during request only.

Now, I have following class:

    [Export(typeof(ITest))]
    [WebPartCreationPolicy(WebCreationPolicy.Session)]
    public class Test : ITest
    {
        public string TestMe()
        {
            return "Hello!";
        }
    }

And my service looks like:

[ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MobileService
    {
        [Import]
        public ITest MyTestClass { get; set; }

        public MobileService()
        {
            int i = 10;
        }

When breakpoint hits at i=10 - I have NULL inside MyTestClass. Clearly, MEF does not initialize this class for me. Am I missing something?

EDIT:

When I examine catalog - I see my class Exported but I don't see it imported anywhere...

EDIT 2:
Daniel, Thank you. It makes sense. It still feels litle like a magic for me at this point. Yes, WCF creates this service. Than I have MembershipProvider and various Utility classes that ALL need the same import. And I'm not creating neither of those classes so I can't have Mef creating them. (Service created by WCF, MembershipProvider created by who-knows-what, Utility classes have static methods..) I wanted to use Mef instead of storing my stuff in HttpContext.Current.  My container object doesn't have SatisfyImports. It has SatisfyImportsOnce. What if I do it in many different constructors? Will Mef share same singleton or it will be creating new instance every time?

At this point I wonder if I should even use Mef in this particular scenario..


问:
How to get previous day's records in MongodDB?
I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day.
So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query.
So something like this

```<code>createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},
</code>```

But like I explained this is not what I want.

答:
We would assume "the previous day" is a 24 hour period starting at the beginning of the day before today. The easiest way to do this is use time based on UTC and add a timezone offset (if needed).

const timeZoneOffset = -5;

createdTime: {
     $gt: new Date().setUTCHours(0,0,0)-1000 * 60 * 60 * (24 + timeZoneOffset),
     $lt: new Date().setUTCHours(23,59,59,999)-1000 * 60 * 60 * (24 + timeZoneOffset)

},
```

Body:
I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day.
So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query.
So something like this

createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},

But like I explained this is not what I want.


问:
Should a class constructor return a subclass?
Should a class constructor return a subclass?

This is mostly a question about OOP style and python style. I have problem where I need to implement a general case solution and, for performance reasons, I need to implement an optimized solution for a specific input type. The input type depends on the user. Currently I've implemented this by sub-classing the general case solution to make the optimized solution. I've come up with the following example to help describe what I mean.

```<code>from collections import Counter

class MyCounter(object):
    """General Case Counter"""
    def __init__(self, seq):
        self.seq = seq

    def count(self, key):
        return sum(key == item for item in self.seq)

class OptimizedCounter(MyCounter):
    """Counter optimized for hashable types"""
    def __init__(self, seq):
        self.counter = Counter(seq)

    def count(self, key):
        return self.counter.get(key, 0)

counter = MyCounter(['a', 'a', 'b', [], [0, 1]])
counter.count([0, 1])
# 1

counter = OptimizedCounter(['a', 'a', 'b'])
counter.count('a')
# 2
</code>```

My question is how do I design a smooth interface so that the user gets an appropriate instance without having to worry about how it's implemented. I've considered doing something like the following, but that feels ugly to me. Is there a more canonical or OOP way to do something like this?

```<code>class MyCounter(object):
    """General Case Counter"""
    def __new__(cls, seq):
        if hasOnlyHashables(seq):
            return object.__new__(OptimizedCounter)
        else:
            return object.__new__(MyCounter)
</code>```

答:
No, the class constructor doesn't return anything.

You need to create a factory as suggested by BrenBarn, but I would put that factory as a static method in the most generic class.

Something like this:

class MyCounter(object):
    @staticmethod
    def from_seq(seq):
        if hasOnlyHashables(seq):
            return OptimizedCounter(seq)
        else:
            return MyCounter(seq)

```

Body:
Should a class constructor return a subclass?

This is mostly a question about OOP style and python style. I have problem where I need to implement a general case solution and, for performance reasons, I need to implement an optimized solution for a specific input type. The input type depends on the user. Currently I've implemented this by sub-classing the general case solution to make the optimized solution. I've come up with the following example to help describe what I mean.

from collections import Counter

class MyCounter(object):
    """General Case Counter"""
    def __init__(self, seq):
        self.seq = seq

    def count(self, key):
        return sum(key == item for item in self.seq)

class OptimizedCounter(MyCounter):
    """Counter optimized for hashable types"""
    def __init__(self, seq):
        self.counter = Counter(seq)

    def count(self, key):
        return self.counter.get(key, 0)

counter = MyCounter(['a', 'a', 'b', [], [0, 1]])
counter.count([0, 1])
# 1

counter = OptimizedCounter(['a', 'a', 'b'])
counter.count('a')
# 2

My question is how do I design a smooth interface so that the user gets an appropriate instance without having to worry about how it's implemented. I've considered doing something like the following, but that feels ugly to me. Is there a more canonical or OOP way to do something like this?

class MyCounter(object):
    """General Case Counter"""
    def __new__(cls, seq):
        if hasOnlyHashables(seq):
            return object.__new__(OptimizedCounter)
        else:
            return object.__new__(MyCounter)


问:
CleanArchitecture: where to put View-related data that can be stored via EF?
My question is simple but somehow complex in detail! I try to explain it ...

I built my application in a 'Clean Architecture' manner, where i have Entities (not to be confused with database entities) at most top layer. They just represent domain specific data (so basically getters/setters + little validation logic + business rules). The layer beneath is called 'Application' where i process all incoming requests, sometimes from APIs, sometimes from web applications and so on. those requests can lead to CRUD - operations directed to a database (not a must). For this i invented a third layer named Infrastructure, where i use EF to map from the Entities (in the Entities - Layer) to database entities. So far its fine ...

Now i have an web application that requires to display some visual elements on a canvas (for example). These visual elements should be able to show some descriptive text and represent the states from an specific Entity out of the Entities - Layer. I have written ViewModels/DTOs that simply map to that Entity for responding to incoming requests and to preserve loose coupling. Now there is the requirement that i have to make these visual elements adjustable on screen (via mouse + drag and drop) and to persist those adjustment (with coordinates).

Now my simple question is:
Where should those coordinates reside?
Putting them into the Entity in the Entities - layer is wrong in my opinion, because there should never be any state corresponding to the visuals of a View.

I need to store those coordinates via EF, so i need to have a model to map from and i used my Entities for that.

The configuration looks like:

```<code>public class SpotConfiguration : IEntityTypeConfiguration<Spot>
{
    public void Configure(EntityTypeBuilder<Spot> builder)
    {
        if (builder == null)
            throw new ArgumentNullException(nameof(builder));

        builder.HasOne(x => x.Area)
            .WithMany(x => x.Spots)
            .HasForeignKey(x => x.AreaId);

        builder.Property(x => x.Description)
            .IsRequired()
            .HasMaxLength(10);
    }
}
</code>```

The Spot is the Entity which needs to refer to the coordinates. There coordinates are only required for one web application, but the Entity is used in other Domains aswell!

I hope you understand my question! :)

答:
The prohibition of sending view-state down into the entity layer is to prevent you from making your entities know how they are displayed.  Your adjustments to UI elements creates a whole new kind of entity, one that needs its own persistence/domain layer.

You should work hard to keep these new elements strongly decoupled from your domain entities.  It is effectively a whole new domain, that happens to have a binding somewhere to your view model (NOT the domain entities).

Your view-models are about to prove their worth!  They will be composed of both domain-entity data as well as Spots to handle the layout configuration bits.  This is why we create view-models, so that we can keep the domain-models clean of this sort of thing.

Body:
My question is simple but somehow complex in detail! I try to explain it ...

I built my application in a 'Clean Architecture' manner, where i have Entities (not to be confused with database entities) at most top layer. They just represent domain specific data (so basically getters/setters + little validation logic + business rules). The layer beneath is called 'Application' where i process all incoming requests, sometimes from APIs, sometimes from web applications and so on. those requests can lead to CRUD - operations directed to a database (not a must). For this i invented a third layer named Infrastructure, where i use EF to map from the Entities (in the Entities - Layer) to database entities. So far its fine ...

Now i have an web application that requires to display some visual elements on a canvas (for example). These visual elements should be able to show some descriptive text and represent the states from an specific Entity out of the Entities - Layer. I have written ViewModels/DTOs that simply map to that Entity for responding to incoming requests and to preserve loose coupling. Now there is the requirement that i have to make these visual elements adjustable on screen (via mouse + drag and drop) and to persist those adjustment (with coordinates).

Now my simple question is:
Where should those coordinates reside?
Putting them into the Entity in the Entities - layer is wrong in my opinion, because there should never be any state corresponding to the visuals of a View.

I need to store those coordinates via EF, so i need to have a model to map from and i used my Entities for that.

The configuration looks like:

public class SpotConfiguration : IEntityTypeConfiguration<Spot>
{
    public void Configure(EntityTypeBuilder<Spot> builder)
    {
        if (builder == null)
            throw new ArgumentNullException(nameof(builder));

        builder.HasOne(x => x.Area)
            .WithMany(x => x.Spots)
            .HasForeignKey(x => x.AreaId);

        builder.Property(x => x.Description)
            .IsRequired()
            .HasMaxLength(10);
    }
}

The Spot is the Entity which needs to refer to the coordinates. There coordinates are only required for one web application, but the Entity is used in other Domains aswell!

I hope you understand my question! :)


问:
C++ Get/Set accessors - how do I avoid typing repetitive code?
I'm writing a pretty large library, and I find myself writing almost identical accessors all the time. I already have several dozen accessors such as the one below.

Question: How can I declare/implement accessors to save typing all this repetitive code? (No #defines please; I'm looking for C++ constructs.)

Update: Yes, I do need accessor functions, because I need to take pointers to these accessors for something called Property Descriptors, which enable huge savings in my GUI code (non-library).

.h file

```<code>private:
    bool _visible;
public:
    bool GetVisible() const { return _visible; }
    void SetVisible (bool value);

// Repeat for Get/SetFlashing, Get/SetColor, Get/SetLineWidth, etc.
</code>```

.cpp file

```<code>void Element::SetVisible (bool value)
{
    _visible = value;
    this->InvalidateSelf(); // Call method in base class
    // ...
    // A bit more code here, identical in 90% of my setters.
    // ...
}

// Repeat for Get/SetFlashing, Get/SetColor, Get/SetLineWidth, etc.
</code>```

答:
I'm a tad late again, but I wanted to answer because I don't totally agree with some other here, and think there's additional points to lay out.

It's difficult to say for sure if your access methods are code smells without seeing a larger codebase, or have more information about intent. Everyone here is right about one thing: access method are generally to be avoided unless they do some 'significant work', or they expose data for the purpose of generic-ism (particularly in libraries).

So, we can go ahead and call methods like the idiomatic data() from STL containers, 'trivial access method'.

Why not use trivial access methods?

First, as others have noted, this can lead to an over-exposure of implementation details. At it's best such exposure makes for tedious code, and at it's worse it can lead to obfuscation of ownership semantics, resource leaks, or fatal exceptions. Exposure is fundamentally opposite of object orientation, because each object ought to manage its own data, and operations.

Secondly, code tends to become long, hard to test, and hard to maintain, as you have noted.

When to use trivial access methods?

Usually when their intent is specific, and non-trivial. For example, the STL containers data() function exists to intentionally expose implementation details for the purposes of genericism for the standard library.

Procedural style-structs

Breaking away from directly object-oriented styles, as implementation sometimes does; you may want to consider a simple struct (or class if you prefer) which acts as a data carrier; that is, they have all, or mostly, public properties. I would advise using a struct only for simple holders. This is opposed to a class ought to be used to establish some invariant in the constructor. In addition to private methods, static methods are a good way to illustrate invariants in a class. For example, a validation method. The invariant establishment on public data is also very good for immutable data.

An example:

// just holds some fields
struct simple_point {
    int x, y;
};

// holds from fields, but asserts invariant that coordinates
// must be in [0, 10].
class small_point {
  public:
    int x, y;

    small_point() noexcept : x{}, y{} {}
    small_point(int u, int v)
    {
        if (!small_point::valid(u) || !small_point::valid(u)) {
           throw std::invalid_argument("small_point: Invalid coordinate.");
        }

        x = u;
        y = v;
    }

    static valid(int v) noexcept { return 0 <= v && v <= 10; }
};
```

Body:
I'm writing a pretty large library, and I find myself writing almost identical accessors all the time. I already have several dozen accessors such as the one below.

Question: How can I declare/implement accessors to save typing all this repetitive code? (No #defines please; I'm looking for C++ constructs.)

Update: Yes, I do need accessor functions, because I need to take pointers to these accessors for something called Property Descriptors, which enable huge savings in my GUI code (non-library).

.h file

private:
    bool _visible;
public:
    bool GetVisible() const { return _visible; }
    void SetVisible (bool value);

// Repeat for Get/SetFlashing, Get/SetColor, Get/SetLineWidth, etc.

.cpp file

void Element::SetVisible (bool value)
{
    _visible = value;
    this->InvalidateSelf(); // Call method in base class
    // ...
    // A bit more code here, identical in 90% of my setters.
    // ...
}

// Repeat for Get/SetFlashing, Get/SetColor, Get/SetLineWidth, etc.