问:
iconv translit table of characters
iconv can convert special characters like ö (odiaeresis) to ascii characters like o when used with //TRANSLIT. Is there a table of characters somewhere that lists how those transformations work? I already poked around the source code but am not familiar enough with c to find what I'm looking for.</p>

答:
The table is defined in the file translit.def. You may find it inside the libiconv. The library might be download at: https://ftp.gnu.org/gnu/libiconv/.  I've extracted the first few lines of the table, which are displayed bellow:

```<code># Definition of transliteration from Unicode to poorer character sets.
#
# This covers all of Markus Kuhn's TARGET1.
#
# The second column gives the transliteration. It is enclosed between tabs!
#
00A0            # NO-BREAK SPACE
00A1    !       # INVERTED EXCLAMATION MARK
00A2    c       # CENT SIGN
00A3    lb      # POUND SIGN
00A4            # CURRENCY SIGN
00A5    yen     # YEN SIGN
00A6    |       # BROKEN BAR
00A7    SS      # SECTION SIGN
00A8    "       # DIAERESIS
 .
 .
 .
</code>```

You might see that ¡ (0x00A1) is translated into !, ¢ (0x00A2) is translated into c, £ (0x00A3) is translated into lb and so on...

Title: iconv translit table of characters

Body:
The table is defined in the file translit.def. You may find it inside the libiconv. The library might be download at: https://ftp.gnu.org/gnu/libiconv/.  I've extracted the first few lines of the table, which are displayed bellow:

# Definition of transliteration from Unicode to poorer character sets.
#
# This covers all of Markus Kuhn's TARGET1.
#
# The second column gives the transliteration. It is enclosed between tabs!
#
00A0            # NO-BREAK SPACE
00A1    !       # INVERTED EXCLAMATION MARK
00A2    c       # CENT SIGN
00A3    lb      # POUND SIGN
00A4            # CURRENCY SIGN
00A5    yen     # YEN SIGN
00A6    |       # BROKEN BAR
00A7    SS      # SECTION SIGN
00A8    "       # DIAERESIS
 .
 .
 .

You might see that ¡ (0x00A1) is translated into !, ¢ (0x00A2) is translated into c, £ (0x00A3) is translated into lb and so on...


来源: stackexchange

问:
Xamarin Forms iOS wrong Task icon
I think a have a really simple problem but I am not quite sure if I am doing something wrong or if this is a Xamarin issue.

I have an iOS Xamarin Forms project where I am unable to set the "task" icon which is shown in the "tasks" view when pressing twice the home button.

It shows always the xamarin icon. For all the other icons like launch icon the correct icon is shown.
I don't find any xamarin icon in my project. I have all the icons in Assets.xcassets for App Icon set.

Which icon should should change the "task" icon. Is this set at a different place?
What is the name for this icon?

Any help is appreciated.

Used Environment:

Visual Studio for Mac 8.5.6

Xamarin.iOS 13.16.0.13

Deployment Target iOS 13

Xamarin.Forms 4.6.8

Update

I meanwhile updated the development environment:

Visual Studio for Mac 8.6

Xamarin.iOS 13.18

The result is still the same:

答:
It was probably an issue with my environment/visual studio as it also occured with a new project.

I switch a few times between deploying different apps in release and debug mode and now it is working with the same code as before.

Seems like a chased a phantom for to many hours.

ContentLicense: CC BY-SA 4.0

Title: Xamarin Forms iOS wrong Task icon


问:
Sharing a URL with a query string on Twitter
I'm trying to put a Twitter share link in an email.  Because this is in an email I can't rely on JavaScript, and have to use the "Build Your Own" Tweet button.

For example, sharing a link to Google:

```<code><a href="http://www.twitter.com/share?url=http://www.google.com/>Tweet</a>
</code>```

This works fine.  The problem I'm having is when the URL has a query string.

```<code><a href="http://www.twitter.com/share?url=http://mysite.org/foo.htm?bar=123&baz=456">Tweet</a>
</code>```

URLs with query strings confuse Twitter's URL shortening service, t.co.  I've tried URL encoding this in various ways and cannot get anything to work.  The closest I have gotten is by doing this.

```<code><a href="http://www.twitter.com/share?url=http://mysite.org/foo.htm%3Fbar%3D123%26baz%3D456">Tweet</a>
</code>```

Here I've encoded only the query string.  When I do this, t.co successfully shortens the URL, but upon following the shortened link, it takes you to the encoded URL.  I see http://mysite.org/foo.htm%3Fbar%3D123%26baz%3D456 in the address bar, and get the following error in the browser

Not Found

The requested URL /foo.htm?bar=123&baz=456 was not found on this server.

I'm at a loss as to how to solve this problem.

Edit:  Re: onteria_

I've tried encoding the entire URL.  When I do that no URL shows up in the Tweet.

答:
This can be solved by using https://twitter.com/intent/tweet instead of http://www.twitter.com/share.  Using the intent/tweet function, you simply URL encode your entire URL and it works like a charm.

https://dev.twitter.com/web/intents

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to put a Twitter share link in an email.  Because this is in an email I can't rely on JavaScript, and have to use the "Build Your Own" Tweet button.

For example, sharing a link to Google:

Tweet

This works fine.  The problem I'm having is when the URL has a query string.

Tweet

URLs with query strings confuse Twitter's URL shortening service, t.co.  I've tried URL encoding this in various ways and cannot get anything to work.  The closest I have gotten is by doing this.

Tweet

Here I've encoded only the query string.  When I do this, t.co successfully shortens the URL, but upon following the shortened link, it takes you to the encoded URL.  I see http://mysite.org/foo.htm%3Fbar%3D123%26baz%3D456 in the address bar, and get the following error in the browser

Not Found

The requested URL /foo.htm?bar=123&baz=456 was not found on this server.

I'm at a loss as to how to solve this problem.

Edit:  Re: onteria_

I've tried encoding the entire URL.  When I do that no URL shows up in the Tweet.


问:
AWS S3 response FAILED, even though file is fully uploaded
I'm just trying to upload an image to S3 via an Android app. What I concluded so far is that images that are bigger than 5MB are uploaded without a problem, however, images that are smaller than 5MB are FULLY UPLOADED and can be downloaded from S3 manually, however, the response i get is FAILED. I just want to remind you that 5MB is the bottom threshold for issuing a multipart request (SDK uploads using multipart automatically when the file is above 5MB, I checked this in their code).

I also checked the md5 sum by hand, and the sums from two files (uploaded and selected for upload) MATCH.

I tested uploading small images using a AWS S3 CLI and it works without a problem.

This is the exception I get:

AmazonClientException: Unable to verify integrity of data upload.  Client calculated content hash didn't match hash calculated by Amazon S3.  You may need to delete the data stored in Amazon S3.

These are the libraries I am using:

com.amazonaws:aws-android-sdk-s3:$version

com.amazonaws:aws-android-sdk-mobile-client:$version

Any help would be much appreciated.

答:
Basically, the problem was that bucket where images were uploaded was encrypted, as soon as we created a new unencrypted bucket, the uploads were fine.
It seems that hash of two files was different because one hash calculation was done on an encrypted file and one on an unencrypted file. It seems (although I'm not completely sure) that multipart request just bypasses the md5 checksum check.

Important to mention, this was only happening while using the Android SDK, the iOS one works fine (don't know what are the exact differences in implementation, I could maybe update on that later).

It worked for months before the encryption was introduced.

I will investigate this issue further and notify AWS support if there is a reason for that.


问:
VBA defining Range with Cells() Error 1004
I am searching for a value and getting its Row with this, and I want to make a Range Variable with lRow and 2 (because it will always be 2), but it doesn't seem to work...

```<code>Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1
Dim newentry As Range
   Set newentry = Range(Cells(lRow, 2))
</code>```

Here, lRow = 3 is given as value...

Runtime error 1004: Method "Range" for object '_Global' failed

答:
If you use Cells inside Range you need to add 2 cells even you want to select 1 cell only:

```<code>Range(Cells(1, 1), Cells(1, 1)).Select
</code>```

your second cell is missing, that causes error

Body:
I am searching for a value and getting its Row with this, and I want to make a Range Variable with lRow and 2 (because it will always be 2), but it doesn't seem to work...

Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1
Dim newentry As Range
   Set newentry = Range(Cells(lRow, 2))

Here, lRow = 3 is given as value...

Runtime error 1004: Method "Range" for object '_Global' failed

Body:
If you use Cells inside Range you need to add 2 cells even you want to select 1 cell only:

Range(Cells(1, 1), Cells(1, 1)).Select

your second cell is missing, that causes error


问:
Typescript, React: TypeError: Cannot read property 'push' of undefined
Seems like a stupid problem, but I can't find out why it occures and what I did wrong even after I read error message and tried to find this sort of problem here

So the main goal is to add a book object into library array. No problems whit states, at least now, the should work correctly (console.log shows that everything's OK), exports and imports are correct in all files, I even have snippets in HiddenPanel.tsx file to use Library methods from Library.ts

Error: TypeError: Cannot read property 'push' of undefined
Function.push../src/Library.ts.Library.addBook
src/Library.ts:36

Line 36:

```<code>Library.library.push(book)
</code>```

Quick problem description: some problem with types which I can't figure out. Occures after pressing ADD (which calls push() from method in Library.class)

Files:
1. HiddenPanel.tsx
2. Library.ts

I have a Book class with constructor (Library.ts)

```<code>class Book {
    constructor(public author: string, public title: string, public pages: string, public rating: number) {
        title = title
        author = author
        pages = pages
        rating = rating
    }
}
</code>```

Book constructor call-method is located in Library class (Library.ts)

```<code>class Library {
    static library: Array<object>

    library = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ]

public static addBook = (title: string, author: string, pages: string, rating: number) => {

        let book = new Book(title, author, pages, rating)
        Library.library.push(book)
        console.log(Library.library)
    }
}
</code>```

Constructor is being called from HiddenPanel.tsx

```<code>class HiddenPanel extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props)
        this.state = {
            author: '',
            title: '',
            pages: '',
            rating: 0,
            value: '',
        }
    }

    ...some private methods here...

    private handleClick = () => {
        Library.addBook(this.state.author, this.state.title, this.state.pages, this.state.rating)
    }
    render() {
        return(
            <div className="add-book-section">
                ...some stuff here...
                <div onClick={this.handleClick} className="submit">ADD</div>

                </div>
        )
    }
}
</code>```

答:
Issue :

If you read the comments and run the below snippet, that will clear the reason behind the issue.

class Library {
    static library: Array<object> // <-- Declared but not initialized

    // ---- this is not static property, this will create a property for class
    library = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ]
}

console.log( 'Static Property' , Library.library);

const libObj = new Library();
console.log( 'Instance Property' , libObj.library);```
</div>
</div>
</p>

<p><strong>Solution :</strong> </p>

<p>You can initialized it with values directly :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Library {
    static library: Array<object> = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ]
}

console.log( 'Static Property' , Library.library);</code>```

Body:
Seems like a stupid problem, but I can't find out why it occures and what I did wrong even after I read error message and tried to find this sort of problem here

So the main goal is to add a book object into library array. No problems whit states, at least now, the should work correctly (console.log shows that everything's OK), exports and imports are correct in all files, I even have snippets in HiddenPanel.tsx file to use Library methods from Library.ts

Error: TypeError: Cannot read property 'push' of undefined
Function.push../src/Library.ts.Library.addBook
src/Library.ts:36

Line 36:

Library.library.push(book)

Quick problem description: some problem with types which I can't figure out. Occures after pressing ADD (which calls push() from method in Library.class)

Files:
1. HiddenPanel.tsx
2. Library.ts

I have a Book class with constructor (Library.ts)

class Book {
    constructor(public author: string, public title: string, public pages: string, public rating: number) {
        title = title
        author = author
        pages = pages
        rating = rating
    }
}

Book constructor call-method is located in Library class (Library.ts)

class Library {
    static library: Array<object>

    library = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ]

public static addBook = (title: string, author: string, pages: string, rating: number) => {

        let book = new Book(title, author, pages, rating)
        Library.library.push(book)
        console.log(Library.library)
    }
}

Constructor is being called from HiddenPanel.tsx

class HiddenPanel extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props)
        this.state = {
            author: '',
            title: '',
            pages: '',
            rating: 0,
            value: '',
        }
    }

    ...some private methods here...

    private handleClick = () => {
        Library.addBook(this.state.author, this.state.title, this.state.pages, this.state.rating)
    }
    render() {
        return(

                ...some stuff here...

ADD

        )
    }
}

