问:
python word frequencies for dictionary with values and key
I am a first-time learner of python, I understand how to use word frequencies to count the number of each unique variable of a list, like this

```<code>sentence = ['hello', 'people', 'are', 'the', 'most', 'common', 'word', 'people', 'use', 'for', 'language ', 'learning']

words_freq ={} #dictionary for the counts
for word in sentence:
    if word not in words_freq:

        words_freq[word] =1
    else:

        words_freq[word] +=1

print (words_freq)
</code>```

however, I wonder how could a word frequencies do on the dictionary by using a double for loop?

for example, I have a dictionary like this

```<code>Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Pork", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}
</code>```

how to do a word frequencies/count and print something like this? Or store the highest value in list form ?
apple : 3
milk : 2
orange : 3
..
..
..

答:
It helps you:</p>

```<code>Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Porn", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

words_freq ={} #dictionary for the counts
for word1 in Food.values():
    for word in word1:
        if word not in words_freq:

            words_freq[word] =1
        else:

            words_freq[word] +=1

print (words_freq)
</code>```

Body:
I am a first-time learner of python, I understand how to use word frequencies to count the number of each unique variable of a list, like this

sentence = ['hello', 'people', 'are', 'the', 'most', 'common', 'word', 'people', 'use', 'for', 'language ', 'learning']

words_freq ={} #dictionary for the counts
for word in sentence:
    if word not in words_freq:

        words_freq[word] =1
    else:

        words_freq[word] +=1

print (words_freq)

however, I wonder how could a word frequencies do on the dictionary by using a double for loop?

for example, I have a dictionary like this

Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Pork", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

how to do a word frequencies/count and print something like this? Or store the highest value in list form ?
apple : 3
milk : 2
orange : 3
..
..
..

Body:
It helps you:

Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Porn", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

words_freq ={} #dictionary for the counts
for word1 in Food.values():
    for word in word1:
        if word not in words_freq:

            words_freq[word] =1
        else:

            words_freq[word] +=1

print (words_freq)


来源: stackexchange

问:
How to solve this Recurrence: T(n) = 2T(n/3)+n^2?
Substitution Method and Recursion Tree Method for:

T(n) = 2/7             If n=1

T(n) = 2T(n/3)+n^2     Otherwise

How to solve such a system of equations?

答:
The equation clearly only can be solved when n is a power of 3. Substituting n by a new variable k^3 gives a simpler equation that can be solved by sympy, python's symbolic mathematics library:

from sympy import Function, rsolve, S, symbols, Eq

k, n = symbols("k n", integer=True, positive=True)

f = Function('f')
g = Function('g')

# T(n) = 2T(n/3)+n^2    T(1) = 2/7

T = Eq(f(n), 2 * f(n / 3) + n * n)
Tk = T.subs({n: 3 ** k, f(n): g(k), f(n / 3): g(k - 1)})

s = rsolve(Tk, g(k), {g(0): 2 / S(7)})
print("solution for k:", s.cancel())

for k in range(0, 11):
    print(f"k={k}, n={3 ** k}, T(n)={-2 ** k + 3 ** (2 * k + 2) / S(7)}")
```

<p>This results in following formula for <code>k</code>: -2<sup>k</sup> + 3<sup>2*k+2</sup>/7</p>

<p>The values for k=0..10 are:</p>

```k=0, n=1, T(n)=2/7
k=1, n=3, T(n)=67/7
k=2, n=9, T(n)=701/7
k=3, n=27, T(n)=6505/7
k=4, n=81, T(n)=58937/7
k=5, n=243, T(n)=531217/7
k=6, n=729, T(n)=4782521/7
k=7, n=2187, T(n)=43045825/7
k=8, n=6561, T(n)=387418697/7
k=9, n=19683, T(n)=3486780817/7
k=10, n=59049, T(n)=31381052441/7
```

ContentLicense: CC BY-SA 4.0

Body:
The equation clearly only can be solved when n is a power of 3. Substituting n by a new variable k^3 gives a simpler equation that can be solved by sympy, python's symbolic mathematics library:

from sympy import Function, rsolve, S, symbols, Eq

k, n = symbols("k n", integer=True, positive=True)

f = Function('f')
g = Function('g')

# T(n) = 2T(n/3)+n^2    T(1) = 2/7

T = Eq(f(n), 2 * f(n / 3) + n * n)
Tk = T.subs({n: 3 ** k, f(n): g(k), f(n / 3): g(k - 1)})

s = rsolve(Tk, g(k), {g(0): 2 / S(7)})
print("solution for k:", s.cancel())

for k in range(0, 11):
    print(f"k={k}, n={3 ** k}, T(n)={-2 ** k + 3 ** (2 * k + 2) / S(7)}")

This results in following formula for k: -2k + 32*k+2/7

The values for k=0..10 are:

k=0, n=1, T(n)=2/7
k=1, n=3, T(n)=67/7
k=2, n=9, T(n)=701/7
k=3, n=27, T(n)=6505/7
k=4, n=81, T(n)=58937/7
k=5, n=243, T(n)=531217/7
k=6, n=729, T(n)=4782521/7
k=7, n=2187, T(n)=43045825/7
k=8, n=6561, T(n)=387418697/7
k=9, n=19683, T(n)=3486780817/7
k=10, n=59049, T(n)=31381052441/7


问:
How can I get Python to match 'x264' using Regex
I'm attempting to find all files that contain certain variations of a codec in their name, but when I try to execute the following code, I get nothing but '* Exited normally *'

x264, X264, h264, H264

as above, but with a period between the X/H and 264

```<code>#!/usr/bin/python3

import os
import re

rootdir = "/mnt/local/int002/Downloads/Complete"
regex = re.compile('x264')

for root, dirs, files in os.walk(rootdir):
  for file in files:
    if regex.match(file):
       print(file)
</code>```

答:
If you really need to use a regex, try re.search. re.match only matches the beginning of the string.

```<code>#!/usr/bin/python3

import os
import re

rootdir = "/mnt/local/int002/Downloads/Complete"
regex = re.compile('x264')

for root, dirs, files in os.walk(rootdir):
  for file in files:
    if regex.search(file):
       print(file)
</code>```

Body:
I'm attempting to find all files that contain certain variations of a codec in their name, but when I try to execute the following code, I get nothing but '* Exited normally *'

x264, X264, h264, H264

as above, but with a period between the X/H and 264

#!/usr/bin/python3

import os
import re

rootdir = "/mnt/local/int002/Downloads/Complete"
regex = re.compile('x264')

for root, dirs, files in os.walk(rootdir):
  for file in files:
    if regex.match(file):
       print(file)

Body:
If you really need to use a regex, try re.search. re.match only matches the beginning of the string.

#!/usr/bin/python3

import os
import re

rootdir = "/mnt/local/int002/Downloads/Complete"
regex = re.compile('x264')

for root, dirs, files in os.walk(rootdir):
  for file in files:
    if regex.search(file):
       print(file)


问:
Django - how to handle time duration
I am trying to display the elapsed time during a race.

```<code>class results(models.Model):
    race_id = models.ForeignKey(Race, on_delete=models.CASCADE)
    runner_id = models.ForeignKey(Runner, on_delete=models.CASCADE)
    race_start = models.DateTimeField()
    race_finish = models.DateTimeField(blank=True, null=True)
    obs = models.TextField(blank=True)
    def __str__(self):
        return self.race_id.race_cod+" - "+self.runner_id.name
    class Meta:
        verbose_name_plural = "Results"
</code>```

Looking here I have found the following guides:

Django model elapsed time between two DateTimeFields

Django: What's the best field type to represent time elapsed?

Unfortunately, the solution presented there seems a little bit complex.

I also have found this workaround in the .html view page

```<code><div class="info-box-content">
  <span class="info-box-number">Time - {{ results.race_finish|timesince:results.race_start }}</span>