Body:
Issue :

If you read the comments and run the below snippet, that will clear the reason behind the issue.

class Library {
    static library: Array<object> // <-- Declared but not initialized

    // ---- this is not static property, this will create a property for class
    library = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ]
}

console.log( 'Static Property' , Library.library);

const libObj = new Library();
console.log( 'Instance Property' , libObj.library);

Solution :

You can initialized it with values directly :

class Library {
    static library: Array<object> = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ]
}

console.log( 'Static Property' , Library.library);


问:
"Error: Must subset rows with a valid subscript vector" in preProcess() when using knnImpute
I'm using kaggle's pokemon data to practice KNN imputation via preProcess(), but when I did I encountered this following message after the predict() step. I am wondering if I use the incorrect data format or if some columns have inappropriate "class." Below is my code.

library(dplyr)
library(ggplot2)
library(tidyr)
library(reshape2)
library(caret)
library(skimr)
library(psych)
library(e1071)
library(data.table)

pokemon <- read.csv("https://www.dropbox.com/s/znbta9u9tub2ox9/pokemon.csv?dl=1")

pokemon = tbl_df(pokemon)

# select relevant features

df <- select(pokemon, hp, weight_kg, height_m, sp_attack, sp_defense, capture_rate)

pre_process_missing_data <- preProcess(df, method="knnImpute")
classify_legendary <- predict(pre_process_missing_data, newdata = df)```
</div>
</div>
</p>

<p>and I received this error message</p>

```Error: Must subset rows with a valid subscript vector.
x Subscript `nn$nn.idx` must be a simple vector, not a matrix.
Run `rlang::last_error()` to see where the error occurred.
```

Body:
I'm using kaggle's pokemon data to practice KNN imputation via preProcess(), but when I did I encountered this following message after the predict() step. I am wondering if I use the incorrect data format or if some columns have inappropriate "class." Below is my code.

library(dplyr)
library(ggplot2)
library(tidyr)
library(reshape2)
library(caret)
library(skimr)
library(psych)
library(e1071)
library(data.table)

pokemon <- read.csv("https://www.dropbox.com/s/znbta9u9tub2ox9/pokemon.csv?dl=1")

pokemon = tbl_df(pokemon)

# select relevant features

df <- select(pokemon, hp, weight_kg, height_m, sp_attack, sp_defense, capture_rate)

pre_process_missing_data <- preProcess(df, method="knnImpute")
classify_legendary <- predict(pre_process_missing_data, newdata = df)

and I received this error message

Error: Must subset rows with a valid subscript vector.
x Subscript `nn$nn.idx` must be a simple vector, not a matrix.
Run `rlang::last_error()` to see where the error occurred.

Body:
The input for preProcess needs to be a data.frame. This works:

pre_process_missing_data <- preProcess(as.data.frame(df), method="knnImpute")

classify_legendary <- predict(pre_process_missing_data, newdata = df)
classify_legendary

> classify_legendary
# A tibble: 801 x 6
       hp weight_kg height_m sp_attack sp_defense capture_rate
    <dbl>     <dbl>    <dbl>     <dbl>      <dbl> <chr>
 1 -0.902    -0.498  -0.429     -0.195     -0.212 45
 2 -0.337    -0.442  -0.152      0.269      0.325 45
 3  0.415     0.353   0.774      1.57       1.76  45
 4 -1.13     -0.484  -0.522     -0.349     -0.748 45
 5 -0.412    -0.388  -0.0591     0.269     -0.212 45
 6  0.340     0.266   0.496      2.71       1.58  45
 7 -0.939    -0.479  -0.615     -0.659     -0.247 45
 8 -0.375    -0.356  -0.152     -0.195      0.325 45
 9  0.378     0.221   0.404      1.97       1.58  45
10 -0.902    -0.535  -0.800     -1.59      -1.82  255
# ... with 791 more rows


问:
Installing Redis use ./install_server.sh
when I Execute the command ./install_server.sh an error has occurred. error message as follow:
This system seems to use systemd.
Please take a look at the provided example service unit files in this directory, and adapt and install them. Sorry!
I don't know how to solve this problem, please help me

```<code>% cd utils
% ./install_server.sh
</code>```

error message

```<code>This systems seems to use systemd.
Please take a look at the provided example service unit files in this directory, and adapt and install them. Sorry!
</code>```

答:
Steps I followed to make it run in my system

Comment out following lines in redis-stable/utils/instal_server.sh file

```<code>#bail if this system is managed by systemd
#_pid_1_exe="$(readlink -f /proc/1/exe)"
#if [ "${_pid_1_exe##*/}" = systemd ]
#then
#       echo "This systems seems to use systemd."
#       echo "Please take a look at the provided example service unit files in this directory, and adapt and install them. Sorry!"
#       exit 1
#fi
</code>```

After this, you need to install tcl tk

for ubuntu: sudo apt-get install -y tcl tk

for RedHat: sudo yum install tcl tk

then inside redis-stable/src
run sudo make install

if it shows error like
Hint: It's a good idea to run 'make test' ;)

go back to redis-stable and run make distclean and again sudo make install

Finally, run the server by running redis-server

Atlast to check if Redis is working: redis-cli ping

Body:
when I Execute the command ./install_server.sh an error has occurred. error message as follow:
This system seems to use systemd.
Please take a look at the provided example service unit files in this directory, and adapt and install them. Sorry!
I don't know how to solve this problem, please help me

% cd utils
% ./install_server.sh

error message

This systems seems to use systemd.
Please take a look at the provided example service unit files in this directory, and adapt and install them. Sorry!

Body:
Steps I followed to make it run in my system

Comment out following lines in redis-stable/utils/instal_server.sh file

#bail if this system is managed by systemd
#_pid_1_exe="$(readlink -f /proc/1/exe)"
#if [ "${_pid_1_exe##*/}" = systemd ]
#then
#       echo "This systems seems to use systemd."
#       echo "Please take a look at the provided example service unit files in this directory, and adapt and install them. Sorry!"
#       exit 1
#fi

After this, you need to install tcl tk

for ubuntu: sudo apt-get install -y tcl tk

for RedHat: sudo yum install tcl tk

then inside redis-stable/src
run sudo make install

if it shows error like
Hint: It's a good idea to run 'make test' ;)

go back to redis-stable and run make distclean and again sudo make install

Finally, run the server by running redis-server

Atlast to check if Redis is working: redis-cli ping


问:
How to programmatically add a css rule to an element
I am using Angular 6 and Typescript. Here's my issue. I need to add a specific CSS rule to the host of a component that I am writing. I cannot apply that rule systematically, I need to have some logic in ngOnInit() before adding my rule. I know this sounds like bad practice, but there are no workarounds and this is the only way I can solve the problem I am facing. I can easily add classes on new styles to my host, but I cannot seem to find a way to add a rule.

Some people have been marking my question as a duplicate. Please read my question carefully. I am not trying to add a class, I am trying to a add a RULE. This is very different and there are no results for such question.

Here's the two rules I have that I want to add to my host element depending on some condition:

```<code>custom-component + custom-component > .vertical-component {
    margin-top: 1rem;
}
</code>```

and

```<code>custom-component + custom-component > .horizontal-component {
    margin-left: 1rem;
}
</code>```

In my component code, I have something like this:

```<code>export class CustomComponent {
    public constructor(private host: ElementRef, private renderer: Renderer2) {

    }

    public applyStylesToHost(): void {
        if (this.variant == TYPE.VERTICAL) {
            // Set the rule with the margin-top
        } else {
            // Set the rule with the margin-left
        }
    }
}
</code>```

I was looking for a method like this.renderer.setRule(), but there is no such thing. How can I programmatically add a specific rule to my host element?

The closest thing I found is this link. The author suggest doing document.createElement("style").sheet.addRule(), but when I tried to do it, the method addRule didn't exist on the sheet element.

答:
As Balastrong mentions you could use ngClass
logicFinished = false

```<code>ngOnInit() {
  ... your logic
  this.logicFinished = true
}