</div>
</code>```

the issue with this one is that everything over 24 hours came as x days, yy hours - while my need is to display the duration as HH:mm

Any hints here?

答:
Have you tried using built-in tags?

```<code>{{ value|time:"H:i" }}
</code>```

https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#time

Title: Django - how to handle time duration

Body:
I am trying to display the elapsed time during a race.

class results(models.Model):
    race_id = models.ForeignKey(Race, on_delete=models.CASCADE)
    runner_id = models.ForeignKey(Runner, on_delete=models.CASCADE)
    race_start = models.DateTimeField()
    race_finish = models.DateTimeField(blank=True, null=True)
    obs = models.TextField(blank=True)
    def __str__(self):
        return self.race_id.race_cod+" - "+self.runner_id.name
    class Meta:
        verbose_name_plural = "Results"

Looking here I have found the following guides:

Django model elapsed time between two DateTimeFields

Django: What's the best field type to represent time elapsed?

Unfortunately, the solution presented there seems a little bit complex.

I also have found this workaround in the .html view page

  Time - {{ results.race_finish|timesince:results.race_start }}

the issue with this one is that everything over 24 hours came as x days, yy hours - while my need is to display the duration as HH:mm

Any hints here?

Body:
Have you tried using built-in tags?

{{ value|time:"H:i" }}

https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#time


问:
The 'componentDidMount' lifecycle method does not update the state
I have a component called DiscardPile that's receive in your props (props.cards) an array of objects like this:

```<code>{key: 'key', 'type', suit: 'suit', label: 'label', flipped: 'fliped, draggable: 'draggable', currentOrder: 0}
</code>```

Well, the component DiscardPile is shown bellow:

```<code>import React, { Component } from 'react';
import $ from 'jquery';
import 'jquery-ui/ui/core';
import 'jquery-ui/ui/widgets/droppable';

import './DiscardPile.scss';

import Card from '../Card/Card';
export default class DiscardPile extends Component {

    constructor(props) {
        super(props);
        this.state = {
            currentCards: []
        }
    }

    componentDidMount() {
        let currentCards = [...this.props.cards];
        for(let i = 0; i < currentCards.length; i++) {
            currentCards[i].currentOrder = i;
        }
        this.setState({currentCards: currentCards});
    }

    render() {
        return (
            <div id="discard-pile" className="discard-pile">
                {this.state.currentCards.map(card =>(
                    <Card key={card.key} type={card.type} suit={card.suit} label={card.label} flipped={card.flipped} draggable={card.draggable} currentOrder={card.currentOrder}></Card>
                ))}
            </div>
        )
    }

}
</code>```

The 'componentDidMount' should update the currentOrder attribute of the object and render the cards list again, but this is not happening. In fact, the list being rendered empty.
What could I do to fix this?

(Sorry for my bad english)

--UPDATE--

The DiscardPile component is called by the KlondikeTable component, shown bellow:

```<code>import React, { Component } from 'react';

import './KlondikeTable.scss';

import Card from './../../generalComponents/Card/Card';
import DiscardPile from '../../generalComponents/DiscardPile/DiscardPile';
import FlippedPile from '../../generalComponents/FlippedPile/FlippedPile';
import SuitsPile from '../../generalComponents/SuitsPile/SuitsPile';
import CardsColumn from '../../generalComponents/CardsColumn/CardsColumn';

export default class KlondikeTable extends Component {

    constructor(props) {
        super(props);
        this.state = {
            cards: [],
            initialDistribution: {
                discardPile: [],
                flippedPile: [],
                cardsPile1: [],
                cardsPile2: [],
                cardsPile3: [],
                cardsPile4: [],
                cardsPile5: [],
                cardsPile6: [],
                cardsPile7: [],
            },
            currentDistribution: null
        }
        this.generateCards = this.generateCards.bind(this);
        this.shuffleCards = this.shuffleCards.bind(this);
    }

    componentDidMount() {
        this.generateCards();
    }

    generateCards() {
        let cards = [];
        let types = ["K","Q","J","10","9","8","7","6","5","4","3","2","A"];
        let suits = ["spades", "clubs", "diamonds", "hearts"];
        for(let i = 0; i < suits.length; i++) {
            for(let j = 0; j < types.length; j++) {
                cards.push(
                    {key: types[j] + "-" + suits[i] + "-0", type: types[j], suit: suits[i], label: "0", flipped: false, draggable: true, currentOrder: 0}
                )
            }
        }
        this.setState(state => ({...state, cards: cards}), () => {
            this.shuffleCards();
        });
    }

    shuffleCards() {
        let amount = 52;
        let numbersArray = [];
        let cards = [...this.state.cards];
        let initialDistribution = {...this.state.initialDistribution};
        for(let i = 0; i < 52; i++) {
            numbersArray.push(i);
        }
        for(let i = 0; i < 24; i++) {
            let randomNumber = Math.floor(Math.random() * amount);
            let removedElement = cards.splice(randomNumber, 1)[0];
            initialDistribution.discardPile.push(removedElement);
            amount--;
        }
        for(let i = 0; i < 28; i++) {
            let randomNumber = Math.floor(Math.random() * amount);
            let removedElement = cards.splice(randomNumber, 1)[0];
            if(i < 1) {
                initialDistribution.cardsPile1.push(removedElement);
            }else if(i < 3) {
                initialDistribution.cardsPile2.push(removedElement);
            }else if(i < 6) {
                initialDistribution.cardsPile3.push(removedElement);
            }else if(i < 10) {
                initialDistribution.cardsPile4.push(removedElement);
            }else if(i < 15) {
                initialDistribution.cardsPile5.push(removedElement);
            }else if(i < 21) {
                initialDistribution.cardsPile6.push(removedElement);
            }else if(i >= 21) {
                initialDistribution.cardsPile7.push(removedElement);
            }
            amount--;
        }
        this.setState({initialDistribution: initialDistribution, currentDistribution: initialDistribution});
    }

    render() {
        return (
            <div className="klondike-table">
                <DiscardPile cards={this.state.initialDistribution.discardPile}></DiscardPile>
                <FlippedPile cards={this.state.initialDistribution.flippedPile}></FlippedPile>
                <div className="suits-piles-container">
                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>
                </div>
                <CardsColumn cards={this.state.initialDistribution.cardsPile1}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile2}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile3}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile4}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile5}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile6}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile7}></CardsColumn>
            </div>
        )
    }

}
</code>```

答:
Since componentDidMount only runs once, any changes you're making will not take effect if the prop changes later on.

The prop cards is initially set to []. So unless you move your ordering logic somewhere else, it will never be updated in state to contain your updated array.

Without knowing the exact logic you want, something like this may work:

componentDidUpdate(prevProps) {
  if (prevProps.cards.length !== this.props.cards.length) {
    let currentCards = [...this.props.cards];
    for(let i = 0; i < currentCards.length; i++) {
      currentCards[i].currentOrder = i;
    }
    this.setState({currentCards: currentCards});
  }
}
```

This will update the state only if the length of the cards array changes.

Body:
I have a component called DiscardPile that's receive in your props (props.cards) an array of objects like this:

{key: 'key', 'type', suit: 'suit', label: 'label', flipped: 'fliped, draggable: 'draggable', currentOrder: 0}

Well, the component DiscardPile is shown bellow:

import React, { Component } from 'react';
import $ from 'jquery';
import 'jquery-ui/ui/core';
import 'jquery-ui/ui/widgets/droppable';

import './DiscardPile.scss';

import Card from '../Card/Card';
export default class DiscardPile extends Component {

    constructor(props) {
        super(props);
        this.state = {
            currentCards: []
        }
    }

    componentDidMount() {
        let currentCards = [...this.props.cards];
        for(let i = 0; i < currentCards.length; i++) {
            currentCards[i].currentOrder = i;
        }
        this.setState({currentCards: currentCards});
    }

    render() {
        return (

                {this.state.currentCards.map(card =>(
                    <Card key={card.key} type={card.type} suit={card.suit} label={card.label} flipped={card.flipped} draggable={card.draggable} currentOrder={card.currentOrder}></Card>
                ))}

        )
    }

}

The 'componentDidMount' should update the currentOrder attribute of the object and render the cards list again, but this is not happening. In fact, the list being rendered empty.
What could I do to fix this?

(Sorry for my bad english)

--UPDATE--

The DiscardPile component is called by the KlondikeTable component, shown bellow:

import React, { Component } from 'react';

import './KlondikeTable.scss';

import Card from './../../generalComponents/Card/Card';
import DiscardPile from '../../generalComponents/DiscardPile/DiscardPile';
import FlippedPile from '../../generalComponents/FlippedPile/FlippedPile';
import SuitsPile from '../../generalComponents/SuitsPile/SuitsPile';
import CardsColumn from '../../generalComponents/CardsColumn/CardsColumn';

export default class KlondikeTable extends Component {

    constructor(props) {
        super(props);
        this.state = {
            cards: [],
            initialDistribution: {
                discardPile: [],
                flippedPile: [],
                cardsPile1: [],
                cardsPile2: [],
                cardsPile3: [],
                cardsPile4: [],
                cardsPile5: [],
                cardsPile6: [],
                cardsPile7: [],
            },
            currentDistribution: null
        }
        this.generateCards = this.generateCards.bind(this);
        this.shuffleCards = this.shuffleCards.bind(this);
    }

    componentDidMount() {
        this.generateCards();
    }

    generateCards() {
        let cards = [];
        let types = ["K","Q","J","10","9","8","7","6","5","4","3","2","A"];
        let suits = ["spades", "clubs", "diamonds", "hearts"];
        for(let i = 0; i < suits.length; i++) {
            for(let j = 0; j < types.length; j++) {
                cards.push(
                    {key: types[j] + "-" + suits[i] + "-0", type: types[j], suit: suits[i], label: "0", flipped: false, draggable: true, currentOrder: 0}
                )
            }
        }
        this.setState(state => ({...state, cards: cards}), () => {
            this.shuffleCards();
        });
    }

    shuffleCards() {
        let amount = 52;
        let numbersArray = [];
        let cards = [...this.state.cards];
        let initialDistribution = {...this.state.initialDistribution};
        for(let i = 0; i < 52; i++) {
            numbersArray.push(i);
        }
        for(let i = 0; i < 24; i++) {
            let randomNumber = Math.floor(Math.random() * amount);
            let removedElement = cards.splice(randomNumber, 1)[0];
            initialDistribution.discardPile.push(removedElement);
            amount--;
        }
        for(let i = 0; i < 28; i++) {
            let randomNumber = Math.floor(Math.random() * amount);
            let removedElement = cards.splice(randomNumber, 1)[0];
            if(i < 1) {
                initialDistribution.cardsPile1.push(removedElement);
            }else if(i < 3) {
                initialDistribution.cardsPile2.push(removedElement);
            }else if(i < 6) {
                initialDistribution.cardsPile3.push(removedElement);
            }else if(i < 10) {
                initialDistribution.cardsPile4.push(removedElement);
            }else if(i < 15) {
                initialDistribution.cardsPile5.push(removedElement);
            }else if(i < 21) {
                initialDistribution.cardsPile6.push(removedElement);
            }else if(i >= 21) {
                initialDistribution.cardsPile7.push(removedElement);
            }
            amount--;
        }
        this.setState({initialDistribution: initialDistribution, currentDistribution: initialDistribution});
    }

    render() {
        return (

                <DiscardPile cards={this.state.initialDistribution.discardPile}></DiscardPile>
                <FlippedPile cards={this.state.initialDistribution.flippedPile}></FlippedPile>

                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>

                <CardsColumn cards={this.state.initialDistribution.cardsPile1}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile2}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile3}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile4}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile5}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile6}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile7}></CardsColumn>

        )
    }

}

Body:
Since componentDidMount only runs once, any changes you're making will not take effect if the prop changes later on.

The prop cards is initially set to []. So unless you move your ordering logic somewhere else, it will never be updated in state to contain your updated array.

Without knowing the exact logic you want, something like this may work:

componentDidUpdate(prevProps) {
  if (prevProps.cards.length !== this.props.cards.length) {
    let currentCards = [...this.props.cards];
    for(let i = 0; i < currentCards.length; i++) {
      currentCards[i].currentOrder = i;
    }
    this.setState({currentCards: currentCards});
  }
}

This will update the state only if the length of the cards array changes.


问:
Custom woocommerce product field not working for CSV import
I've created a custom field for my products this way:

```<code>// The code for displaying WooCommerce Product Custom Fields
add_action( 'woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields' );
// Following code Saves  WooCommerce Product Custom Fields
add_action( 'woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save' );
function woocommerce_product_custom_fields () {
    global $woocommerce, $post;
    echo '<div class=" product_custom_field ">';
    // Custom Product Number Field
    woocommerce_wp_text_input(
        array(
            'id' => '_shipping_days_field',
            'placeholder' => 'Días de entrega',
            'label' => __('Días estimados de entrega', 'woocommerce'),
            'type' => 'number',
            'custom_attributes' => array(
                'step' => 'any',
                'min' => '1'
            )
        )
    );
    echo '</div>';
}

function woocommerce_product_custom_fields_save($post_id){
    // Custom Product Number Field
    $shipping_days = $_POST['_shipping_days_field'];
    if (!empty($shipping_days))
        update_post_meta($post_id, '_shipping_days_field', esc_attr($shipping_days));
}
</code>```

This is working ok on the frontend admin it shows the field and saves it, but it is not working for the CSV impornt, I cannot specify the field in my CSV mapping. Is there a way I can create custom field that works for CSV import as well?

答:
I actually solved it, on the mapping you just should select Meta Attributes, and the label on the CSV column must be as follows:

meta:your_custom_field

Body:
I've created a custom field for my products this way:

// The code for displaying WooCommerce Product Custom Fields
add_action( 'woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields' );
// Following code Saves  WooCommerce Product Custom Fields
add_action( 'woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save' );
function woocommerce_product_custom_fields () {
    global $woocommerce, $post;
    echo '
';
    // Custom Product Number Field
    woocommerce_wp_text_input(
        array(
            'id' => '_shipping_days_field',
            'placeholder' => 'Días de entrega',
            'label' => __('Días estimados de entrega', 'woocommerce'),
            'type' => 'number',
            'custom_attributes' => array(
                'step' => 'any',
                'min' => '1'
            )
        )
    );
    echo '
';
}

function woocommerce_product_custom_fields_save($post_id){
    // Custom Product Number Field
    $shipping_days = $_POST['_shipping_days_field'];
    if (!empty($shipping_days))
        update_post_meta($post_id, '_shipping_days_field', esc_attr($shipping_days));
}

This is working ok on the frontend admin it shows the field and saves it, but it is not working for the CSV impornt, I cannot specify the field in my CSV mapping. Is there a way I can create custom field that works for CSV import as well?


问:
Signal R and AJAX not getting updates from API
So I followed this quick guide from the MS site for building a SignalR app :
SignalR App

I would of thought that I could use a local API to watch the count change after adding a row to it in real time. I used AJAX for this:

```<code>function getALL() {
  $.ajax({
    url: 'http://localhost:8080/api/GetCount',
    contentType: 'application/json ; charset:utf-8',
    type: 'GET',
    success: function (data) {
        console.log(data);
        document.getElementById("messageList").innerHTML = data[0].Count;
    }
  });
}
</code>```

Of course initiated hub with: var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

```<code>connection.on("ReceiveMessage", function () {
  getALL();
});

connection.start().then(function () {
  getALL();
  connection.invoke("SendMessage").catch(function (err) {
    return console.error(err.toString());
});
}).catch(function (err) {
  return console.error(err.toString());
});
</code>```

Now the above code works and shows me the data the first time, but when I add another row, nothing happens. What am I missing? The onclick event in the MS example works. But not if I try to load it without no events.

My Hub:

```<code>    public class ChatHub : Hub
    {
        private IHubContext<ChatHub> _hubContext;

        public ChatHub(IHubContext<ChatHub> hubContext) { _hubContext = hubContext; }

        public async Task SendMessage()
        {
            await _hubContext.Clients.All.SendAsync("ReceiveMessage");
        }
    }
}
</code>```

Am I adding the AJAX in the wrong place? Is my hub missing a Entity Model? If so, why would it when I'm calling a local API.

I also loaded the hub in the Startup.cs file as advised:

```<code>app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
            endpoints.MapFallbackToPage("/_Host");
        });
</code>```

I'm trying this with net Core 3.1 as well. Any suggestions are helpful. I thought this would be a simple example to modify, but I have had no luck with it yet. Thank you all.

答:
You need the hub to be notified, when there is a change like this:

```<code>connection.invoke("SendMessage").catch(function (err) {
    return console.error(err.toString());
});
</code>```

And you need this not, after starting the connection, but after every add of an row.
Edit:
To show you a bit, of what is needed:
1. You need an event in an signalR-Client, where the row is added and the code before is run.
2. you Need a (second or same) signalR-Client, that is notified, like you already have.

You can’t see changes in the database, if you only add a row directly.
You have to add the row in the Frontensegeln and notify the Hub in your client-side application.

Body:
So I followed this quick guide from the MS site for building a SignalR app :
SignalR App

I would of thought that I could use a local API to watch the count change after adding a row to it in real time. I used AJAX for this:

function getALL() {
  $.ajax({
    url: 'http://localhost:8080/api/GetCount',
    contentType: 'application/json ; charset:utf-8',
    type: 'GET',
    success: function (data) {
        console.log(data);
        document.getElementById("messageList").innerHTML = data[0].Count;
    }
  });
}

Of course initiated hub with: var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

connection.on("ReceiveMessage", function () {
  getALL();
});

connection.start().then(function () {
  getALL();
  connection.invoke("SendMessage").catch(function (err) {
    return console.error(err.toString());
});
}).catch(function (err) {
  return console.error(err.toString());
});

Now the above code works and shows me the data the first time, but when I add another row, nothing happens. What am I missing? The onclick event in the MS example works. But not if I try to load it without no events.

My Hub:

    public class ChatHub : Hub
    {
        private IHubContext<ChatHub> _hubContext;

        public ChatHub(IHubContext<ChatHub> hubContext) { _hubContext = hubContext; }

        public async Task SendMessage()
        {
            await _hubContext.Clients.All.SendAsync("ReceiveMessage");
        }
    }
}

Am I adding the AJAX in the wrong place? Is my hub missing a Entity Model? If so, why would it when I'm calling a local API.

I also loaded the hub in the Startup.cs file as advised:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
            endpoints.MapFallbackToPage("/_Host");
        });

I'm trying this with net Core 3.1 as well. Any suggestions are helpful. I thought this would be a simple example to modify, but I have had no luck with it yet. Thank you all.

Body:
You need the hub to be notified, when there is a change like this:

connection.invoke("SendMessage").catch(function (err) {
    return console.error(err.toString());
});

And you need this not, after starting the connection, but after every add of an row.
Edit:
To show you a bit, of what is needed:
1. You need an event in an signalR-Client, where the row is added and the code before is run.
2. you Need a (second or same) signalR-Client, that is notified, like you already have.

You can’t see changes in the database, if you only add a row directly.
You have to add the row in the Frontensegeln and notify the Hub in your client-side application.


问:
isolating an angularjs anonymous $parser:ueoe error
Having a devil of time finding where this error is coming from.

On a button, I have ng-click="goUrl('L_1001_1008_1113')"

In the controller (ClubCtrl) is:

```<code>$scope.goUrl = function(id) {
   console.log("HereA - "+id) ;
   $location.url('/tab/clubs/'+id) ;
   console.log("HereB - "+id) ;
}
</code>```

When I click the button I get this error in console:

HereA - L_1001_1008_1113

HereB - L_1001_1008_1113

ionic.bundle.js:20306 Error: [$parse:ueoe] Unexpected end of
  expression: club.
  http://errors.angularjs.org/1.3.13/$parse/ueoe?p0=club.

```<code>at ionic.bundle.js:8762
at Parser.consume (ionic.bundle.js:20747)
at Parser.identifier (ionic.bundle.js:20778)
at Parser.fieldAccess (ionic.bundle.js:20975)
at Parser.primary (ionic.bundle.js:20701)
at Parser.unary (ionic.bundle.js:20970)
at Parser.multiplicative (ionic.bundle.js:20953)
at Parser.additive (ionic.bundle.js:20944)
at Parser.relational (ionic.bundle.js:20935)
at Parser.equality (ionic.bundle.js:20926)
</code>```

There is only one place I use club - its in the detail-club.html template page and in that pages  controller (ClubDetailCtrl).  My state changer is:

```<code>  .state('tab.clubs', {
      cache: true,
      url: '/clubs',
      params: {
        'refreshClubs' : 0,
        'pushAction' : 0,
        'pushSub' : null,
        'pushMsg' : null,
        'pushCode' : null
      },
      views: {
        'tab-clubs': {
          templateUrl: 'templates/tab-clubs.html',
          controller: 'ClubCtrl'

        }
      }
    })
    .state('tab.club-detail', {
      url: '/clubs/:ceID',
      views: {
        'tab-clubs': {
          templateUrl: 'templates/detail-clubs.html',
          controller: 'ClubDetailCtrl'
        }
      }
    })
</code>```

At the moment, I have commented out EVERYTHING in ClubDetailCtrl rxcept a console.log("HereC"); trying to isolate the error.  But "HereC" never fires in the console.  So I know the issue isn't happening in ClubDetailCtrl.

The error message is terrible and doesn't point to whats actually triggering it.  What is this error and more importantly how can I track it down?

Could the error becoming FROM the template page that has the button in it?  Or could it becoming from the template page the button is trying to redirect to?  the redirect page/controller is the only thing with just club in it, but I imagine the controller console message HereC would fire before a template page would cause the error.  So where else could it be?

答:
For debugging purpose, create a simplified template and controller for the state:</p>

```<code>.state('tab.club-detail', {
  url: '/clubs/:ceID',
  views: {
    'tab-clubs': {
      template: `<div>DETAIL-CLUBS</div>`,
      controller: function() {
          console.log("details controller init");
      }
    }
  }
})
</code>```

Body:
Having a devil of time finding where this error is coming from.

On a button, I have ng-click="goUrl('L_1001_1008_1113')"

In the controller (ClubCtrl) is:

$scope.goUrl = function(id) {
   console.log("HereA - "+id) ;
   $location.url('/tab/clubs/'+id) ;
   console.log("HereB - "+id) ;
}

When I click the button I get this error in console:

HereA - L_1001_1008_1113

HereB - L_1001_1008_1113

ionic.bundle.js:20306 Error: [$parse:ueoe] Unexpected end of
  expression: club.
  http://errors.angularjs.org/1.3.13/$parse/ueoe?p0=club.

at ionic.bundle.js:8762
at Parser.consume (ionic.bundle.js:20747)
at Parser.identifier (ionic.bundle.js:20778)
at Parser.fieldAccess (ionic.bundle.js:20975)
at Parser.primary (ionic.bundle.js:20701)
at Parser.unary (ionic.bundle.js:20970)
at Parser.multiplicative (ionic.bundle.js:20953)
at Parser.additive (ionic.bundle.js:20944)
at Parser.relational (ionic.bundle.js:20935)
at Parser.equality (ionic.bundle.js:20926)

There is only one place I use club - its in the detail-club.html template page and in that pages  controller (ClubDetailCtrl).  My state changer is:

  .state('tab.clubs', {
      cache: true,
      url: '/clubs',
      params: {
        'refreshClubs' : 0,
        'pushAction' : 0,
        'pushSub' : null,
        'pushMsg' : null,
        'pushCode' : null
      },
      views: {
        'tab-clubs': {
          templateUrl: 'templates/tab-clubs.html',
          controller: 'ClubCtrl'

        }
      }
    })
    .state('tab.club-detail', {
      url: '/clubs/:ceID',
      views: {
        'tab-clubs': {
          templateUrl: 'templates/detail-clubs.html',
          controller: 'ClubDetailCtrl'
        }
      }
    })

At the moment, I have commented out EVERYTHING in ClubDetailCtrl rxcept a console.log("HereC"); trying to isolate the error.  But "HereC" never fires in the console.  So I know the issue isn't happening in ClubDetailCtrl.

The error message is terrible and doesn't point to whats actually triggering it.  What is this error and more importantly how can I track it down?

Could the error becoming FROM the template page that has the button in it?  Or could it becoming from the template page the button is trying to redirect to?  the redirect page/controller is the only thing with just club in it, but I imagine the controller console message HereC would fire before a template page would cause the error.  So where else could it be?

Body:
For debugging purpose, create a simplified template and controller for the state:

.state('tab.club-detail', {
  url: '/clubs/:ceID',
  views: {
    'tab-clubs': {
      template: `<div>DETAIL-CLUBS</div>`,
      controller: function() {
          console.log("details controller init");
      }
    }
  }
})