[ngClass]="{'vertical-component': logicFinished, 'horizontal-component': !logicFinished}"
</code>```

Alternative javascript hack to fix the problem.

```<code>this.yourElement = document.getElementById('yourElement') as HTMLElement
this.yourElement.style.margin = '1rem 0 0 0'
this.yourElement.style.margin = '0 0 0 1rem'
</code>```

But NgClass seems a better solution for the problem.

Body:
I am using Angular 6 and Typescript. Here's my issue. I need to add a specific CSS rule to the host of a component that I am writing. I cannot apply that rule systematically, I need to have some logic in ngOnInit() before adding my rule. I know this sounds like bad practice, but there are no workarounds and this is the only way I can solve the problem I am facing. I can easily add classes on new styles to my host, but I cannot seem to find a way to add a rule.

Some people have been marking my question as a duplicate. Please read my question carefully. I am not trying to add a class, I am trying to a add a RULE. This is very different and there are no results for such question.

Here's the two rules I have that I want to add to my host element depending on some condition:

custom-component + custom-component > .vertical-component {
    margin-top: 1rem;
}

and

custom-component + custom-component > .horizontal-component {
    margin-left: 1rem;
}

In my component code, I have something like this:

export class CustomComponent {
    public constructor(private host: ElementRef, private renderer: Renderer2) {

    }

    public applyStylesToHost(): void {
        if (this.variant == TYPE.VERTICAL) {
            // Set the rule with the margin-top
        } else {
            // Set the rule with the margin-left
        }
    }
}

I was looking for a method like this.renderer.setRule(), but there is no such thing. How can I programmatically add a specific rule to my host element?

The closest thing I found is this link. The author suggest doing document.createElement("style").sheet.addRule(), but when I tried to do it, the method addRule didn't exist on the sheet element.

Body:
As Balastrong mentions you could use ngClass
logicFinished = false

ngOnInit() {
  ... your logic
  this.logicFinished = true
}

[ngClass]="{'vertical-component': logicFinished, 'horizontal-component': !logicFinished}"

Alternative javascript hack to fix the problem.

this.yourElement = document.getElementById('yourElement') as HTMLElement
this.yourElement.style.margin = '1rem 0 0 0'
this.yourElement.style.margin = '0 0 0 1rem'

But NgClass seems a better solution for the problem.


问:
Passing images from one page to another in Xamarin Forms
In  my app I need to pass images from one page to another page image view to display. I am taking a photo from camera and do some stuffs, then I want to send that images to the second page.

```<code>            if (await isCamAvailable())
            {

                 MediaFile photo1 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions() { Directory = "NewBusiness", Name = "image1.jpg", PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 1024, CompressionQuality = 95 });

                if (photo1 != null)
                {
                    PhotoImage1.Source = ImageSource.FromStream(() => { return photo1.GetStream(); });
                    countList.Remove("a");
                    countList.Add("a");
                }

            }
</code>```

Then I am added it to a string array by doing

```<code>        private List<string> sendImgList = new List<string>();

        sendImgList.Add(createImgByteString(photo1.GetStream()));

        private string createImgByteString(Stream data)
        {
            var bytes = new byte[data.Length];
            return Convert.ToBase64String(bytes);
        }
</code>```

Then from second page (for testing i just added only one image)

```<code>        foreach (string ss in imgList) {

            byte[] Base64Stream = Convert.FromBase64String(ss);
            imgView.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));

        }
</code>```

I followed this example. But image not showing.

https://forums.xamarin.com/discussion/139360/how-to-transfer-images-from-one-page-to-another

Also getting this in logcat..

```<code>[0:] ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource05-29 14:22:43.758 W/monodroid-assembly( 8737): typemap: unable to find mapping to a Java type from managed type 'System.Byte, mscorlib'
</code>```

答:
The best mode to pass parameter in pages is with Prism.

https://prismlibrary.com/docs/xamarin-forms/navigation/passing-parameters.html

>

```<code>_navigationService.NavigateAsync(new Uri("MainPage", new NavigationParameters
{
    { "key_parameter", image }
})));
</code>```

And on other page:

>

```<code>public override void OnNavigatedTo(INavigationParameters parameters)
{
    image = (Image)parameters["key_parameter"];
}
</code>```

Body:
In  my app I need to pass images from one page to another page image view to display. I am taking a photo from camera and do some stuffs, then I want to send that images to the second page.

            if (await isCamAvailable())
            {

                 MediaFile photo1 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions() { Directory = "NewBusiness", Name = "image1.jpg", PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 1024, CompressionQuality = 95 });

                if (photo1 != null)
                {
                    PhotoImage1.Source = ImageSource.FromStream(() => { return photo1.GetStream(); });
                    countList.Remove("a");
                    countList.Add("a");
                }

            }

Then I am added it to a string array by doing

        private List<string> sendImgList = new List<string>();

        sendImgList.Add(createImgByteString(photo1.GetStream()));

        private string createImgByteString(Stream data)
        {
            var bytes = new byte[data.Length];
            return Convert.ToBase64String(bytes);
        }

Then from second page (for testing i just added only one image)

        foreach (string ss in imgList) {

            byte[] Base64Stream = Convert.FromBase64String(ss);
            imgView.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));

        }

I followed this example. But image not showing.

https://forums.xamarin.com/discussion/139360/how-to-transfer-images-from-one-page-to-another

Also getting this in logcat..

[0:] ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource05-29 14:22:43.758 W/monodroid-assembly( 8737): typemap: unable to find mapping to a Java type from managed type 'System.Byte, mscorlib'

Body:
The best mode to pass parameter in pages is with Prism.

https://prismlibrary.com/docs/xamarin-forms/navigation/passing-parameters.html

>

_navigationService.NavigateAsync(new Uri("MainPage", new NavigationParameters
{
    { "key_parameter", image }
})));

And on other page:

>

public override void OnNavigatedTo(INavigationParameters parameters)
{
    image = (Image)parameters["key_parameter"];
}


问:
ruby thinks I'm referencing a top-level constant even when I specify the full namespace
In my app I have

```<code>class User
  include User::Foo
end
</code>```

User::Foo is defined in app/models/user/foo.rb

Now I'm using a library that defines its own Foo class. I'm getting this error:

warning: toplevel constant Foo referenced by User::Foo

User only refers to Foo with the full path, User::Foo, and Foo never actually refers to Foo.

What's going on?

update: just remembered I had the same problem before, seen here in question 1: How do I refer to a submodule's "full path" in ruby?

答:
Make sure the User::Foo definition you want is visible

The message says: the only definition it found was at the top level. This is obviously suspicious since you went to the trouble of qualifying the name.

There isn't a good way to say you want a different ::User.  It's a class and ruby will look for a definition there, then at the top level. You need to somehow specify the module without referencing your class.

One way to fix this:

```<code>module Other
  class User
    include ::User::Foo
  end
end
</code>```

Body:
In my app I have

class User
  include User::Foo
end

User::Foo is defined in app/models/user/foo.rb

Now I'm using a library that defines its own Foo class. I'm getting this error:

warning: toplevel constant Foo referenced by User::Foo

User only refers to Foo with the full path, User::Foo, and Foo never actually refers to Foo.

What's going on?

update: just remembered I had the same problem before, seen here in question 1: How do I refer to a submodule's "full path" in ruby?

Body:
Make sure the User::Foo definition you want is visible

The message says: the only definition it found was at the top level. This is obviously suspicious since you went to the trouble of qualifying the name.

There isn't a good way to say you want a different ::User.  It's a class and ruby will look for a definition there, then at the top level. You need to somehow specify the module without referencing your class.

One way to fix this:

module Other
  class User
    include ::User::Foo
  end
end


问:
Same custom set property for some class field
I want every time that TextBox filed is set the back color change according to the sign.

```<code>    public TextBox Current_value_text1
    {
        get { return Current_value_text; }
        set {
                Current_value_text = value;
                if (Current_value_text.Text[0] == '+')
                    Current_value_text.BackColor = Color.Green;
                else
                    Current_value_text.BackColor = Color.Red;
            }
    }
</code>```

but I want to do this for all my textbox fields - any suggestions?

Thanks

答:
You are probably looking for TextChanged event: whenever TextBox(es) change its Text, analyze it and update BackColor when necessary.

If it's your case, can select all the Textboxes (say, with a mouse), open "Properties" window and implement event hander for the TextChanged:

```<code> private void myTextBox_TextChanged(object sender, EventArgs e) {
   TextBox box = sender as TextBox;

   if (null == box)
     return;

   box.BackColor = box.Text.Trim().StartsWith("-")
     ? Color.Red
     : Color.Green;
 }
</code>```

EDIT: The question in the comment is a quite different case; here we don't have events, but we can try extracting a method (NumSet):

```<code> private int m_Num1;
 private int m_Num2;

 private void NumSet(ref int num, int value) {
   if (value == 1)
     num = value + 1;
   else
     num = value - 1;
 }

 public int Num1 {
   get => m_Num1;
   set => NumSet(ref m_Num1, value);
 }

 public int Num2 {
   get => m_Num2;
   set => NumSet(ref m_Num2, value);
 }
</code>```

Body:
I want every time that TextBox filed is set the back color change according to the sign.

    public TextBox Current_value_text1
    {
        get { return Current_value_text; }
        set {
                Current_value_text = value;
                if (Current_value_text.Text[0] == '+')
                    Current_value_text.BackColor = Color.Green;
                else
                    Current_value_text.BackColor = Color.Red;
            }
    }

but I want to do this for all my textbox fields - any suggestions?

Thanks

Body:
You are probably looking for TextChanged event: whenever TextBox(es) change its Text, analyze it and update BackColor when necessary.

If it's your case, can select all the Textboxes (say, with a mouse), open "Properties" window and implement event hander for the TextChanged:

 private void myTextBox_TextChanged(object sender, EventArgs e) {
   TextBox box = sender as TextBox;

   if (null == box)
     return;

   box.BackColor = box.Text.Trim().StartsWith("-")
     ? Color.Red
     : Color.Green;
 }

EDIT: The question in the comment is a quite different case; here we don't have events, but we can try extracting a method (NumSet):

 private int m_Num1;
 private int m_Num2;

 private void NumSet(ref int num, int value) {
   if (value == 1)
     num = value + 1;
   else
     num = value - 1;
 }

 public int Num1 {
   get => m_Num1;
   set => NumSet(ref m_Num1, value);
 }

 public int Num2 {
   get => m_Num2;
   set => NumSet(ref m_Num2, value);
 }


问:
django: Force cache-refresh after update
After updating a model instance, I redirect back to this instance "detail page". Part of the model is an image generated from the models content.
In this redirect I want to force the browser to reload the image from the server. I tried it with headers but that doesn't work:

```<code>response = HttpResponseRedirect('/target/path/')
response['Cache-Control'] =  'no-cache'
response['Pragma'] = 'no-cache'
return response
</code>```

Because I assume the redirect loses the headers.

How can I force the page to reload the image but only after user returns from update page?

EDIT:

the image is served in an img tag. The src actually points to a server end-point that generates the image form the "id" in the src link.  Then the image should be cached until it changes.

答:
How are you serving the image? A good idea would be to add a hash on to the end of the filename for the image, and then when you update the image, change that hash. This way, when the image is updated the browser is forced to reload the image.

You could even just use a timestamp of when the file was last updated??

Body:
After updating a model instance, I redirect back to this instance "detail page". Part of the model is an image generated from the models content.
In this redirect I want to force the browser to reload the image from the server. I tried it with headers but that doesn't work:

response = HttpResponseRedirect('/target/path/')
response['Cache-Control'] =  'no-cache'
response['Pragma'] = 'no-cache'
return response

Because I assume the redirect loses the headers.

How can I force the page to reload the image but only after user returns from update page?

EDIT:

the image is served in an img tag. The src actually points to a server end-point that generates the image form the "id" in the src link.  Then the image should be cached until it changes.


问:
Resilience4j returning a CompletableFuture around tried method
I can't find out how to wrap a synchronous method with Resilience4j so that it returns a CompletableFuture, although this seems to be part of Resilience4j's target area.
Especially since the synchronous method I want to wrap can throw an Exception.
What I want in pseudo code:

boolean void syncMethod() throws Exception {
    // May throw Exception due to connection/authorization problems.
}

CompletableFuture<Boolean> asyncResilience4jWrapper() {
    CompletableFuture<Boolean> result =
        ...
            Resilience4j magic around "syncMethod()".
            Trying 4 calls, interval between calls of 100 ms.
        ...;
    return result;
}
```