问:
NHibernate One-To-Many Delete Not Cascading
I have a 'Photo' class and a 'Comment' class. An Photo can have multiple comments assigned to it.

I have this configured as a one-to-many relationship within my HBM mapping file, and have set cascade="all-delete-orphan" against the 'Comments' bag within the Photo.hbm.xml mapping file.

However, if I try to delete a Photo which has 1 or more Comments associated with it, I am getting 'The DELETE statement conflicted with the REFERENCE constraint "FK_Comments_Photos"'

I tried a couple of other cascade options against the Comments bag in my Photo.hbm.xml but regardless of what I set it to, I'm getting the same outcome each time. I just want to be able to delete a Photo and have any associated comments automatically delete too.

Here is my Photo mapping (edited for brevity):

```<code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" .... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Photo" table="Photos">
    <id name="PhotoId" unsaved-value="0">
        <column  name="PhotoId" />
        <generator class="native" />
    </id>
    ...
    <bag name="Comments" table="Comments" cascade="all-delete-orphan" order-by="DateTimePosted desc" where="Approved=1">
        <key column="PhotoId" />
        <one-to-many class="Comment" />
    </bag>
</class>
</code>```

Here is my Comment mapping (edited for brevity):

```<code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Comment" table="Comments">
    <id name="CommentId" unsaved-value="0">
        <column name="CommentId"></column>
        <generator class="native" />
    </id>
    ...
    <property name="Author" not-null="true" />
    <property name="Body" not-null="true" />
    <property name="Approved" not-null="true" />
    <many-to-one name="Photo" not-null="true">
        <column name="PhotoId" />
    </many-to-one>
</class>
</code>```

Does anyone have any suggestions as to why the cascade is not happening when I try to delete a Photo with comments associated with it?

UPDATE: The only way I can get the cascade to happen is to configure the 'Delete Rule' within SQL Server against this relationship to 'Cascade', and in doing so means that I don't need to specify any cascade action within my NHibernate Mapping. However, this isn't ideal for me - I'd like to be able to configure the cascade behaviour within the NHibernate Mapping ideally, so I'm still confused as to why it doesn't appear to be taking any notice of my NHibernate cascade setting?

答:
I had similar problem for 1 day .. and got frustrated over it.

Finally the solution boiled down to the DB.
I had to change the FK key constraints in "INSERT UPDATE SPECIFICATION"
'Delete Rule' : from 'No Action' to 'Cascade'

additionally you can also set
'Update Rule' : from 'No Action' to 'Cascade'

ContentLicense: CC BY-SA 2.5

Body:
I have a 'Photo' class and a 'Comment' class. An Photo can have multiple comments assigned to it.

I have this configured as a one-to-many relationship within my HBM mapping file, and have set cascade="all-delete-orphan" against the 'Comments' bag within the Photo.hbm.xml mapping file.

However, if I try to delete a Photo which has 1 or more Comments associated with it, I am getting 'The DELETE statement conflicted with the REFERENCE constraint "FK_Comments_Photos"'

I tried a couple of other cascade options against the Comments bag in my Photo.hbm.xml but regardless of what I set it to, I'm getting the same outcome each time. I just want to be able to delete a Photo and have any associated comments automatically delete too.

Here is my Photo mapping (edited for brevity):

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" .... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Photo" table="Photos">
    <id name="PhotoId" unsaved-value="0">
        <column  name="PhotoId" />
        <generator class="native" />
    </id>
    ...
    <bag name="Comments" table="Comments" cascade="all-delete-orphan" order-by="DateTimePosted desc" where="Approved=1">
        <key column="PhotoId" />
        <one-to-many class="Comment" />
    </bag>
</class>

Here is my Comment mapping (edited for brevity):

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Comment" table="Comments">
    <id name="CommentId" unsaved-value="0">
        <column name="CommentId"></column>
        <generator class="native" />
    </id>
    ...
    <property name="Author" not-null="true" />
    <property name="Body" not-null="true" />
    <property name="Approved" not-null="true" />
    <many-to-one name="Photo" not-null="true">
        <column name="PhotoId" />
    </many-to-one>
</class>

Does anyone have any suggestions as to why the cascade is not happening when I try to delete a Photo with comments associated with it?

UPDATE: The only way I can get the cascade to happen is to configure the 'Delete Rule' within SQL Server against this relationship to 'Cascade', and in doing so means that I don't need to specify any cascade action within my NHibernate Mapping. However, this isn't ideal for me - I'd like to be able to configure the cascade behaviour within the NHibernate Mapping ideally, so I'm still confused as to why it doesn't appear to be taking any notice of my NHibernate cascade setting?

ContentLicense: CC BY-SA 3.0


问:
Entity Framework Core - Very slow performance
I have the following entities (I'll show the properties I'm working with because I don't want to make it larger than needed):

PROPERTY: Where a property can be child of another one and has a 1-1 relationship with GeoLocation and can have multiple Multimedia and Operation

```<code>public partial class Property
{
    public Property()
    {
        InverseParent = new HashSet<Property>();
        Multimedia = new HashSet<Multimedia>();
        Operation = new HashSet<Operation>();
    }

    public long Id { get; set; }
    public string GeneratedTitle { get; set; }
    public string Url { get; set; }
    public DateTime? DatePublished { get; set; }
    public byte StatusCode { get; set; }
    public byte Domain { get; set; }
    public long? ParentId { get; set; }

    public virtual Property Parent { get; set; }
    public virtual GeoLocation GeoLocation { get; set; }
    public virtual ICollection<Property> InverseParent { get; set; }
    public virtual ICollection<Multimedia> Multimedia { get; set; }
    public virtual ICollection<Operation> Operation { get; set; }
}
</code>```

GEOLOCATION: As mentioned, it has a 1-1 relationship with Property

```<code>public partial class GeoLocation
{
    public int Id { get; set; }
    public double? Latitude { get; set; }
    public double? Longitude { get; set; }
    public long? PropertyId { get; set; }

    public virtual Property Property { get; set; }
}
</code>```

MULTIMEDIA: it can hold multiple Images, with different sizes, for a single Property. The detail here is that Order specifies the order of the images to be shown in the client application, but it doesn't start always with 1. There're some cases where a Property has Multimedia files that starts with 3 or x.

```<code>public partial class Multimedia
{
    public long Id { get; set; }
    public long? Order { get; set; }
    public string Resize360x266 { get; set; }
    public long? PropertyId { get; set; }

    public virtual Property Property { get; set; }
}
</code>```

OPERATIONS: defines all the operations a Property can have, using OperationType to name this operation. (rent, sell, etc.)

```<code>public partial class Operation
{
    public Operation()
    {
        Price = new HashSet<Price>();
    }

    public long Id { get; set; }
    public long? OperationTypeId { get; set; }
    public long? PropertyId { get; set; }

    public virtual OperationType OperationType { get; set; }
    public virtual Property Property { get; set; }
    public virtual ICollection<Price> Price { get; set; }
}

public partial class OperationType
{
    public OperationType()
    {
        Operation = new HashSet<Operation>();
    }

    public long Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Operation> Operation { get; set; }
}
</code>```

PRICE: defines the price for each operation and the currency type. (i.e.: A property can have the rent option - Operation - for X amount in USD currency, but another price registered for the same Operation in case of use another currency type )

```<code>public partial class Price
{
    public long Id { get; set; }
    public float? Amount { get; set; }
    public string CurrencyCode { get; set; }
    public long? OperationId { get; set; }

    public virtual Operation Operation { get; set; }
}
</code>```

Said that, I want to get all the records (actually are about 40K-50K), but only for a few properties. As I mentioned before, the Multimedia table can have a lot of records for each Property, but I only need the first one with the smaller Order value and sorted by DatePublished. After that, I need to convert the result into MapMarker object, which is as follows:

```<code>public class MapMarker : EstateBase
{
    public long Price { get; set; }
    public int Category { get; set; }
    public List<Tuple<string, string, string>> Prices { get; set; }
}
</code>```

In order to achieve this, I made the following:

```<code>public async Task<IEnumerable<MapMarker>> GetGeolocatedPropertiesAsync(int quantity)
{
    var properties = await GetAllProperties().AsNoTracking()
        .Include(g => g.GeoLocation)
        .Include(m => m.Multimedia)
        .Include(p => p.Operation).ThenInclude(o => o.Price)
        .Include(p => p.Operation).ThenInclude(o => o.OperationType)
        .Where(p => p.GeoLocation != null
            && !string.IsNullOrEmpty(p.GeoLocation.Address)
            && p.GeoLocation.Longitude != null
            && p.GeoLocation.Latitude != null
            && p.StatusCode == (byte)StatusCode.Online
            && p.Operation.Count > 0)
        .OrderByDescending(p => p.ModificationDate)
        .Take(quantity)
        .Select(p => new {
            p.Id,
            p.Url,
            p.GeneratedTitle,
            p.GeoLocation.Address,
            p.GeoLocation.Latitude,
            p.GeoLocation.Longitude,
            p.Domain,
            p.Operation,
            p.Multimedia.OrderBy(m => m.Order).FirstOrDefault().Resize360x266
        })
        .ToListAsync();

    var mapMarkers = new List<MapMarker>();

    try
    {
        foreach (var property in properties)
        {
            var mapMarker = new MapMarker();
            mapMarker.Id = property.Id.ToString();
            mapMarker.Url = property.Url;
            mapMarker.Title = property.GeneratedTitle ?? string.Empty;
            mapMarker.Address = property.Address ?? string.Empty;
            mapMarker.Latitude = property.Latitude.ToString() ?? string.Empty;
            mapMarker.Longitude = property.Longitude.ToString() ?? string.Empty;
            mapMarker.Domain = ((Domain)Enum.ToObject(typeof(Domain), property.Domain)).ToString();
            mapMarker.Image = property.Resize360x266 ?? string.Empty;
            mapMarker.Prices = new List<Tuple<string, string, string>>();
            foreach (var operation in property.Operation)
            {
                foreach (var price in operation.Price)
                {
                    var singlePrice = new Tuple<string, string, string>(operation.OperationType.Name, price.CurrencyCode, price.Amount.ToString());
                    mapMarker.Prices.Add(singlePrice);
                }
            }
            mapMarkers.Add(mapMarker);
        }
    }
    catch (Exception ex)
    {

        throw;
    }

    return mapMarkers;
}
</code>```

but the results take more than 14 minutes and this method could be called multiple times in a minute. I want to optimize it to return the results in the less time possible. I alreay tried removing ToListAsync(), but in the foreach loop it takes a lot of time too, and that makes all the sense.

So, what do you think I can do here?
Thanks in advance.

UPDATE:
Here is GetAllProperties() method, I forgot to include this one.

```<code>private IQueryable<Property> GetAllProperties()
{
    return _dbContext.Property.AsQueryable();
}
</code>```

And the SQL query that Entity Framework is making against SQL Server:

```<code>SELECT [p].[Id], [p].[Url], [p].[GeneratedTitle], [g].[Address], [g].[Latitude], [g].[Longitude], [p].[Domain], (
    SELECT TOP(1) [m].[Resize360x266]
    FROM [Multimedia] AS [m]
    WHERE [p].[Id] = [m].[PropertyId]
    ORDER BY [m].[Order]), [t].[Id], [t].[CreationDate], [t].[ModificationDate], [t].[OperationTypeId], [t].[PropertyId], [t].[Id0], [t].[CreationDate0], [t].[ModificationDate0], [t].[Name], [t].[Id1], [t].[Amount], [t].[CreationDate1], [t].[CurrencyCode], [t].[ModificationDate1], [t].[OperationId]
FROM [Property] AS [p]
LEFT JOIN [GeoLocation] AS [g] ON [p].[Id] = [g].[PropertyId]
LEFT JOIN (
    SELECT [o].[Id], [o].[CreationDate], [o].[ModificationDate], [o].[OperationTypeId], [o].[PropertyId], [o0].[Id] AS [Id0], [o0].[CreationDate] AS [CreationDate0], [o0].[ModificationDate] AS [ModificationDate0], [o0].[Name], [p0].[Id] AS [Id1], [p0].[Amount], [p0].[CreationDate] AS [CreationDate1], [p0].[CurrencyCode], [p0].[ModificationDate] AS [ModificationDate1], [p0].[OperationId]
    FROM [Operation] AS [o]
    LEFT JOIN [OperationType] AS [o0] ON [o].[OperationTypeId] = [o0].[Id]
    LEFT JOIN [Price] AS [p0] ON [o].[Id] = [p0].[OperationId]
) AS [t] ON [p].[Id] = [t].[PropertyId]
WHERE (((([g].[Id] IS NOT NULL AND ([g].[Address] IS NOT NULL AND (([g].[Address] <> N'') OR [g].[Address] IS NULL))) AND [g].[Longitude] IS NOT NULL) AND [g].[Latitude] IS NOT NULL) AND ([p].[StatusCode] = CAST(1 AS tinyint))) AND ((
    SELECT COUNT(*)
    FROM [Operation] AS [o1]
    WHERE [p].[Id] = [o1].[PropertyId]) > 0)
ORDER BY [p].[ModificationDate] DESC, [p].[Id], [t].[Id], [t].[Id1]
</code>```

UPDATE 2: As @Igor mentioned, this is the link of the Execution Plan Result:
https://www.brentozar.com/pastetheplan/?id=BJNz9KdQI

答:
Ok, a few things that should help.  #1. .Include() and .Select() should in general be treated mutually exclusive.

You are selecting:

```<code>p.Id,
p.Url,
p.GeneratedTitle,
p.GeoLocation.Address,
p.GeoLocation.Latitude,
p.GeoLocation.Longitude,
p.Domain,
p.Operation,
p.Multimedia.OrderBy(m => m.Order).FirstOrDefault().Resize360x266
</code>```

but then in your foreach loop accessing Price and OperationType entities off it.

Edit Updated the example for the collection of operation. (Whups)

Instead I would recommend:

```<code>p.Id,
p.Url,
p.GeneratedTitle,
p.GeoLocation.Address,
p.GeoLocation.Latitude,
p.GeoLocation.Longitude,
p.Domain,
Operations = p.Operation.Select( o => new
{
   OperationTypeName = o.OperationType.Name,
   o.Price.Amount,
   o.Price.CurrencyCode
}).ToList(),
p.Multimedia.OrderBy(m => m.Order).FirstOrDefault().Resize360x266
</code>```

Then adjust your foreach logic to use the returned properties rather than a returned entity and related entity values.

Loading 40-50k records with something like that image field (MultiMedia) is potentially always going to be problematic. Why do you need to load all 50k in one go?

This looks like something that would put markers on a map. Solutions like this should consider applying a radius filter at the very least to get markers within a reasonable radius of a given center point on a map, or if loading a larger area (zoomed out map) calculating regions and filtering data by region or getting a count falling in that region and loading/rendering the locations in batches of 100 or so rather than potentially waiting for all locations to load.   Something to consider.

Body:
I have the following entities (I'll show the properties I'm working with because I don't want to make it larger than needed):

PROPERTY: Where a property can be child of another one and has a 1-1 relationship with GeoLocation and can have multiple Multimedia and Operation

public partial class Property
{
    public Property()
    {
        InverseParent = new HashSet<Property>();
        Multimedia = new HashSet<Multimedia>();
        Operation = new HashSet<Operation>();
    }

    public long Id { get; set; }
    public string GeneratedTitle { get; set; }
    public string Url { get; set; }
    public DateTime? DatePublished { get; set; }
    public byte StatusCode { get; set; }
    public byte Domain { get; set; }
    public long? ParentId { get; set; }

    public virtual Property Parent { get; set; }
    public virtual GeoLocation GeoLocation { get; set; }
    public virtual ICollection<Property> InverseParent { get; set; }
    public virtual ICollection<Multimedia> Multimedia { get; set; }
    public virtual ICollection<Operation> Operation { get; set; }
}

GEOLOCATION: As mentioned, it has a 1-1 relationship with Property

public partial class GeoLocation
{
    public int Id { get; set; }
    public double? Latitude { get; set; }
    public double? Longitude { get; set; }
    public long? PropertyId { get; set; }

    public virtual Property Property { get; set; }
}

MULTIMEDIA: it can hold multiple Images, with different sizes, for a single Property. The detail here is that Order specifies the order of the images to be shown in the client application, but it doesn't start always with 1. There're some cases where a Property has Multimedia files that starts with 3 or x.

public partial class Multimedia
{
    public long Id { get; set; }
    public long? Order { get; set; }
    public string Resize360x266 { get; set; }
    public long? PropertyId { get; set; }

    public virtual Property Property { get; set; }
}

OPERATIONS: defines all the operations a Property can have, using OperationType to name this operation. (rent, sell, etc.)

public partial class Operation
{
    public Operation()
    {
        Price = new HashSet<Price>();
    }

    public long Id { get; set; }
    public long? OperationTypeId { get; set; }
    public long? PropertyId { get; set; }

    public virtual OperationType OperationType { get; set; }
    public virtual Property Property { get; set; }
    public virtual ICollection<Price> Price { get; set; }
}

public partial class OperationType
{
    public OperationType()
    {
        Operation = new HashSet<Operation>();
    }

    public long Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Operation> Operation { get; set; }
}

PRICE: defines the price for each operation and the currency type. (i.e.: A property can have the rent option - Operation - for X amount in USD currency, but another price registered for the same Operation in case of use another currency type )

public partial class Price
{
    public long Id { get; set; }
    public float? Amount { get; set; }
    public string CurrencyCode { get; set; }
    public long? OperationId { get; set; }

    public virtual Operation Operation { get; set; }
}

Said that, I want to get all the records (actually are about 40K-50K), but only for a few properties. As I mentioned before, the Multimedia table can have a lot of records for each Property, but I only need the first one with the smaller Order value and sorted by DatePublished. After that, I need to convert the result into MapMarker object, which is as follows:

public class MapMarker : EstateBase
{
    public long Price { get; set; }
    public int Category { get; set; }
    public List<Tuple<string, string, string>> Prices { get; set; }
}

In order to achieve this, I made the following:

public async Task<IEnumerable<MapMarker>> GetGeolocatedPropertiesAsync(int quantity)
{
    var properties = await GetAllProperties().AsNoTracking()
        .Include(g => g.GeoLocation)
        .Include(m => m.Multimedia)
        .Include(p => p.Operation).ThenInclude(o => o.Price)
        .Include(p => p.Operation).ThenInclude(o => o.OperationType)
        .Where(p => p.GeoLocation != null
            && !string.IsNullOrEmpty(p.GeoLocation.Address)
            && p.GeoLocation.Longitude != null
            && p.GeoLocation.Latitude != null
            && p.StatusCode == (byte)StatusCode.Online
            && p.Operation.Count > 0)
        .OrderByDescending(p => p.ModificationDate)
        .Take(quantity)
        .Select(p => new {
            p.Id,
            p.Url,
            p.GeneratedTitle,
            p.GeoLocation.Address,
            p.GeoLocation.Latitude,
            p.GeoLocation.Longitude,
            p.Domain,
            p.Operation,
            p.Multimedia.OrderBy(m => m.Order).FirstOrDefault().Resize360x266
        })
        .ToListAsync();

    var mapMarkers = new List<MapMarker>();

    try
    {
        foreach (var property in properties)
        {
            var mapMarker = new MapMarker();
            mapMarker.Id = property.Id.ToString();
            mapMarker.Url = property.Url;
            mapMarker.Title = property.GeneratedTitle ?? string.Empty;
            mapMarker.Address = property.Address ?? string.Empty;
            mapMarker.Latitude = property.Latitude.ToString() ?? string.Empty;
            mapMarker.Longitude = property.Longitude.ToString() ?? string.Empty;
            mapMarker.Domain = ((Domain)Enum.ToObject(typeof(Domain), property.Domain)).ToString();
            mapMarker.Image = property.Resize360x266 ?? string.Empty;
            mapMarker.Prices = new List<Tuple<string, string, string>>();
            foreach (var operation in property.Operation)
            {
                foreach (var price in operation.Price)
                {
                    var singlePrice = new Tuple<string, string, string>(operation.OperationType.Name, price.CurrencyCode, price.Amount.ToString());
                    mapMarker.Prices.Add(singlePrice);
                }
            }
            mapMarkers.Add(mapMarker);
        }
    }
    catch (Exception ex)
    {

        throw;
    }

    return mapMarkers;
}

but the results take more than 14 minutes and this method could be called multiple times in a minute. I want to optimize it to return the results in the less time possible. I alreay tried removing ToListAsync(), but in the foreach loop it takes a lot of time too, and that makes all the sense.

So, what do you think I can do here?
Thanks in advance.

UPDATE:
Here is GetAllProperties() method, I forgot to include this one.

private IQueryable<Property> GetAllProperties()
{
    return _dbContext.Property.AsQueryable();
}

And the SQL query that Entity Framework is making against SQL Server:

SELECT [p].[Id], [p].[Url], [p].[GeneratedTitle], [g].[Address], [g].[Latitude], [g].[Longitude], [p].[Domain], (
    SELECT TOP(1) [m].[Resize360x266]
    FROM [Multimedia] AS [m]
    WHERE [p].[Id] = [m].[PropertyId]
    ORDER BY [m].[Order]), [t].[Id], [t].[CreationDate], [t].[ModificationDate], [t].[OperationTypeId], [t].[PropertyId], [t].[Id0], [t].[CreationDate0], [t].[ModificationDate0], [t].[Name], [t].[Id1], [t].[Amount], [t].[CreationDate1], [t].[CurrencyCode], [t].[ModificationDate1], [t].[OperationId]
FROM [Property] AS [p]
LEFT JOIN [GeoLocation] AS [g] ON [p].[Id] = [g].[PropertyId]
LEFT JOIN (
    SELECT [o].[Id], [o].[CreationDate], [o].[ModificationDate], [o].[OperationTypeId], [o].[PropertyId], [o0].[Id] AS [Id0], [o0].[CreationDate] AS [CreationDate0], [o0].[ModificationDate] AS [ModificationDate0], [o0].[Name], [p0].[Id] AS [Id1], [p0].[Amount], [p0].[CreationDate] AS [CreationDate1], [p0].[CurrencyCode], [p0].[ModificationDate] AS [ModificationDate1], [p0].[OperationId]
    FROM [Operation] AS [o]
    LEFT JOIN [OperationType] AS [o0] ON [o].[OperationTypeId] = [o0].[Id]
    LEFT JOIN [Price] AS [p0] ON [o].[Id] = [p0].[OperationId]
) AS [t] ON [p].[Id] = [t].[PropertyId]
WHERE (((([g].[Id] IS NOT NULL AND ([g].[Address] IS NOT NULL AND (([g].[Address] <> N'') OR [g].[Address] IS NULL))) AND [g].[Longitude] IS NOT NULL) AND [g].[Latitude] IS NOT NULL) AND ([p].[StatusCode] = CAST(1 AS tinyint))) AND ((
    SELECT COUNT(*)
    FROM [Operation] AS [o1]
    WHERE [p].[Id] = [o1].[PropertyId]) > 0)
ORDER BY [p].[ModificationDate] DESC, [p].[Id], [t].[Id], [t].[Id1]

UPDATE 2: As @Igor mentioned, this is the link of the Execution Plan Result:
https://www.brentozar.com/pastetheplan/?id=BJNz9KdQI

Body:
Ok, a few things that should help.  #1. .Include() and .Select() should in general be treated mutually exclusive.

You are selecting:

p.Id,
p.Url,
p.GeneratedTitle,
p.GeoLocation.Address,
p.GeoLocation.Latitude,
p.GeoLocation.Longitude,
p.Domain,
p.Operation,
p.Multimedia.OrderBy(m => m.Order).FirstOrDefault().Resize360x266

but then in your foreach loop accessing Price and OperationType entities off it.

Edit Updated the example for the collection of operation. (Whups)

Instead I would recommend:

p.Id,
p.Url,
p.GeneratedTitle,
p.GeoLocation.Address,
p.GeoLocation.Latitude,
p.GeoLocation.Longitude,
p.Domain,
Operations = p.Operation.Select( o => new
{
   OperationTypeName = o.OperationType.Name,
   o.Price.Amount,
   o.Price.CurrencyCode
}).ToList(),
p.Multimedia.OrderBy(m => m.Order).FirstOrDefault().Resize360x266

Then adjust your foreach logic to use the returned properties rather than a returned entity and related entity values.

Loading 40-50k records with something like that image field (MultiMedia) is potentially always going to be problematic. Why do you need to load all 50k in one go?

This looks like something that would put markers on a map. Solutions like this should consider applying a radius filter at the very least to get markers within a reasonable radius of a given center point on a map, or if loading a larger area (zoomed out map) calculating regions and filtering data by region or getting a count falling in that region and loading/rendering the locations in batches of 100 or so rather than potentially waiting for all locations to load.   Something to consider.


答:
Well, after 2 days I finally found the error.  Posting this in case someone else finds themselves dealing with a similar situation.

I had added new HTML to the template page the above link/url is loading.  The new HTML code was supposed to print out a readable description by referencing {{club.}} - apparently I didn't add all the code, it was supposed to be {{club.ceDesc}} - this was causing the error to be thrown, no page was loading, no other indication this was where the error was coming from.  It appeared the error was being thrown on the ng-click from the prevoius page or in the .state. url call .

Title: isolating an angularjs anonymous $parser:ueoe error


问:
Using testthat to check each variable in a data frame for NA values
I'm building a dataset from very messy raw files, and am using testthat to make sure things don't break as new data is added or cleaning rules are corrected. I'd like to add a test to see if there are any NA values in the data, and, if so, to report which columns they are in.

Its trivial to do so manually, by writing a test for each column. But that solution will be a pain to maintain and error-prone as I don't want to have to remember to update the test-NA file everytime a column is added or removed from the dataset.

Here is example code for what I have

```<code>df <- tidyr::tribble(
  ~A, ~B, ~C,
  1, 2, 3,
  NA, 2, 3,
  1, 2, NA
)

# checks all variables, doesn't report which have NA values
testthat::test_that("NA Values", {
  testthat::expect_true(sum(is.na(df)) == 0)
})

# Checks each column, but is a pain to maintain
testthat::test_that("Variable specific checks", {
  testthat::expect_true(sum(is.na(df$A)) == 0)
  testthat::expect_true(sum(is.na(df$B)) == 0)
  testthat::expect_true(sum(is.na(df$C)) == 0)
})
</code>```

答:
Solution 1: quick and (not so) dirty

```<code>df <- tidyr::tribble(
  ~A, ~B, ~C,
  1, 2, 3,
  NA, 2, 3,
  1, 2, NA
)

# Checks each column, but is a pain to maintain
testthat::test_that("Variable specific checks", {
    res <- apply(df, 2, function(x) sum(is.na(x))>0)
    testthat::expect_true(all(res), label = paste(paste(which(res), collapse=", "), "contain(s) NA(s)"))
})
</code>```

which should return

```<code>Error: Test failed: 'Variable specific checks'
* 1, 3 contain(s) NA isn't true.
</code>```

Solution 2: tailor an expect_() function to your needs

```<code>expect_true2 <- function(object, info = NULL, label = NULL) {
        act <- testthat::quasi_label(rlang::enquo(object), label, arg = "object")
        testthat::expect(identical(as.vector(act$val), TRUE), sprintf("Column %s contain(s) NA(s).",
            act$lab), info = info)
        invisible(act$val)
    }
testthat::test_that("Variable specific checks", {
    res <- apply(df, 2, function(x) sum(is.na(x))>0)
    expect_true2(all(res), label = paste(which(res), collapse=","))
})
</code>```

which should return

```<code>Error: Test failed: 'Variable specific checks'
* Column 1,3 contain(s) NA(s).
</code>```

Body:
I'm building a dataset from very messy raw files, and am using testthat to make sure things don't break as new data is added or cleaning rules are corrected. I'd like to add a test to see if there are any NA values in the data, and, if so, to report which columns they are in.

Its trivial to do so manually, by writing a test for each column. But that solution will be a pain to maintain and error-prone as I don't want to have to remember to update the test-NA file everytime a column is added or removed from the dataset.

Here is example code for what I have

df <- tidyr::tribble(
  ~A, ~B, ~C,
  1, 2, 3,
  NA, 2, 3,
  1, 2, NA
)

# checks all variables, doesn't report which have NA values
testthat::test_that("NA Values", {
  testthat::expect_true(sum(is.na(df)) == 0)
})

# Checks each column, but is a pain to maintain
testthat::test_that("Variable specific checks", {
  testthat::expect_true(sum(is.na(df$A)) == 0)
  testthat::expect_true(sum(is.na(df$B)) == 0)
  testthat::expect_true(sum(is.na(df$C)) == 0)
})

Body:
Solution 1: quick and (not so) dirty

df <- tidyr::tribble(
  ~A, ~B, ~C,
  1, 2, 3,
  NA, 2, 3,
  1, 2, NA
)

# Checks each column, but is a pain to maintain
testthat::test_that("Variable specific checks", {
    res <- apply(df, 2, function(x) sum(is.na(x))>0)
    testthat::expect_true(all(res), label = paste(paste(which(res), collapse=", "), "contain(s) NA(s)"))
})

which should return

Error: Test failed: 'Variable specific checks'
* 1, 3 contain(s) NA isn't true.

Solution 2: tailor an expect_() function to your needs

expect_true2 <- function(object, info = NULL, label = NULL) {
        act <- testthat::quasi_label(rlang::enquo(object), label, arg = "object")
        testthat::expect(identical(as.vector(act$val), TRUE), sprintf("Column %s contain(s) NA(s).",
            act$lab), info = info)
        invisible(act$val)
    }
testthat::test_that("Variable specific checks", {
    res <- apply(df, 2, function(x) sum(is.na(x))>0)
    expect_true2(all(res), label = paste(which(res), collapse=","))
})

which should return

Error: Test failed: 'Variable specific checks'
* Column 1,3 contain(s) NA(s).


问:
How can I change a file change name as it is uploaded with Flask?
I'm trying to create a web app for my team at work and we want it to take user uploaded photos and rename them as they're uploaded. For now, I have a directory on my machine where the files go. My app takes 3 inputs: Name, Email and the file to be uploaded. Upon a user clicking the "upload" button, I want the file to show up in my directory as the email address they entered. For example:

```<code>Name: trent
Email: trent@trent.com
File: photo_of_trent.jpg
</code>```

I would like the uploaded file to show up in my directory as trent@trent.com.jpg.

My Python/Flask code is as follows:

```<code>import os
from flask import Flask, render_template
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import StringField
from wtforms import SubmitField
from wtforms.validators import DataRequired, Email

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY'] = 'I have a dream'
app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(basedir, 'uploads') # you'll need to create a folder named uploads

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # set maximum file size, default is 16MB

class UploadForm(FlaskForm):
    name = StringField('Name', [DataRequired()])
    email = StringField('Email', [Email(message='Not a valid email address.'), DataRequired()])
    photo = FileField(validators=[FileAllowed(photos, 'Image only!'), FileRequired('File was empty!')])
    submit = SubmitField('Upload')

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    form = UploadForm()
    if form.validate_on_submit():
        filename = photos.save(form.photo.data)
        file_url = photos.url(filename)
    else:
        file_url = None
    return render_template('index.html', form=form, file_url=file_url)

if __name__ == '__main__':
    app.run()
</code>```

and my html is as follows:

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

{% block styles %}
    <link rel="stylesheet" href="{{ url_for('static', filename='css/forms.css') }}" rel="stylesheet" type="text/css">
{% endblock %}

{% block content %}
<div class="formwrapper">
  <h2 class="title">Contact</h2>
  <form method="POST" action="/" enctype="multipart/form-data">
      <div class="form-field">{{ form.name.label }} {{ form.name(size=20) }}
      {% if form.name.errors %}
        <ul class="errors">
          {% for error in form.name.errors %}
            <li>{{ error }}</li>
          {% endfor %}
        </ul>
      {% endif %}
      </div>
      <div class="form-field">{{ form.email.label }} {{ form.email }}
      {% if form.email.errors %}
        <ul class="errors">
            {% for error in form.email.errors %}
                <li>{{ error }}</li>
            {% endfor %}
        </ul>
    {% endif %}
      </div>
       {{ form.hidden_tag() }}
     {{ form.photo }}
      {{ form.submit }}

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

It's a not super complex and I kind of mangled this code together as it's my first substantive experience with Flask. There's a little jinja sprinkled in there as well as far as the html is concerned. So far the program only uploads the file with the name of the file. Any help is appreciated. Thank you.

答:
The UploadSet.save() function takes a parameter name, which should give you what you want.

e.g.

```<code>photos.save(form.photo.data, name=f"{form.email.data}.jpg")
</code>```

Note: I'm not sure how the file extension will be handled in this case, so you may need to test/tweak this.

Body:
I'm trying to create a web app for my team at work and we want it to take user uploaded photos and rename them as they're uploaded. For now, I have a directory on my machine where the files go. My app takes 3 inputs: Name, Email and the file to be uploaded. Upon a user clicking the "upload" button, I want the file to show up in my directory as the email address they entered. For example:

Name: trent
Email: trent@trent.com
File: photo_of_trent.jpg

I would like the uploaded file to show up in my directory as trent@trent.com.jpg.

My Python/Flask code is as follows:

import os
from flask import Flask, render_template
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import StringField
from wtforms import SubmitField
from wtforms.validators import DataRequired, Email

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY'] = 'I have a dream'
app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(basedir, 'uploads') # you'll need to create a folder named uploads

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # set maximum file size, default is 16MB

class UploadForm(FlaskForm):
    name = StringField('Name', [DataRequired()])
    email = StringField('Email', [Email(message='Not a valid email address.'), DataRequired()])
    photo = FileField(validators=[FileAllowed(photos, 'Image only!'), FileRequired('File was empty!')])
    submit = SubmitField('Upload')

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    form = UploadForm()
    if form.validate_on_submit():
        filename = photos.save(form.photo.data)
        file_url = photos.url(filename)
    else:
        file_url = None
    return render_template('index.html', form=form, file_url=file_url)

if __name__ == '__main__':
    app.run()

and my html is as follows:

{% extends 'layout.html' %}

{% block styles %}
    <link rel="stylesheet" href="{{ url_for('static', filename='css/forms.css') }}" rel="stylesheet" type="text/css">
{% endblock %}

{% block content %}

Contact

  <form method="POST" action="/" enctype="multipart/form-data">

{{ form.name.label }} {{ form.name(size=20) }}
      {% if form.name.errors %}

          {% for error in form.name.errors %}

{{ error }}

          {% endfor %}

      {% endif %}

{{ form.email.label }} {{ form.email }}
      {% if form.email.errors %}

            {% for error in form.email.errors %}

{{ error }}

            {% endfor %}

    {% endif %}

       {{ form.hidden_tag() }}
     {{ form.photo }}
      {{ form.submit }}

  </form>

{% endblock %}

It's a not super complex and I kind of mangled this code together as it's my first substantive experience with Flask. There's a little jinja sprinkled in there as well as far as the html is concerned. So far the program only uploads the file with the name of the file. Any help is appreciated. Thank you.

Body:
The UploadSet.save() function takes a parameter name, which should give you what you want.

e.g.

photos.save(form.photo.data, name=f"{form.email.data}.jpg")

Note: I'm not sure how the file extension will be handled in this case, so you may need to test/tweak this.


问:
background transition flash when mouse leave target
I'm trying to animate background property using transition.

When I hover over target it works smooth but when I leave out it makes like flash!

Shouldn't it be smooth in and out?

It looks that mix-blend-mode behind this flashing issue or maybe sth else so I need explanation.

a {
    position:relative;
    display:block;
}

img {
    position:relative;
    width: 172px;
    border-radius:15px;
    float:left;
    margin-bottom:10px;
    filter:grayscale(100%);
}

a::after {
    position: absolute;
    left: 0;
    top: 0;
    width: 172px;
    height: 242px;
    background: #2d293e;
    content: " ";
    display: block;
    border-radius: 14px;
    mix-blend-mode: screen;
    transition: opacity 300ms ease-in-out,background 400ms ease-in-out;
}

a:hover::after {
    background:#FF0101;
    opacity:0.1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><a>
    <img src="https://images.wikidi.net/crop/172x242/http://f2.fsm.wikidi.com/af/ad/yb/e0d20df22741de9c3480e691bc7a3a41efceddcd.jpg" alt=""/>
</a></code>```

答:
The issue you're having is to do with timing. This line in particular:

```<code>transition: opacity 300ms ease-in-out,background 400ms ease-in-out;
</code>```

the opacity only lasts 300ms, and then for 100ms the background transition continues but the opacity transition has stopped.

This means that if you want the exact opposite to happen, you want the opacity to be delayed 100ms before it begins to transition for 300ms.

To do this, you just need to add the following in then a::after css, and keep the above line in the a:hover::after definition:

```<code>transition: opacity 300ms ease-in-out 100ms,background 400ms ease-in-out;
</code>```

(the 100 ms after ease-in-out for the opacity transition in shorthand for a 100ms delay).

then the transition looks the same going in and going out. See the snippet:

a {
    position:relative;
    display:block;
}

img {
    position:relative;
    width: 172px;
    border-radius:15px;
    float:left;
    margin-bottom:10px;
    filter:grayscale(100%);
}

a::after {
    position: absolute;
    left: 0;
    top: 0;
    width: 172px;
    height: 242px;
    background: #2d293e;
    content: " ";
    display: block;
    border-radius: 14px;
    mix-blend-mode: screen;
    transition: opacity 300ms ease-in-out 100ms,background 400ms ease-in-out;
}

a:hover::after {
    background:#FF0101;
    opacity:0.1;
    transition: opacity 300ms ease-in-out,background 400ms ease-in-out;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><a>
    <img src="https://images.wikidi.net/crop/172x242/http://f2.fsm.wikidi.com/af/ad/yb/e0d20df22741de9c3480e691bc7a3a41efceddcd.jpg" alt=""/>
</a></code>```

Body:
The issue you're having is to do with timing. This line in particular:

transition: opacity 300ms ease-in-out,background 400ms ease-in-out;

the opacity only lasts 300ms, and then for 100ms the background transition continues but the opacity transition has stopped.

This means that if you want the exact opposite to happen, you want the opacity to be delayed 100ms before it begins to transition for 300ms.

To do this, you just need to add the following in then a::after css, and keep the above line in the a:hover::after definition:

transition: opacity 300ms ease-in-out 100ms,background 400ms ease-in-out;

(the 100 ms after ease-in-out for the opacity transition in shorthand for a 100ms delay).

then the transition looks the same going in and going out. See the snippet:

a {
    position:relative;
    display:block;
}

img {
    position:relative;
    width: 172px;
    border-radius:15px;
    float:left;
    margin-bottom:10px;
    filter:grayscale(100%);
}

a::after {
    position: absolute;
    left: 0;
    top: 0;
    width: 172px;
    height: 242px;
    background: #2d293e;
    content: " ";
    display: block;
    border-radius: 14px;
    mix-blend-mode: screen;
    transition: opacity 300ms ease-in-out 100ms,background 400ms ease-in-out;
}

a:hover::after {
    background:#FF0101;
    opacity:0.1;
    transition: opacity 300ms ease-in-out,background 400ms ease-in-out;
}

<a>
    <img src="https://images.wikidi.net/crop/172x242/http://f2.fsm.wikidi.com/af/ad/yb/e0d20df22741de9c3480e691bc7a3a41efceddcd.jpg" alt=""/>
</a>


问:
Settings for multiple partitions, multiple node for service fabric stateless service
With current situation of using stateless services, to prevent loss of connection the required design is using primary instance running in every node (Currently set to use 5 nodes) and hopefully each primary running in every node helps endpoint not error out due to connection loss. (In this case, SignalR)

So the design would be:
Single primary and 4 replicas in each partition total 5 partitions running in 5 nodes.

This should have been a straightforward configuration setting, but turns out tricky to accomplish due to lack of thorough manuals with example code.

So far, what I have found out is:

Setting DefaultValue="-1" for the Service instance count achieves the service to run in every node but you still need it to be in combination with one of the followings:

SingletonPartition or
UniformInt64Partition or
NamedPartition

SingletonPartition is the default in Stateless service and combination of DefaultValue "-1" with SingletonPartition forces the service run on only one node, which beats the purpose of using multiple nodes.

So I tried something like:
StatelessService InstanceCount="5"  (Should this be 25 including replicas?)
UniformInt64Partition PartitionCount="5" lowKey="0" highkey="5"  (Should the highkey be 24 to include all the replicas?)

Some link says lowkey and highkey should match number of partitions and another link seemingly including all the instances including replicas.

I am still not successful in achieving 5 partitions, 5 nodes and each parition running primary service..

答:
You should use replica set in both cases. In term of stateless service in Service Fabric, replica is just a copy of a service.
Plus, partitioning stateless service is a very rare scenario.</p>


问:
C++ Dynamic Array Increase Size By 1 with each add - ERROR
I'm working on an assignment for an OO C++ class and I'm stumped. The assignment is to add grade (int) to a dynamic array and increase the size of that array by 1. The array must start with zero. Here are the specifications given to us:

Specification Bundle.

Specification B1 - Dynamic Array
Create an array on the heap. Store student scores in it.

Specification B2 - Add Elements
Start your array at size 0 and increase it by one every time you add
a new score with menu option 1.

I've looked at numerous examples on the web in our book and I am just banging my head against the wall. I've moved stuff around, tried to put things in different orders etc. I've come up with the following code and it just wont work. I'm pretty sure someone with experience is just gonna tell me I forgot a comma but here goes. I understand the basic concept is to create the dynamic array, create a temporary array that is one size bigger, then copy the elements of the original array to the temp array and then to just point the dynamic array to the temp array's memory address, delete the old array then wash rinse repeat, but i just cant seem to do it. I need help :) Currently i get a heap corruption error message. Here's the code.

```<code>#include <iostream>
#include <cstdlib> // do not use
#include <ctime> // for seeding random numbers
#include <string>

using namespace std;

//Global Variables

//Function Prototypes
void ProgramGreeting(); // All programs will have this method - Draw a happy litte tree
int mainMenu(int[], int*, int*); //Main Menu
void addGrade(int[], int*, int*); // Add a grade to the list. Takes the array  and the number of items in the array
void displayGrades(int[], int); // Display all the grades. Takes the array and the number of items in the array
void processGrades(int[], int); // Process all the grades. Takes the array and the number of items in the array
char letterGrade(int); // Return a letter grade
void Unittest(); // All CISP400 programs should have this.

int main()
{
    // Specification B1 - Dynamic Array
    int* grades = NULL;
    int max = 0;
    int numofGrades = 0; //A counter for the size of the dynamic array
    grades = new int[max];

    ProgramGreeting();
    mainMenu(grades, &numofGrades, &max);

    delete[] grades;

    return 0;
}

void ProgramGreeting()
{
    // Specification C1 - Program Greeting Function
    cout << "Welcome to GPA Analyzer!" << endl;
    cout << "Written by William Graves" << endl;
    cout << "This assignment is due on February 16, 2020" << endl;
}

int mainMenu(int grades[], int *numofGrades, int *max)
{
    char ans;

    do {

        cout << "Main Menu" << endl;
        cout << "--------------" << endl;
        cout << "1) Add Grade" << endl;
        cout << "2) Display All Grades" << endl;
        cout << "3) Process All Grades" << endl;
        cout << "4) Quit" << endl << endl;
        cout << "Enter your choice: ";
        cin >> ans;

        switch (ans) {
        case '1': //The user selected add grade
            addGrade(grades, numofGrades, max);
            break;
        case '2': //Display all grades
            displayGrades(grades, *numofGrades);
            break;
        case '3': //Display all grades
            processGrades(grades, *numofGrades);
            break;
        case '4': //The user chose to exit.
            cout << "Exit time. ";
            return 1000;
            break;
            // Specification C4 - Bulletproof Menu
        default:
            cout << "Your selection of '" << ans << "' is invalid. Try again." << endl;
            break;
        }
    } while (1);

}

void addGrade(int grades[], int *numofGrades, int *max) // Add a grade to the list. Takes the array  and the number of items in the array
{
    int gradeEntry = 0;
    cout << "Enter the grade: ";
    cin >> gradeEntry;
    if (gradeEntry <= 100 && gradeEntry >= 0) //verify that the grade entered is between 0 and 100
    {
        grades[*numofGrades] = gradeEntry;
        cout << "Grade of " << gradeEntry << " added successfully.";
        *numofGrades = *numofGrades + 1;
        if (*numofGrades >= *max)
        {
            *max += 1;
            //create a temporary array a size bigger:
            int* tempArray = new int[*max];
            //copy the contents of the old array to the newly allocated array
            for (int i = 0; i < *numofGrades; i++)
            {
                tempArray[i] = grades[i];
            }
            //get rid of the old array.
            delete[] grades;
            //change the memory location.
            grades = tempArray;
        }
        return;
    }
    else
    {
        cout << "Error occured. User entered: " << gradeEntry << " The grade must be an integer between 0 and 100. No grade added." << endl;
        return;
    }
}
</code>```

答:
When debugging something like this, always try to walk yourself through the code line by line for a typical input. (Words of wisdom from my own Data Structures prof)

In this case it looks like it has to do with your array size.
You initialize an int array of size 0.
In your first call to addGrade() function, you

1. Get input from console. (so far so good)

2. Then you set grades[0] equal to your input

3. Then you resize the array.

The issue is the order of steps 2 and 3. You start with array of size 0, so you can't set grades[0] to anything because you haven't allocated memory for it yet. You must FIRST resize your array, THEN copy in your new (and old) data.

Hope that helps for this time around, but next time a bug comes around on an assignment, try to use it as a chance to test out some debugging techniques (no matter how primitive they may be). I'm sure your professor would gladly give suggestions on HOW TO DEBUG this.

Body:
I'm working on an assignment for an OO C++ class and I'm stumped. The assignment is to add grade (int) to a dynamic array and increase the size of that array by 1. The array must start with zero. Here are the specifications given to us:

Specification Bundle.

Specification B1 - Dynamic Array
Create an array on the heap. Store student scores in it.

Specification B2 - Add Elements
Start your array at size 0 and increase it by one every time you add
a new score with menu option 1.

I've looked at numerous examples on the web in our book and I am just banging my head against the wall. I've moved stuff around, tried to put things in different orders etc. I've come up with the following code and it just wont work. I'm pretty sure someone with experience is just gonna tell me I forgot a comma but here goes. I understand the basic concept is to create the dynamic array, create a temporary array that is one size bigger, then copy the elements of the original array to the temp array and then to just point the dynamic array to the temp array's memory address, delete the old array then wash rinse repeat, but i just cant seem to do it. I need help :) Currently i get a heap corruption error message. Here's the code.

#include <iostream>
#include <cstdlib> // do not use
#include <ctime> // for seeding random numbers
#include <string>

using namespace std;

//Global Variables

//Function Prototypes
void ProgramGreeting(); // All programs will have this method - Draw a happy litte tree
int mainMenu(int[], int*, int*); //Main Menu
void addGrade(int[], int*, int*); // Add a grade to the list. Takes the array  and the number of items in the array
void displayGrades(int[], int); // Display all the grades. Takes the array and the number of items in the array
void processGrades(int[], int); // Process all the grades. Takes the array and the number of items in the array
char letterGrade(int); // Return a letter grade
void Unittest(); // All CISP400 programs should have this.

int main()
{
    // Specification B1 - Dynamic Array
    int* grades = NULL;
    int max = 0;
    int numofGrades = 0; //A counter for the size of the dynamic array
    grades = new int[max];

    ProgramGreeting();
    mainMenu(grades, &numofGrades, &max);

    delete[] grades;

    return 0;
}

void ProgramGreeting()
{
    // Specification C1 - Program Greeting Function
    cout << "Welcome to GPA Analyzer!" << endl;
    cout << "Written by William Graves" << endl;
    cout << "This assignment is due on February 16, 2020" << endl;
}

int mainMenu(int grades[], int *numofGrades, int *max)
{
    char ans;

    do {

        cout << "Main Menu" << endl;
        cout << "--------------" << endl;
        cout << "1) Add Grade" << endl;
        cout << "2) Display All Grades" << endl;
        cout << "3) Process All Grades" << endl;
        cout << "4) Quit" << endl << endl;
        cout << "Enter your choice: ";
        cin >> ans;

        switch (ans) {
        case '1': //The user selected add grade
            addGrade(grades, numofGrades, max);
            break;
        case '2': //Display all grades
            displayGrades(grades, *numofGrades);
            break;
        case '3': //Display all grades
            processGrades(grades, *numofGrades);
            break;
        case '4': //The user chose to exit.
            cout << "Exit time. ";
            return 1000;
            break;
            // Specification C4 - Bulletproof Menu
        default:
            cout << "Your selection of '" << ans << "' is invalid. Try again." << endl;
            break;
        }
    } while (1);

}

void addGrade(int grades[], int *numofGrades, int *max) // Add a grade to the list. Takes the array  and the number of items in the array
{
    int gradeEntry = 0;
    cout << "Enter the grade: ";
    cin >> gradeEntry;
    if (gradeEntry <= 100 && gradeEntry >= 0) //verify that the grade entered is between 0 and 100
    {
        grades[*numofGrades] = gradeEntry;
        cout << "Grade of " << gradeEntry << " added successfully.";
        *numofGrades = *numofGrades + 1;
        if (*numofGrades >= *max)
        {
            *max += 1;
            //create a temporary array a size bigger:
            int* tempArray = new int[*max];
            //copy the contents of the old array to the newly allocated array
            for (int i = 0; i < *numofGrades; i++)
            {
                tempArray[i] = grades[i];
            }
            //get rid of the old array.
            delete[] grades;
            //change the memory location.
            grades = tempArray;
        }
        return;
    }
    else
    {
        cout << "Error occured. User entered: " << gradeEntry << " The grade must be an integer between 0 and 100. No grade added." << endl;
        return;
    }
}


问:
File verification and validation
So I have this code here made in a more simplified way:

```<code>var reader = new FileReader();
reader.onload = function(progressEvent) {

    // By lines
    var lines = this.result.split('\n');
    let N = /^(N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$/;

    for (var line = 0; line < lines.length; line++) {
      if (N.test(lines[line])) {
        console.log(lines[line]);
      } else {
        console.log("Invalid register = ", lines[line]);
      }
    }
}

</code>```

What I want is a way that a message can be shown to tell me that the file corresponded to all those requirements and if not that a message can be printed to tell me that the file is not valid, but keep showing me the message at the console. How can I possibly do that? Another question I have is if there is a way to specify that can be only one register called N1

HERE IS A FILE EXAMPLE

```<code>N108258594000135255240708     315370        BLABLA BLABLABL BLAB BLA
N2BLA2222016BLABLA BLABLABLA                                3525.250
N3BLABLABLABL.EXE                                   01BF011351A2B06D7A88048CBDDC53CE
N908234944000135255240708     000016
</code>```

答:
If there should be no occurrences of 2 times N1, you could use a negative lookahead (?!.*N1.*N1) at the start of the pattern asserting not 2 times N1

```<code>^(?!.*N1.*N1)(?:N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$
</code>```

Regex demo

To keep the messages and show a message after the loop if all have passed, you could for example introduce a variable and give it a default value of true.

If there is a line that does not match, you change the variable to false.

For example

```<code>// By lines
var lines = this.result.split('\n');
let N = /^(?!.*N1.*N1)(?:N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$/;
var passAll = true;

for (var line = 0; line < lines.length; line++) {
    if (lines[line].trim() === "") continue;
    if (N.test(lines[line])) {
        console.log(lines[line]);
    } else {
        passAll = false;
        console.log("Invalid register = ", lines[line]);
    }
}
console.log(passAll === true ? "All lines passed" : "Not all lines passed");
</code>```

Title: File verification and validation

Body:
So I have this code here made in a more simplified way:

var reader = new FileReader();
reader.onload = function(progressEvent) {

    // By lines
    var lines = this.result.split('\n');
    let N = /^(N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$/;

    for (var line = 0; line < lines.length; line++) {
      if (N.test(lines[line])) {
        console.log(lines[line]);
      } else {
        console.log("Invalid register = ", lines[line]);
      }
    }
}

What I want is a way that a message can be shown to tell me that the file corresponded to all those requirements and if not that a message can be printed to tell me that the file is not valid, but keep showing me the message at the console. How can I possibly do that? Another question I have is if there is a way to specify that can be only one register called N1

HERE IS A FILE EXAMPLE

N108258594000135255240708     315370        BLABLA BLABLABL BLAB BLA
N2BLA2222016BLABLA BLABLABLA                                3525.250
N3BLABLABLABL.EXE                                   01BF011351A2B06D7A88048CBDDC53CE
N908234944000135255240708     000016

Body:
If there should be no occurrences of 2 times N1, you could use a negative lookahead (?!.*N1.*N1) at the start of the pattern asserting not 2 times N1

^(?!.*N1.*N1)(?:N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$

Regex demo

To keep the messages and show a message after the loop if all have passed, you could for example introduce a variable and give it a default value of true.

If there is a line that does not match, you change the variable to false.

For example

// By lines
var lines = this.result.split('\n');
let N = /^(?!.*N1.*N1)(?:N1\d{14}.{78}|N2.{70}|N3.{82}|N9\d{14}.{14}\d{6})$/;
var passAll = true;

for (var line = 0; line < lines.length; line++) {
    if (lines[line].trim() === "") continue;
    if (N.test(lines[line])) {
        console.log(lines[line]);
    } else {
        passAll = false;
        console.log("Invalid register = ", lines[line]);
    }
}
console.log(passAll === true ? "All lines passed" : "Not all lines passed");