Resilience4j should just try to call the method 4 times until it gives up, with intervals between the calls of 100 ms and then complete the asynchronous call.
The asyncResilience4jWrapper caller should just get back a CompletableFuture which doesn't block and don't care about any of that.

答:
```<code>ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
TimeLimiter timeLimiter = TimeLimiter.of(Duration.ofSeconds(1));

CompletableFuture<Boolean> future = Decorators.ofCallable(() -> syncMethod)
    .withThreadPoolBulkhead(threadPoolBulkhead)
    .withTimeLimiter(timeLimiter, scheduledExecutorService)
    .withCircuitBreaker(circuitBreaker)
    .withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
      throwable -> "Hello from Recovery")
    .get().toCompletableFuture();
</code>```

Just add withRetry below the CircuitBreaker.

Body:
I can't find out how to wrap a synchronous method with Resilience4j so that it returns a CompletableFuture, although this seems to be part of Resilience4j's target area.
Especially since the synchronous method I want to wrap can throw an Exception.
What I want in pseudo code:

boolean void syncMethod() throws Exception {
    // May throw Exception due to connection/authorization problems.
}

CompletableFuture<Boolean> asyncResilience4jWrapper() {
    CompletableFuture<Boolean> result =
        ...
            Resilience4j magic around "syncMethod()".
            Trying 4 calls, interval between calls of 100 ms.
        ...;
    return result;
}

Resilience4j should just try to call the method 4 times until it gives up, with intervals between the calls of 100 ms and then complete the asynchronous call.
The asyncResilience4jWrapper caller should just get back a CompletableFuture which doesn't block and don't care about any of that.

Body:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
TimeLimiter timeLimiter = TimeLimiter.of(Duration.ofSeconds(1));

CompletableFuture<Boolean> future = Decorators.ofCallable(() -> syncMethod)
    .withThreadPoolBulkhead(threadPoolBulkhead)
    .withTimeLimiter(timeLimiter, scheduledExecutorService)
    .withCircuitBreaker(circuitBreaker)
    .withFallback(asList(TimeoutException.class, CallNotPermittedException.class, BulkheadFullException.class),
      throwable -> "Hello from Recovery")
    .get().toCompletableFuture();

Just add withRetry below the CircuitBreaker.


答:
Try defining your class like this..</p>

```<code>class Library {
  static library = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ];
}
</code>```

Title: Typescript, React: TypeError: Cannot read property 'push' of undefined

Body:
Seems like a stupid problem, but I can't find out why it occures and what I did wrong even after I read error message and tried to find this sort of problem here

So the main goal is to add a book object into library array. No problems whit states, at least now, the should work correctly (console.log shows that everything's OK), exports and imports are correct in all files, I even have snippets in HiddenPanel.tsx file to use Library methods from Library.ts

Error: TypeError: Cannot read property 'push' of undefined
Function.push../src/Library.ts.Library.addBook
src/Library.ts:36

Line 36:

Library.library.push(book)

Quick problem description: some problem with types which I can't figure out. Occures after pressing ADD (which calls push() from method in Library.class)

Files:
1. HiddenPanel.tsx
2. Library.ts

I have a Book class with constructor (Library.ts)

class Book {
    constructor(public author: string, public title: string, public pages: string, public rating: number) {
        title = title
        author = author
        pages = pages
        rating = rating
    }
}

Book constructor call-method is located in Library class (Library.ts)

class Library {
    static library: Array<object>

    library = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ]

public static addBook = (title: string, author: string, pages: string, rating: number) => {

        let book = new Book(title, author, pages, rating)
        Library.library.push(book)
        console.log(Library.library)
    }
}

Constructor is being called from HiddenPanel.tsx

class HiddenPanel extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props)
        this.state = {
            author: '',
            title: '',
            pages: '',
            rating: 0,
            value: '',
        }
    }

    ...some private methods here...

    private handleClick = () => {
        Library.addBook(this.state.author, this.state.title, this.state.pages, this.state.rating)
    }
    render() {
        return(

                ...some stuff here...

ADD

        )
    }
}

Body:
Try defining your class like this..

class Library {
  static library = [
        {
        author: 'Johann Fjord Kallenberg',
        title: 'Norvegian dragonslayers',
        pages: '443',
        rating: 4
        }, {
        author: 'Dungo McCallahey',
        title: 'Irish Golden Era',
        pages: '318',
        rating: 3
        }, {
        author: 'John Doe Mouse',
        title: 'Preparing to fight a Wolfgod',
        pages: '714',
        rating: 4
        }
    ];
}


问:
PermissionError: [Errno 13] Permission denied to access selenium python through webdriver-manager
I recently installed webdriver-manager 2.5.2 to work with chromedriver for selenium in python. It was working fine, but now suddenly i am getting the below error-
PermissionError: [Errno 13] Permission denied: 'C:\Users\mrudu\.wdm\drivers\chromedriver\83.0.4103.39\win32\chromedriver.exe'

How to resolve this issue? I am new to programming so not sure how the permissions work in windows 10 and Pycharm.
Please help

答:
It worked when i did this-
There is some process that is holding this driver. Close all Chrome drivers, and try to find all processes with name chromedriver.exe.

Solution provided by SergeyPirogov github owner for webdriver-manager


问:
How can I 'translate' all unicode codes in a string to the actual symbols using Python 3?
I'm parsing web content to isolate the body of news articles from a certain site, for which I'm using urllib.request to retrieve the source code for the article webpage and isolate the main text. However, urllib takes characters like "ç" and puts it into a python string as its utf-8 notation, "c387". It does the same for the '”' and "„" characters, which print as an 'e' followed by a set of numbers. This is very irritating when trying to read the article and thus needs to be resolved. I could loop through the article and change every recognizable utf-8 code to the actual character using a tedious function, but I was wondering if there was a way to do that more easily.

For an example, the current output of my program might be:
e2809eThis country doesn't...e2809d

I would like it to be:
„This country doesn't...”

Note: I've already checked the source code of the web page, which just uses these 'special' characters, so it's definitely a urllib issue.

Thanks in advance!

答:
urllib returns bytes:

```<code>>import urllib
>url = 'https://stackoverflow.com/questions/62085906'
>data = urllib.request.urlopen(url).read()
>type(data)
bytes
>idx = data.index(b'characters like')
>data[idx:idx+20]
b'characters like "\xc3\xa7"'
</code>```

Now, let's try to interpret this as utf-8:

```<code>>data[idx:idx+20].decode('utf-8')
'characters like "ç"'
</code>```

Et voilà!

Body:
urllib returns bytes:

>import urllib
>url = 'https://stackoverflow.com/questions/62085906'
>data = urllib.request.urlopen(url).read()
>type(data)
bytes
>idx = data.index(b'characters like')
>data[idx:idx+20]
b'characters like "\xc3\xa7"'

Now, let's try to interpret this as utf-8:

>data[idx:idx+20].decode('utf-8')
'characters like "ç"'

Et voilà!


问:
Error while training CNN for text classification in keras "ValueError: Input 0 is incompatible with layer"
I am building a prediction model for sequence data using conv1d layer provided by Keras. This is how I did

```<code>input_layer = Input(shape=(500,))
layer = Conv1D(128,5,activation="relu")(input_layer)
layer = MaxPooling1D(pool_size=2)(layer)
layer = Flatten()(layer)
layer = Dense(128, activation='relu')(layer)
output_layer = Dense(10, activation='softmax')(layer)
classifier = Model(input_layer, output_layer)
classifier.summary()
classifier.compile(optimizer=optimizers.Adam(), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return classifier
</code>```

However, am facing the following error:

```<code>Traceback (most recent call last):
File "train.py", line 71, in <module>
classifier = create_cnn_model()
File "train.py", line 60, in create_cnn_model
layer = Conv1D(128,5, activation="relu")(input_layer)
File "C:\Python368\lib\site-packages\keras\backend\tensorflow_backend.py", line 75, in symbolic_fn
_wrapper
return func(*args, **kwargs)
File "C:\Python368\lib\site-packages\keras\engine\base_layer.py", line 446, in __call__
self.assert_input_compatibility(inputs)
File "C:\Python368\lib\site-packages\keras\engine\base_layer.py", line 342, in assert_input_compat
ibility
str(K.ndim(x)))
ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=2
</code>```

I think the input_shape in the first layer is not setup right. How to set it up?

答:
Right, conv layers need 3 dimensional input.
I am assuming you have a univariate time series with 500 samples.
You need to write a function to split the time series into steps.
For example:

```<code>     x             y
[t-n,...,t-2,t-1]  t
</code>```

So you are basically using the last n values to predict the next value in your series.
Then your input shape will be [len(x), n, 1]

Body:
I am building a prediction model for sequence data using conv1d layer provided by Keras. This is how I did

input_layer = Input(shape=(500,))
layer = Conv1D(128,5,activation="relu")(input_layer)
layer = MaxPooling1D(pool_size=2)(layer)
layer = Flatten()(layer)
layer = Dense(128, activation='relu')(layer)
output_layer = Dense(10, activation='softmax')(layer)
classifier = Model(input_layer, output_layer)
classifier.summary()
classifier.compile(optimizer=optimizers.Adam(), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return classifier

However, am facing the following error:

Traceback (most recent call last):
File "train.py", line 71, in <module>
classifier = create_cnn_model()
File "train.py", line 60, in create_cnn_model
layer = Conv1D(128,5, activation="relu")(input_layer)
File "C:\Python368\lib\site-packages\keras\backend\tensorflow_backend.py", line 75, in symbolic_fn
_wrapper
return func(*args, **kwargs)
File "C:\Python368\lib\site-packages\keras\engine\base_layer.py", line 446, in __call__
self.assert_input_compatibility(inputs)
File "C:\Python368\lib\site-packages\keras\engine\base_layer.py", line 342, in assert_input_compat
ibility
str(K.ndim(x)))
ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=2

I think the input_shape in the first layer is not setup right. How to set it up?

Body:
Right, conv layers need 3 dimensional input.
I am assuming you have a univariate time series with 500 samples.
You need to write a function to split the time series into steps.
For example:

     x             y
[t-n,...,t-2,t-1]  t

So you are basically using the last n values to predict the next value in your series.
Then your input shape will be [len(x), n, 1]


问:
QueryDSL how to add ParamExpression to JPAQuery to be executed with EntityManager.createQuery

Hi, I'd like to create JPA query with parameters using QueryDSL, the code is like

```<code>private static JPAQuery<Tuple> projectionQuery(JPAQuery<?> query, QCoupon qCoupon, QCouponApplication qCouponApplication) {
        return query.select(
                qCoupon.id,
                qCoupon.code,
                qCoupon.status,
                qCoupon.amount,
                qCoupon.benefitType,
                qCoupon.maxDiscountPerApplication,
                qCoupon.additionalMonth,
                qCouponApplication.count().as("usedQuota"),
                qCoupon.globalQuota,
                qCoupon.basePriceOnly
        );
    }

public GetCouponsResponseDTO getCouponsRewrited(String code, ZonedDateTime startCreatedDate, ZonedDateTime endCreatedDate, CouponStatus status, Integer pageNumber, Integer pageSize) {
        QCoupon qCoupon = QCoupon.coupon;
        QCouponApplication qCouponApplication = QCouponApplication.couponApplication;
        PageRequest pageRequest = new PageRequest(pageNumber, pageSize);
        JPAQuery<?> query =
                        projectionQuery(new JPAQuery<>(), qCoupon, qCouponApplication)
                        .from(qCoupon).leftJoin(qCoupon.applications, qCouponApplication)
                        .groupBy(qCoupon)
                        .orderBy(new OrderSpecifier<>(Order.DESC, qCoupon.createdAt));

        if (StringUtils.isNotBlank(code)) {
            ParamExpression<String> codeParam = new ParamExpressionImpl<>(String.class);
            query = query.where(qCoupon.code.likeIgnoreCase(codeParam)).set(codeParam, '%' + code + '%');
        }
        if (Objects.nonNull(startCreatedDate)) {
            ParamExpression<ZonedDateTime> createdAtParam = new ParamExpressionImpl<>(ZonedDateTime.class);
            query = query.where(qCoupon.createdAt.goe(createdAtParam)).set(createdAtParam, startCreatedDate);
        }
        if (Objects.nonNull(endCreatedDate)) {
            ParamExpression<ZonedDateTime> endedAtParam = new ParamExpressionImpl<>(ZonedDateTime.class);
            query = query.where(qCoupon.createdAt.loe(endedAtParam)).set(endedAtParam, endCreatedDate);
        }
        ......
       final String queryString = query.toString();
       final TypedQuery<Object[]> typedQuery = entityManager.createQuery(queryString, Object[].class)
                .setFirstResult(pageRequest.getOffset())
                .setMaxResults(pageRequest.getPageSize());

        for (Map.Entry<ParamExpression<?>, Object> paramExpressionObjectEntry : query.getMetadata().getParams().entrySet()) {
            ParamExpression<?> paramExpression = paramExpressionObjectEntry.getKey();
            typedQuery.setParameter(paramExpression.getName(), paramExpressionObjectEntry.getValue());
        }

        List<Object[]> queryResult = typedQuery
                .getResultList();
</code>```

The problem is the queryString variable contains unnamed parameter like where lower(coupon.code) like lower(?1) not as expected with named parameter that starts with :. I've tried using name, adding second constructor argument in ParamExpressionImpl like new ParamExpressionImpl<>(String.class, qCoupon.code.getMetadata().getName()) it's just same.

As a result it returns with exception message Parameter with that name [code] did not exist.
How's the correct use of QueryDSL's ParamExpression on the typedQuery.setParameter(...) line?

答: Instead of ParamExpressionImpl you should use com.querydsl.core.types.dsl.Param, which also takes a String argument which will be the name of the parameter (:parameter).

Body:
Hi, I'd like to create JPA query with parameters using QueryDSL, the code is like

private static JPAQuery<Tuple> projectionQuery(JPAQuery<?> query, QCoupon qCoupon, QCouponApplication qCouponApplication) {
        return query.select(
                qCoupon.id,
                qCoupon.code,
                qCoupon.status,
                qCoupon.amount,
                qCoupon.benefitType,
                qCoupon.maxDiscountPerApplication,
                qCoupon.additionalMonth,
                qCouponApplication.count().as("usedQuota"),
                qCoupon.globalQuota,
                qCoupon.basePriceOnly
        );
    }

public GetCouponsResponseDTO getCouponsRewrited(String code, ZonedDateTime startCreatedDate, ZonedDateTime endCreatedDate, CouponStatus status, Integer pageNumber, Integer pageSize) {
        QCoupon qCoupon = QCoupon.coupon;
        QCouponApplication qCouponApplication = QCouponApplication.couponApplication;
        PageRequest pageRequest = new PageRequest(pageNumber, pageSize);
        JPAQuery<?> query =
                        projectionQuery(new JPAQuery<>(), qCoupon, qCouponApplication)
                        .from(qCoupon).leftJoin(qCoupon.applications, qCouponApplication)
                        .groupBy(qCoupon)
                        .orderBy(new OrderSpecifier<>(Order.DESC, qCoupon.createdAt));

        if (StringUtils.isNotBlank(code)) {
            ParamExpression<String> codeParam = new ParamExpressionImpl<>(String.class);
            query = query.where(qCoupon.code.likeIgnoreCase(codeParam)).set(codeParam, '%' + code + '%');
        }
        if (Objects.nonNull(startCreatedDate)) {
            ParamExpression<ZonedDateTime> createdAtParam = new ParamExpressionImpl<>(ZonedDateTime.class);
            query = query.where(qCoupon.createdAt.goe(createdAtParam)).set(createdAtParam, startCreatedDate);
        }
        if (Objects.nonNull(endCreatedDate)) {
            ParamExpression<ZonedDateTime> endedAtParam = new ParamExpressionImpl<>(ZonedDateTime.class);
            query = query.where(qCoupon.createdAt.loe(endedAtParam)).set(endedAtParam, endCreatedDate);
        }
        ......
       final String queryString = query.toString();
       final TypedQuery<Object[]> typedQuery = entityManager.createQuery(queryString, Object[].class)
                .setFirstResult(pageRequest.getOffset())
                .setMaxResults(pageRequest.getPageSize());

        for (Map.Entry<ParamExpression<?>, Object> paramExpressionObjectEntry : query.getMetadata().getParams().entrySet()) {
            ParamExpression<?> paramExpression = paramExpressionObjectEntry.getKey();
            typedQuery.setParameter(paramExpression.getName(), paramExpressionObjectEntry.getValue());
        }

        List<Object[]> queryResult = typedQuery
                .getResultList();

The problem is the queryString variable contains unnamed parameter like where lower(coupon.code) like lower(?1) not as expected with named parameter that starts with :. I've tried using name, adding second constructor argument in ParamExpressionImpl like new ParamExpressionImpl<>(String.class, qCoupon.code.getMetadata().getName()) it's just same.

As a result it returns with exception message Parameter with that name [code] did not exist.
How's the correct use of QueryDSL's ParamExpression on the typedQuery.setParameter(...) line?


问:
ASP.Net XUnit check if list of objects cointains a specific object
I am trying to add unit tests to my project. Some of these tests are checking if a list of objects does of does not contain an object. For checking if a list contains an object i've tried Assert.Contains(MyList, ExpectedObject), but it still gives an error that says that the list does not contain this object. Even when i debug the test i can see that the object is correctly added to the list.

The same happens with Assert.DoesNotContain(MyList, ExpectedObject). When i remove an item from the list and do this check it does say that it not in the list. But when i no longer remove the item, it still says that it is no longer in the list. Even though it is still in the list.

When i try it with a test list:List<string>. and do the same operations of adding and removing items, and then checking if these items are in the list or not. It does work.
Maybe Assert.Contains does not work for lists of objects. But the compiler does not give any errors. And i've also already checked if the ExpectedObject is the same type as the objects in the list.

Is there maybe another way of checking if an object is or isn't in a list.
any help is appreciated.

答:
Generally in Java and C# implementation of contains methods for object lists compare them by equals method. If equals method if not specified for the object by default it will look for object unique id or memory address, it means even if there were 2 objects with all same fields can be different. Because they created separately and allocated different ram addresses. If you want to compare objects override equals method. This will allow contains method to compare objects with each other using your custom comparison method.

Example:

Let say you have a Person object with fields like id, name, mail etc. If you want objects to be equal if their id's are same you can use:

// They are same person if their id is same
public override bool Equals(Object obj)
   {
      Person personObj = obj as Person;
      if (personObj == null)
         return false;
      else
         return idNumber.Equals(personObj.idNumber);
   }
```


答:
I guess you are looking for a pivot_wider solution:

library(tidyr)

haves %>%
  pivot_wider(names_from = x, values_from = starts_with("number_"), values_fill = 0)
```

<p>gives you</p>

<pre class="lang-r prettyprint-override"><code># A tibble: 2 x 14
     id factor1 factor2   age date1          y number_1_2 number_1_1 number_1_0 number_1_3 number_2_2 number_2_1 number_2_0
  <dbl> <fct>   <fct>   <dbl> <date>     <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
1     1 f1      f2          2 2014-07-01  554.          1          2          3          0         43         44         45
2     1 f1      f2          9 2015-02-01  616           0          0         11         10          0          0         53
</code>```

Title: cast/spread 2 columns based on one shared factor

Body:
I am struggling with this - sorry. This is my haves:

library(dplyr)
library(reshape2)

haves <- data.frame(
    id = c(1, 1, 1, 1, 1)
    , factor1 = c("f1", "f1", "f1", "f1", "f1")
    , factor2 = c("f2", "f2", "f2", "f2", "f2")
    , number_1 = c(1,2,3,10,11)
    , number_2 = c(43,44,45,52,53)
    , age = c(2, 2, 2, 9, 9)
    , date1 = c(as.Date("2014-07-01"), as.Date("2014-07-01"), as.Date("2014-07-01"), as.Date("2015-02-01"), as.Date("2015-02-01"))
    , y = c(554.5, 554.5, 554.5, 616, 616)
    , x = c(2,1,0,3,0)
)

haves

  id factor1 factor2 number_1 number_2 age      date1     y x
1  1      f1      f2        1       43   2 2014-07-01 554.5 2
2  1      f1      f2        2       44   2 2014-07-01 554.5 1
3  1      f1      f2        3       45   2 2014-07-01 616.0 0
4  1      f1      f2       10       52   9 2015-02-01 616.0 3
5  1      f1      f2       11       53   9 2015-02-01 616.0 0

I want to cast/spread the values in number_1 and number_2 according to x to get this:

Body:
I guess you are looking for a pivot_wider solution:

library(tidyr)

haves %>%
  pivot_wider(names_from = x, values_from = starts_with("number_"), values_fill = 0)

gives you

# A tibble: 2 x 14
     id factor1 factor2   age date1          y number_1_2 number_1_1 number_1_0 number_1_3 number_2_2 number_2_1 number_2_0
  <dbl> <fct>   <fct>   <dbl> <date>     <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
1     1 f1      f2          2 2014-07-01  554.          1          2          3          0         43         44         45
2     1 f1      f2          9 2015-02-01  616           0          0         11         10          0          0         53


问:
Performance of reverse-mapping collection
I have a collection of objects where every object has a unique string Id, and any other object can contain entirely arbitrary (many-to-one) "Links" to another object.  I also want to be able to generate a "usage map" which is the reverse index -- given any one object, which other objects are linked either directly to it or to a child of it?  (Here a "child" is defined as any object with a matching prefix Id, as the Id is a dotted-path notation.)

So Baz.Boz might be one object that links to Foo.Bar -- the usage map should then reflect that both Foo and Foo.Bar (but not Foo.Bob) are used by Baz.Boz.

This is the code used to calculate the usage map:

```<code>// builds Id => links that link to Id or one of Id's children (by prefix)
public IDictionary<string, IList<Link>> CalculateUsageMap()
{
    var all = All();
    var links = all.Values
        .SelectMany(o => o.Links ?? Enumerable.Empty<Link>())
        .ToList();
    return all.Keys.ToDictionary(i => i, i => links.Where(k => IsLinkedTo(k, i)).ToList());
    // this last line is very slow
}

private static bool IsLinkedTo(Link link, string candidateId)
{
    return !string.IsNullOrEmpty(link.TargetId)
        && !string.IsNullOrEmpty(candidateId)
        && link.TargetId.StartsWith(candidateId, StringComparison.Ordinal);
}
</code>```

This is the supporting structure behind it:

```<code>public interface ILinkable
{
    string Id { get; }
    IEnumerable<ILinkable> Children { get; }
    IEnumerable<Link> Links { get; }
}

public class Link
{
    public string Name { get; }
    public ILinkable Source { get; } // our immediate owner
    public string TargetId { get; }
    // plus constructors etc that's irrelevant at present
}

public ILinkable Root { get; }

public IDictionary<string, ILinkable> All()
{
    var tree = new Dictionary<string, ILinkable>();
    AddWithDescendants(tree, Root);
    return tree;
}

private static void AddWithDescendants(IDictionary<string, ILinkable> tree, ILinkable obj)
{
    tree.Add(obj.Id, obj);

    foreach (var child in obj.Children ?? Enumerable.Empty<ILinkable>())
    {
        AddWithDescendants(tree, child);
    }
}
</code>```

This works, but in a tree with ~14k objects and ~3k links (producing ~20k usages) this takes ~5s to generate, which is longer than I'd like.  (I've checked and All() and calculating links takes basically no time; it's all being spent inside ToDictionary.)

Is there some way to improve performance of this line?  My first thought was using something like GroupJoin, but since we're "joining" on prefix-equality rather than actual equality that doesn't really work.  I would prefer to keep this in pure code, not involving a database.

(I did attempt to write a custom equality comparer for GroupJoin but this ended up being both slower and producing the wrong results, with only ~7k of usage output.  And it's dubious anyway since this is an asymmetric match, while equality comparers assume symmetry.)

答:
The time complexity of this code

```<code>return all.Keys.ToDictionary(i => i, i => links.Where(k => IsLinkedTo(k, i)).ToList());
</code>```

is quadratic O(N*M), where N is all.Keys.Count and M is links.Count. So not surprisingly it is slow.

Since what you are trying to achieve is essentially finding all ILinkable.Id being prefix of Link.TargetId, you need an efficient data structure optimized for such operation. Such data structure exists and is called Prefix tree. Following is a quick implementation for your case:

```<code>class ItemMap : IReadOnlyCollection<KeyValuePair<string, IReadOnlyList<Link>>>
{
    class Node
    {
        public Node(char key) => Key = key;
        public char Key { get; }
        public NodeMap Children;
        public ILinkable Item;
        public List<Link> Links;
        public IReadOnlyList<Link> ItemLinks => Links ?? (Item != null ? NoLinks : null);
        public static IReadOnlyList<Link> NoLinks => Array.Empty<Link>();
    }

    struct NodeMap
    {
        Dictionary<char, Node> items;
        public IEnumerable<Node> Items => items?.Values;
        public bool TryGetItem(char key, out Node item, bool create = false)
        {
            item = null;
            if ((items == null || !items.TryGetValue(key, out item)) && create)
                (items ?? (items = new Dictionary<char, Node>())).Add(key, item = new Node(key));
            return item != null;
        }
    }

    NodeMap RootNodes;

    IEnumerable<Node> Nodes
        => RootNodes.Items?.Expand(e => e.Children.Items) ?? Enumerable.Empty<Node>();

    IEnumerable<Node> ItemNodes
        => Nodes.Where(n => n.Item != null);

    IEnumerable<KeyValuePair<string, IReadOnlyList<Link>>> Items
        => ItemNodes.Select(n => new KeyValuePair<string, IReadOnlyList<Link>>(n.Item.Id, n.ItemLinks));

    public ItemMap(ILinkable tree)
    {
        if (tree == null) return;
        var items = new[] { tree }.Expand(e => e.Children);
        foreach (var item in items)
            AddItem(item);
        var links = Nodes.Where(n => n.Item?.Links != null).SelectMany(n => n.Item.Links);
        foreach (var link in links)
            AddLink(link);
    }

    void AddItem(ILinkable item)
    {
        var node = GetNode(item.Id, create: true);
        if (node == null) return;
        if (node.Item != null) throw new Exception($"Duplicate key: {item.Id}");
        node.Item = item;
        Count++;
    }

    void AddLink(Link link)
    {
        var key = link.TargetId;
        if (string.IsNullOrEmpty(key)) return;
        ref var nodes = ref RootNodes;
        for (int i = 0; i < key.Length; i++)
        {
            if (!nodes.TryGetItem(key[i], out var node)) break;
            // Add to each item in the prefix path
            if (node.Item != null && node.Item != link.Source)
                (node.Links ?? (node.Links = new List<Link>())).Add(link);
            nodes = ref node.Children;
        }
    }

    Node GetNode(string key, bool create = false)
    {
        if (string.IsNullOrEmpty(key)) return null;
        Node node = null;
        ref var nodes = ref RootNodes;
        for (int i = 0; i < key.Length; i++)
        {
            if (!nodes.TryGetItem(key[i], out node, create)) break;
            nodes = ref node.Children;
        }
        return node;
    }

    public int Count { get; private set; }

    public IEnumerator<KeyValuePair<string, IReadOnlyList<Link>>> GetEnumerator() => Items.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
</code>```

(Note: Instead of recursive tree traversals, in many places I use the generic DRY Expand method from my answer to How to flatten tree via LINQ?))

All the hard work happens in the class constructor. The first pass adds all items to the prefix tree. Then the second pass associates the links with each item. The first operation is O(N), second is O(M), so the overall is O(M+N), i.e. linear and much faster than the original.

Now you can easily build the desired dictionary (I've changed the interfaces to their ReadOnly variants):

```<code>public IReadOnlyDictionary<string, IReadOnlyList<Link>> CalculateUsageMap()
    => new ItemMap(Root).ToDictionary(e => e.Key, e => e.Value);
</code>```

But note that this is not even needed, because the prefix tree can be used effectively as dictionary. Implementing the read only dictionary interface is quite easy - change the class declaration to

```<code>class ItemMap : IReadOnlyDictionary<string, IReadOnlyList<Link>>
</code>```

and add the following few lines inside

```<code>public IEnumerable<string> Keys => Items.Select(e => e.Key);

public IEnumerable<IReadOnlyList<Link>> Values => Items.Select(e => e.Value);

public IReadOnlyList<Link> this[string key]
    => TryGetValue(key, out var value) ? value : throw new KeyNotFoundException();

public bool ContainsKey(string key) => TryGetValue(key, out _);

public bool TryGetValue(string key, out IReadOnlyList<Link> value)
    => (value = GetNode(key)?.ItemLinks) != null;
</code>```

Now you can remove the ToDictionary call:

```<code>public IReadOnlyDictionary<string, IReadOnlyList<Link>> CalculateUsageMap()
    => new ItemMap(Root);
</code>```

The above prefix tree implementation use Dictionary<char, Node> for child node list storage/traversal. This might use much more memory. Since the whole implementation is encapsulated in NodeMap, you can experiment with different data structures and measure the performance and memory usage.

For instance, the following is another implementation which uses null, single Node or sorted List<Node> as storage, and binary search for locating the Node by key in the sorted list:

```<code>struct NodeMap
{
    object items; // null, Node or sorted List<Node>
    public IEnumerable<Node> Items => items is Node node ? new[] { node } : items as IEnumerable<Node>;
    public bool TryGetItem(char key, out Node item, bool create = false)
    {
        item = null;
        if (items == null)
        {
            if (create) items = item = new Node(key);
        }
        else if (items is Node node)
        {
            if (node.Key == key) item = node;
            else if (create) items = node.Key < key ? new List<Node>(2) { node, (item = new Node(key)) } : new List<Node>(2) { (item = new Node(key)), node };
        }
        else
        {
            var nodeList = (List<Node>)items;
            int lo = 0, hi = nodeList.Count - 1;
            while (lo <= hi)
            {
                int mid = lo + ((hi - lo) >> 1);
                node = nodeList[mid];
                if (node.Key == key) { item = node; break; }
                if (node.Key < key) lo = mid + 1; else hi = mid - 1;
            }
            if (item == null && create) nodeList.Insert(lo, item = new Node(key));
        }
        return item != null;
    }
}
</code>```

Body:
I have a collection of objects where every object has a unique string Id, and any other object can contain entirely arbitrary (many-to-one) "Links" to another object.  I also want to be able to generate a "usage map" which is the reverse index -- given any one object, which other objects are linked either directly to it or to a child of it?  (Here a "child" is defined as any object with a matching prefix Id, as the Id is a dotted-path notation.)

So Baz.Boz might be one object that links to Foo.Bar -- the usage map should then reflect that both Foo and Foo.Bar (but not Foo.Bob) are used by Baz.Boz.

This is the code used to calculate the usage map:

// builds Id => links that link to Id or one of Id's children (by prefix)
public IDictionary<string, IList<Link>> CalculateUsageMap()
{
    var all = All();
    var links = all.Values
        .SelectMany(o => o.Links ?? Enumerable.Empty<Link>())
        .ToList();
    return all.Keys.ToDictionary(i => i, i => links.Where(k => IsLinkedTo(k, i)).ToList());
    // this last line is very slow
}

private static bool IsLinkedTo(Link link, string candidateId)
{
    return !string.IsNullOrEmpty(link.TargetId)
        && !string.IsNullOrEmpty(candidateId)
        && link.TargetId.StartsWith(candidateId, StringComparison.Ordinal);
}

This is the supporting structure behind it:

public interface ILinkable
{
    string Id { get; }
    IEnumerable<ILinkable> Children { get; }
    IEnumerable<Link> Links { get; }
}

public class Link
{
    public string Name { get; }
    public ILinkable Source { get; } // our immediate owner
    public string TargetId { get; }
    // plus constructors etc that's irrelevant at present
}

public ILinkable Root { get; }

public IDictionary<string, ILinkable> All()
{
    var tree = new Dictionary<string, ILinkable>();
    AddWithDescendants(tree, Root);
    return tree;
}

private static void AddWithDescendants(IDictionary<string, ILinkable> tree, ILinkable obj)
{
    tree.Add(obj.Id, obj);

    foreach (var child in obj.Children ?? Enumerable.Empty<ILinkable>())
    {
        AddWithDescendants(tree, child);
    }
}

This works, but in a tree with ~14k objects and ~3k links (producing ~20k usages) this takes ~5s to generate, which is longer than I'd like.  (I've checked and All() and calculating links takes basically no time; it's all being spent inside ToDictionary.)

Is there some way to improve performance of this line?  My first thought was using something like GroupJoin, but since we're "joining" on prefix-equality rather than actual equality that doesn't really work.  I would prefer to keep this in pure code, not involving a database.

(I did attempt to write a custom equality comparer for GroupJoin but this ended up being both slower and producing the wrong results, with only ~7k of usage output.  And it's dubious anyway since this is an asymmetric match, while equality comparers assume symmetry.)

Body:
The time complexity of this code

return all.Keys.ToDictionary(i => i, i => links.Where(k => IsLinkedTo(k, i)).ToList());

is quadratic O(N*M), where N is all.Keys.Count and M is links.Count. So not surprisingly it is slow.

Since what you are trying to achieve is essentially finding all ILinkable.Id being prefix of Link.TargetId, you need an efficient data structure optimized for such operation. Such data structure exists and is called Prefix tree. Following is a quick implementation for your case:

class ItemMap : IReadOnlyCollection<KeyValuePair<string, IReadOnlyList<Link>>>
{
    class Node
    {
        public Node(char key) => Key = key;
        public char Key { get; }
        public NodeMap Children;
        public ILinkable Item;
        public List<Link> Links;
        public IReadOnlyList<Link> ItemLinks => Links ?? (Item != null ? NoLinks : null);
        public static IReadOnlyList<Link> NoLinks => Array.Empty<Link>();
    }

    struct NodeMap
    {
        Dictionary<char, Node> items;
        public IEnumerable<Node> Items => items?.Values;
        public bool TryGetItem(char key, out Node item, bool create = false)
        {
            item = null;
            if ((items == null || !items.TryGetValue(key, out item)) && create)
                (items ?? (items = new Dictionary<char, Node>())).Add(key, item = new Node(key));
            return item != null;
        }
    }

    NodeMap RootNodes;

    IEnumerable<Node> Nodes
        => RootNodes.Items?.Expand(e => e.Children.Items) ?? Enumerable.Empty<Node>();

    IEnumerable<Node> ItemNodes
        => Nodes.Where(n => n.Item != null);

    IEnumerable<KeyValuePair<string, IReadOnlyList<Link>>> Items
        => ItemNodes.Select(n => new KeyValuePair<string, IReadOnlyList<Link>>(n.Item.Id, n.ItemLinks));

    public ItemMap(ILinkable tree)
    {
        if (tree == null) return;
        var items = new[] { tree }.Expand(e => e.Children);
        foreach (var item in items)
            AddItem(item);
        var links = Nodes.Where(n => n.Item?.Links != null).SelectMany(n => n.Item.Links);
        foreach (var link in links)
            AddLink(link);
    }

    void AddItem(ILinkable item)
    {
        var node = GetNode(item.Id, create: true);
        if (node == null) return;
        if (node.Item != null) throw new Exception($"Duplicate key: {item.Id}");
        node.Item = item;
        Count++;
    }

    void AddLink(Link link)
    {
        var key = link.TargetId;
        if (string.IsNullOrEmpty(key)) return;
        ref var nodes = ref RootNodes;
        for (int i = 0; i < key.Length; i++)
        {
            if (!nodes.TryGetItem(key[i], out var node)) break;
            // Add to each item in the prefix path
            if (node.Item != null && node.Item != link.Source)
                (node.Links ?? (node.Links = new List<Link>())).Add(link);
            nodes = ref node.Children;
        }
    }

    Node GetNode(string key, bool create = false)
    {
        if (string.IsNullOrEmpty(key)) return null;
        Node node = null;
        ref var nodes = ref RootNodes;
        for (int i = 0; i < key.Length; i++)
        {
            if (!nodes.TryGetItem(key[i], out node, create)) break;
            nodes = ref node.Children;
        }
        return node;
    }

    public int Count { get; private set; }

    public IEnumerator<KeyValuePair<string, IReadOnlyList<Link>>> GetEnumerator() => Items.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

(Note: Instead of recursive tree traversals, in many places I use the generic DRY Expand method from my answer to How to flatten tree via LINQ?))

All the hard work happens in the class constructor. The first pass adds all items to the prefix tree. Then the second pass associates the links with each item. The first operation is O(N), second is O(M), so the overall is O(M+N), i.e. linear and much faster than the original.

Now you can easily build the desired dictionary (I've changed the interfaces to their ReadOnly variants):

public IReadOnlyDictionary<string, IReadOnlyList<Link>> CalculateUsageMap()
    => new ItemMap(Root).ToDictionary(e => e.Key, e => e.Value);

But note that this is not even needed, because the prefix tree can be used effectively as dictionary. Implementing the read only dictionary interface is quite easy - change the class declaration to

class ItemMap : IReadOnlyDictionary<string, IReadOnlyList<Link>>

and add the following few lines inside

public IEnumerable<string> Keys => Items.Select(e => e.Key);

public IEnumerable<IReadOnlyList<Link>> Values => Items.Select(e => e.Value);

public IReadOnlyList<Link> this[string key]
    => TryGetValue(key, out var value) ? value : throw new KeyNotFoundException();

public bool ContainsKey(string key) => TryGetValue(key, out _);

public bool TryGetValue(string key, out IReadOnlyList<Link> value)
    => (value = GetNode(key)?.ItemLinks) != null;

Now you can remove the ToDictionary call:

public IReadOnlyDictionary<string, IReadOnlyList<Link>> CalculateUsageMap()
    => new ItemMap(Root);

The above prefix tree implementation use Dictionary<char, Node> for child node list storage/traversal. This might use much more memory. Since the whole implementation is encapsulated in NodeMap, you can experiment with different data structures and measure the performance and memory usage.

For instance, the following is another implementation which uses null, single Node or sorted List<Node> as storage, and binary search for locating the Node by key in the sorted list:

struct NodeMap
{
    object items; // null, Node or sorted List<Node>
    public IEnumerable<Node> Items => items is Node node ? new[] { node } : items as IEnumerable<Node>;
    public bool TryGetItem(char key, out Node item, bool create = false)
    {
        item = null;
        if (items == null)
        {
            if (create) items = item = new Node(key);
        }
        else if (items is Node node)
        {
            if (node.Key == key) item = node;
            else if (create) items = node.Key < key ? new List<Node>(2) { node, (item = new Node(key)) } : new List<Node>(2) { (item = new Node(key)), node };
        }
        else
        {
            var nodeList = (List<Node>)items;
            int lo = 0, hi = nodeList.Count - 1;
            while (lo <= hi)
            {
                int mid = lo + ((hi - lo) >> 1);
                node = nodeList[mid];
                if (node.Key == key) { item = node; break; }
                if (node.Key < key) lo = mid + 1; else hi = mid - 1;
            }
            if (item == null && create) nodeList.Insert(lo, item = new Node(key));
        }
        return item != null;
    }
}


问:
iOS Outline of Stroked UIBezierPath/CGPath, as a Path
(I have read other answers on SO, but they do not appear to address the problem at hand.)

[Swift 4, Xcode 9]

I need to get the path representing the drawn areas following the stroke() of a path. i.e. a path that represents the outline of the stroke.

Given a UIBezierPath with the following attributes:

```<code>let dotWidth: CGFloat = 3
let spacing: CGFloat = 12
let dashes: [CGFloat] = [0.0, spacing]
let lineCapStyle: CGLineCap = .round
let lineJoinStyle: CGLineJoin = .miter
bezierPath.lineCapStyle = lineCapStyle
bezierPath.lineJoinStyle = lineJoinStyle
bezierPath.setLineDash(dashes, count: dashes.count, phase: 0)
bezierPath.lineWidth = dotWidth
</code>```

Xcode's debugger preview will kindly render the result:

I need those dots as a path.

First attempt, using the modern version of CGPathCreateCopyByStrokingPath()

```<code>let strokedCGPath = bezierPath.cgPath.copy(strokingWithWidth: dotWidth,
    lineCap: lineCapStyle,
    lineJoin: lineJoinStyle,
    miterLimit: 4)
</code>```

Second attempt:

```<code>let dashedCGPath = bezierPath.cgPath.copy(dashingWithPhase: 0, lengths: dashes)
</code>```

Result: neither copy(strokingWithWidth:) or copy(dashingWithPhase:) give me the complete path that I need.

Question: am I missing something obvious here? Is there a way to get the entire path of the stroke?

Thanks for any help.

答:
Since there are two different algorithms discussed here, let me show the difference:

```<code>cgPath.copy(dashingWithPhase: phase, lengths: pattern)
</code>```

creates one-dimensional polylines as subpaths that are not closed for each dash. They do not contain a closeSubpath element. "strokes"

on the other hand

```<code>context.replacePathWithStrokedPath()
let newCGPath = context.path
</code>```

creates two-dimensional closed polygons as subpaths for each dash. They do contain a closeSubpath element.  "shapes"

Hope this helps to choose the algorithm they need.

Body:
(I have read other answers on SO, but they do not appear to address the problem at hand.)

[Swift 4, Xcode 9]

I need to get the path representing the drawn areas following the stroke() of a path. i.e. a path that represents the outline of the stroke.

Given a UIBezierPath with the following attributes:

let dotWidth: CGFloat = 3
let spacing: CGFloat = 12
let dashes: [CGFloat] = [0.0, spacing]
let lineCapStyle: CGLineCap = .round
let lineJoinStyle: CGLineJoin = .miter
bezierPath.lineCapStyle = lineCapStyle
bezierPath.lineJoinStyle = lineJoinStyle
bezierPath.setLineDash(dashes, count: dashes.count, phase: 0)
bezierPath.lineWidth = dotWidth

Xcode's debugger preview will kindly render the result:

I need those dots as a path.

First attempt, using the modern version of CGPathCreateCopyByStrokingPath()

let strokedCGPath = bezierPath.cgPath.copy(strokingWithWidth: dotWidth,
    lineCap: lineCapStyle,
    lineJoin: lineJoinStyle,
    miterLimit: 4)

Second attempt:

let dashedCGPath = bezierPath.cgPath.copy(dashingWithPhase: 0, lengths: dashes)

Result: neither copy(strokingWithWidth:) or copy(dashingWithPhase:) give me the complete path that I need.

Question: am I missing something obvious here? Is there a way to get the entire path of the stroke?

Thanks for any help.

Body:
Since there are two different algorithms discussed here, let me show the difference:

cgPath.copy(dashingWithPhase: phase, lengths: pattern)

creates one-dimensional polylines as subpaths that are not closed for each dash. They do not contain a closeSubpath element. "strokes"

on the other hand

context.replacePathWithStrokedPath()
let newCGPath = context.path

creates two-dimensional closed polygons as subpaths for each dash. They do contain a closeSubpath element.  "shapes"

Hope this helps to choose the algorithm they need.


问:
Meteor typescript complaining about missing doctype in vscode
VSCode is complaining about missing DOCTYPE on the html files. Meteor build system automatically adds file types and having them causes build errors. How do I make vscode to ignore missing doctype on html files?

Error I get for this.

```<code>Doctype must be declared first.
</code>```

答:
Go to your VScode Preferences > Settings > HTML-Hint and add this:

"htmlhint.options": {
  "doctype-first": false
}

Body:
VSCode is complaining about missing DOCTYPE on the html files. Meteor build system automatically adds file types and having them causes build errors. How do I make vscode to ignore missing doctype on html files?

Error I get for this.

Doctype must be declared first.


问:
constraint issue on iOS 13, looks different than iOS 12
i have issue with bottom constraint of my view on iOS 13, here is my single line of code that i have issue with it:

myLabel.bottomAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 0).isActive = true

this code works different on iOS 13 and iOS 12: (below images related to iOS 13 and it's debug view)

in debug view it's looks different from simulator view, i don't know why?!

now if you see in below image: (related to iOS 12)

this is what i'm done until now:

when i remove height constraint on headerView(GreenImage) it's work normally, but when i set height on it, issue back :(

i create headerBackground constraint in layoutSubviews()
and create label bottom constraint in closure property like code below:

```<code>private lazy var headerView : HeaderView = {
        let view = HeaderView(layout: .login)
        let welcomeLabel = UILabel()
        view.addSubview(welcomeLabel)
        welcomeLabel.translatesAutoresizingMaskIntoConstraints = false
        welcomeLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        welcomeLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
        welcomeLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
        return view
    }()
</code>```

答:
I found an answer that I think in iOS 12 or earlier views has a default value of clipToBounds = true

which in iOS 13 is false

after I change the value my problem is solved and the front imageView clip from behind view.

Body:
i have issue with bottom constraint of my view on iOS 13, here is my single line of code that i have issue with it:

myLabel.bottomAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 0).isActive = true

this code works different on iOS 13 and iOS 12: (below images related to iOS 13 and it's debug view)

in debug view it's looks different from simulator view, i don't know why?!

now if you see in below image: (related to iOS 12)

this is what i'm done until now:

when i remove height constraint on headerView(GreenImage) it's work normally, but when i set height on it, issue back :(

i create headerBackground constraint in layoutSubviews()
and create label bottom constraint in closure property like code below:

private lazy var headerView : HeaderView = {
        let view = HeaderView(layout: .login)
        let welcomeLabel = UILabel()
        view.addSubview(welcomeLabel)
        welcomeLabel.translatesAutoresizingMaskIntoConstraints = false
        welcomeLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
        welcomeLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
        welcomeLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
        return view
    }()


问:
How to search string with strstr but with a key word that was not assigned by the user
This is the code

```<code>int main()
{
    FILE* fptr;
    char c_id[50];
    char str[BUFFER_SIZE];
    int choices;
    char* pos;
    int customer_id;
    printf("Enter customer ID: ");
    scanf("%d", &customer_id);
    sprintf(c_id, "%d", customer_id);
    fptr = fopen("servicestest.txt", "r");
    printf("\n1. Check for unpaid\n2. Check for paid\n");
    scanf("%d", &choices);
    switch (choices)
    {
    case 1:
        while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
        {
            pos = strstr(str, "Not");

            if (pos == 1)
            {
                printf("%s\n", str);
            }
        }
        break;
    case 2:
        while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
        {
            pos = strstr(str, "Not");
            if (pos =! 1)
            {
                printf("%s\n", str);
            }
        }
  }
}
</code>```

Was planning to check a line with not and print them how to do that? Why is it not printing anything when I inputted "1" as choices

I wanted to assign

```<code>char ch[50];
ch[1] = "Not";
</code>```

but when i tried the strstr (str, ch[1]) it caused an error

Any idea how to do it?

答:
check the return value of fopen:

```<code>if(!fptr) {
   return -1;
}
</code>```

You try to compare between a pointer and int value.

```<code>if (pos == 1)
// and
if (pos =! 1) // even you can compare, it should be if (pos != 1)
</code>```

If you want to calculate the position of substring "Not", you can do as:

```<code>pos = strstr(str, "Not");
if(pos) {
   int pos_substring = (int) (str-pos);
   // from here you can compare the position of substring with an `int` value.
   if (pos_substring == 1) {/*do something*/}
   eles {/*do something*/}

}
</code>```

When you try the code:

```<code>char ch[50];
char ch[1] = "Not"; // string "Not" need at least 4 bytes (3 bytes for 'N', 'o' and 't', 1 bytes for null character)
</code>```

It should change to:

```<code>char ch[50] = "Not";
// or
char ch[] = "Not";
// or
const char *ch = "Not" // be attention with the string literal
</code>```

Then when you want to apply to strstr function:

```<code>strstr (str, ch); // use ch instead of ch[1]
</code>```

If you want to use something like strstr (str, ch[1]), you can use the 2D array of characters:

```<code>char ch[50][50] = {/*init the string here or later as you want*/}; // this 2D array contents of maximum 50 strings, each string length ups to 49.
strstr (str, ch[0]);
strstr (str, ch[1]);
strstr (str, ch[2]);
// etc.

</code>```

Body:
This is the code

int main()
{
    FILE* fptr;
    char c_id[50];
    char str[BUFFER_SIZE];
    int choices;
    char* pos;
    int customer_id;
    printf("Enter customer ID: ");
    scanf("%d", &customer_id);
    sprintf(c_id, "%d", customer_id);
    fptr = fopen("servicestest.txt", "r");
    printf("\n1. Check for unpaid\n2. Check for paid\n");
    scanf("%d", &choices);
    switch (choices)
    {
    case 1:
        while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
        {
            pos = strstr(str, "Not");

            if (pos == 1)
            {
                printf("%s\n", str);
            }
        }
        break;
    case 2:
        while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
        {
            pos = strstr(str, "Not");
            if (pos =! 1)
            {
                printf("%s\n", str);
            }
        }
  }
}

Was planning to check a line with not and print them how to do that? Why is it not printing anything when I inputted "1" as choices

I wanted to assign

char ch[50];
ch[1] = "Not";

but when i tried the strstr (str, ch[1]) it caused an error

Any idea how to do it?

Body:
check the return value of fopen:

if(!fptr) {
   return -1;
}

You try to compare between a pointer and int value.

if (pos == 1)
// and
if (pos =! 1) // even you can compare, it should be if (pos != 1)

If you want to calculate the position of substring "Not", you can do as:

pos = strstr(str, "Not");
if(pos) {
   int pos_substring = (int) (str-pos);
   // from here you can compare the position of substring with an `int` value.
   if (pos_substring == 1) {/*do something*/}
   eles {/*do something*/}

}

When you try the code:

char ch[50];
char ch[1] = "Not"; // string "Not" need at least 4 bytes (3 bytes for 'N', 'o' and 't', 1 bytes for null character)

It should change to:

char ch[50] = "Not";
// or
char ch[] = "Not";
// or
const char *ch = "Not" // be attention with the string literal

Then when you want to apply to strstr function:

strstr (str, ch); // use ch instead of ch[1]

If you want to use something like strstr (str, ch[1]), you can use the 2D array of characters:

char ch[50][50] = {/*init the string here or later as you want*/}; // this 2D array contents of maximum 50 strings, each string length ups to 49.
strstr (str, ch[0]);
strstr (str, ch[1]);
strstr (str, ch[2]);
// etc.