问:
After dynamically add item, it adds outside owl-stage-outer
I am facing strange issue
I have created a carousel which loops through via vuejs.

```<code><div class="owl-carousel unitslide">
  <div  v-for="unit in sortedUnits" class="unit" :class="{selected : activeUnit.id === unit.id}" @click="activeUnit = unit">
     @{{  unit.name }}
  </div>
</div>
</code>```

So after load, above code looks like this.

```<code><div class="owl-carousel unitslide owl-loaded owl-drag">
    <div class="owl-stage-outer">
        <div class="owl-stage" style="transform: translate3d(0px, 0px, 0px); transition: all 0s ease 0s; width: 776px;">
            <div class="owl-item active" style="width: 56.5px; margin-right: 14px;">
                <div class="unit">
                301
                </div>
            </div>
            <div class="owl-item active" style="width: 56.5px; margin-right: 14px;">
                <div class="unit">
                    400
                </div>
            </div>
        </div>
    </div>
    <div class="owl-nav">
        <button type="button" role="presentation" class="owl-prev disabled">
            <div class="arrow left"></div>
        </button>
        <button type="button" role="presentation" class="owl-next">
            <div class="arrow right"></div>
        </button>
    </div>
    <div class="owl-dots disabled"></div>
</div>
</code>```

After adding  some more unit dynamically via vuejs new item add below owl-dots disabled tag like this

```<code><div class="owl-dots disabled"></div>
<div class="unit">501</div>
<div class="unit">502</div>
</code>```

owl carousel not wrapping new items in

```<code><div class="owl-item active"></div>
</code>```

Owl carousel js is this:

```<code>$(".unitslide").owlCarousel({
        margin:14,
        items:4,
        loop:false,
        autoWidth:false,
        dots:false,
        nav: true,
        navText: ["<div class='arrow left'></div>","<div class='arrow right'></div>"]

    });
</code>```

Thanks in advance.

答:
```<code><div v-if=showTopStore >
   <carousel class="carousel-inner" :autoplay="false" :nav="false" :items="1">
       <div v-for="(store, key) in allStore" class="item" >
           <mobile-store-card :store="store" ></mobile-store-card>
       </div>
   </carousel>
</div>
</code>```

showTopStore is False by default and True when the data  is fully loaded.

Body:
I am facing strange issue
I have created a carousel which loops through via vuejs.

     @{{  unit.name }}

So after load, above code looks like this.

                301

                    400

        <button type="button" role="presentation" class="owl-prev disabled">

        </button>
        <button type="button" role="presentation" class="owl-next">

        </button>

After adding  some more unit dynamically via vuejs new item add below owl-dots disabled tag like this

501

502

owl carousel not wrapping new items in

Owl carousel js is this:

$(".unitslide").owlCarousel({
        margin:14,
        items:4,
        loop:false,
        autoWidth:false,
        dots:false,
        nav: true,
        navText: ["

","

"]

    });

Thanks in advance.

Body:
<div v-if=showTopStore >
   <carousel class="carousel-inner" :autoplay="false" :nav="false" :items="1">
       <div v-for="(store, key) in allStore" class="item" >
           <mobile-store-card :store="store" ></mobile-store-card>
       </div>
   </carousel>
</div>

showTopStore is False by default and True when the data  is fully loaded.


来源: stackexchange

问:
Indent error is being triggered and I cannot find a solution
Code:

```<code>def funt():
  print(Fore.GREEN, end='')
  tool = input('Enter Desired Tool: ')
  if tool == 'web':
      try:
        print(Fore.CYAN, end='')
        site = input('Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        if response.status_code == 200:
          print(f'{Fore.GREEN}Online!')
          sleep(1)
        else:
          print(f'{Fore.RED}Offline!')
          sleep(1)

while True:
    funt()
</code>```

Location of Error is while True: .
The Error Is As Follows:

```<code>    while True:
    ^
IndentationError: unexpected unindent
</code>```

I cannot find a solution, there is not any sign of indentation in the while loop.

答:
Do this:

```<code>def funt():
  print(Fore.GREEN, end='')
  tool = input('Enter Desired Tool: ')
  if tool == 'web':
      try:
        print(Fore.CYAN, end='')
        site = input('Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        if response.status_code == 200:
          print(f'{Fore.GREEN}Online!')
          sleep(1)
        else:
          print(f'{Fore.RED}Offline!')
          sleep(1)
      # You were missing this part:
      except:
        print("Message")

while True:
   funt()
</code>```

A try block always goes together with a catch block. The purpose of the try block is to attempt to run code that may throw an exception. The catch block is what catches this exception.

ContentLicense: CC BY-SA 4.0

Body:
Code:

def funt():
  print(Fore.GREEN, end='')
  tool = input('Enter Desired Tool: ')
  if tool == 'web':
      try:
        print(Fore.CYAN, end='')
        site = input('Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        if response.status_code == 200:
          print(f'{Fore.GREEN}Online!')
          sleep(1)
        else:
          print(f'{Fore.RED}Offline!')
          sleep(1)

while True:
    funt()

Location of Error is while True: .
The Error Is As Follows:

    while True:
    ^
IndentationError: unexpected unindent

I cannot find a solution, there is not any sign of indentation in the while loop.

Body:
Do this:

def funt():
  print(Fore.GREEN, end='')
  tool = input('Enter Desired Tool: ')
  if tool == 'web':
      try:
        print(Fore.CYAN, end='')
        site = input('Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        if response.status_code == 200:
          print(f'{Fore.GREEN}Online!')
          sleep(1)
        else:
          print(f'{Fore.RED}Offline!')
          sleep(1)
      # You were missing this part:
      except:
        print("Message")

while True:
   funt()

A try block always goes together with a catch block. The purpose of the try block is to attempt to run code that may throw an exception. The catch block is what catches this exception.


问:
ContainerContentChanging event and data model changes
I'm using the ContentContainerChanging event raised by the GridView to render a grid of image in my UWP app. The app is syncing some data from the web and the data is rendered as they are stored locally to a SQLite database. I have a couple of TextBlocks for two properties in my Model that I bind to from my XAML. I then load the images progressively in the ContentContainerChanging callback. This works great for data that is readily available for rendering but is at direct odds with one way data binding.

My understanding of this event is it is called every time the item is rendered on the screen. In my case, the model with the text data is available ahead of time while the image is still being downloaded. So they see a placeholder. But then once the image has been downloaded, there is no way to force ContentContainerChanging to be called again. When the image is fully downloaded, how can I tell the GridView to re-render only the items in the ViewPort? As the user scrolls, images are going to get rendered, but what if the user never scrolls?

I could refresh the whole ObservableCollection but that is an odd experience for the user. I see the items being removed and all items being added again. Technically, there are no changes to the model itself, only the images. So it seems wasteful. Also the scroll position/context is lost.

Is there a way to somehow kick off ContentContainerChanging again and force the UI to render my images again?

答: Thanks @Faywang. Your suggestion to bind to the full path to the LocalCache image worked well for me. That coupled with x:Phase seems to work exactly like overriding the ContainerContentChanging event.</p>


问:
Wocommerce Diferent template for only one product
I have a simply question :
Can i use different template for just one product leaving default template untouched ?
My case : I have little shop with 4 products but , i want to modify template just for  first product .
Thanks a lot .</p>

答: Yes, it is totally possible. You can override the single-product.php template from Woocommerce by copying the template in (your-child-theme-root/woocommerce/single-product.php). Then you set a condition using the product id and load the template you created for that specific product. PD: Sorry if my English is not 100%.</p>


问:
Will having two NSTimers in one class cause them to be less accurate?
I have one NSTimer which is my main game loop, it calls 60 times a second. I have another timer which is a countdown, which gets called 0.001 times a second. Is it normal that timer is not accurate? or should i call the countdown timer fewer times per second?</p>

答:
If I'm reading your question correctly the second timer (which I assume is fired every 0.001) seconds is not going to be accurate.

NSTimer has a resolution of about 50-100 milliseconds (0.05s-0.1s) and this can be significantly impacted if your run loop is loaded.

ContentLicense: CC BY-SA 3.0


问:
How can I put a callable object into the map in C++?
I am confused why it cannot be used in this way. Is there a way to achieve a function call similar to this?I am confused why it cannot be used in this way. Is there a way to achieve a function call similar to this?</p>

```<code>std::map<std::string, std::function<std::string()>> FUNCS;

void test_map_operator()
{
    FUNCS["MD5"] = [](std::string data) { return std::string("MD5 : ") + data; };
    FUNCS["CRC32"] = [](std::string data) { return std::string("CRC32 : ") + data; };
    FUNCS["RSA"] = [](std::string data, std::string key) { return std::string("RSA : ") + data + key; };

    std::cout << FUNCS["MD5"]("hello") << std::endl;
    std::cout << FUNCS["CRC32"]("hello") << std::endl;
    std::cout << FUNCS["RSA"]("hello","world") << std::endl;
}
</code>```

答:
your function in the map is defined as:

```<code>std::function<std::string()
</code>```

which means, takes no paramters and returns a std::string...
you can as workaround defined to take 2 strings as parameters and ignore the 2nd one in the lambda code for MD5 and CRC32

```<code>std::map<std::string, std::function<std::string(std::string, std::string)>> FUNCS;
</code>```

--

```<code>FUNCS["MD5"] = [](std::string data, std::string) { return std::string("MD5 : ") + data; };
FUNCS["CRC32"] = [](std::string data, std::string) { return std::string("CRC32 : ") + data; };
FUNCS["RSA"] = [](std::string data, std::string key) { return std::string("RSA : ") + data + key; };

std::cout << FUNCS["MD5"]("hello", "") << std::endl;
std::cout << FUNCS["CRC32"]("hello", "") << std::endl;
std::cout << FUNCS["RSA"]("hello", "world") << std::endl;
</code>```

Body:
I am confused why it cannot be used in this way. Is there a way to achieve a function call similar to this?I am confused why it cannot be used in this way. Is there a way to achieve a function call similar to this?

std::map<std::string, std::function<std::string()>> FUNCS;

void test_map_operator()
{
    FUNCS["MD5"] = [](std::string data) { return std::string("MD5 : ") + data; };
    FUNCS["CRC32"] = [](std::string data) { return std::string("CRC32 : ") + data; };
    FUNCS["RSA"] = [](std::string data, std::string key) { return std::string("RSA : ") + data + key; };

    std::cout << FUNCS["MD5"]("hello") << std::endl;
    std::cout << FUNCS["CRC32"]("hello") << std::endl;
    std::cout << FUNCS["RSA"]("hello","world") << std::endl;
}

Body:
your function in the map is defined as:

std::function<std::string()

which means, takes no paramters and returns a std::string...
you can as workaround defined to take 2 strings as parameters and ignore the 2nd one in the lambda code for MD5 and CRC32

std::map<std::string, std::function<std::string(std::string, std::string)>> FUNCS;

--

FUNCS["MD5"] = [](std::string data, std::string) { return std::string("MD5 : ") + data; };
FUNCS["CRC32"] = [](std::string data, std::string) { return std::string("CRC32 : ") + data; };
FUNCS["RSA"] = [](std::string data, std::string key) { return std::string("RSA : ") + data + key; };

std::cout << FUNCS["MD5"]("hello", "") << std::endl;
std::cout << FUNCS["CRC32"]("hello", "") << std::endl;
std::cout << FUNCS["RSA"]("hello", "world") << std::endl;


答:
try expects an except block followed by it.

You can modify your code as follows:

def funt():
  print(Fore.GREEN, end='')
  tool = input('Enter Desired Tool: ')
  if tool == 'web':
      try:
        print(Fore.CYAN, end='')
        site = input('Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        if response.status_code == 200:
          print(f'{Fore.GREEN}Online!')
          sleep(1)
        else:
          print(f'{Fore.RED}Offline!')
          sleep(1)
      except:
        pass

while True:
    funt()
```

But writing proper code requires you to handle exceptions. So, if possible write a piece of code in the except block.

Title: Indent error is being triggered and I cannot find a solution

Body:
try expects an except block followed by it.

You can modify your code as follows:

def funt():
  print(Fore.GREEN, end='')
  tool = input('Enter Desired Tool: ')
  if tool == 'web':
      try:
        print(Fore.CYAN, end='')
        site = input('Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        if response.status_code == 200:
          print(f'{Fore.GREEN}Online!')
          sleep(1)
        else:
          print(f'{Fore.RED}Offline!')
          sleep(1)
      except:
        pass

while True:
    funt()

But writing proper code requires you to handle exceptions. So, if possible write a piece of code in the except block.


问:
Alternative for this react code burger ingereidnet add app
Hi Guys I am new in react i am creating one burger builder app for practice i don't undestand the following code, can any one give the simple alternative for this code?</p>

```<code>    props.ingredients: {
            salad: 0,
            eggs: 0,
            cheese: 0,
            meat: 0
        },

let ingredientList = Object.keys(props.ingredients)
    .map(igKey => {
        return [...Array(props.ingredients[igKey])].map((_, i) => {
            return <BurgerFilling key={igKey + i} type={igKey} />
        });
    })
    .reduce((rootArray, currEl) => {
        console.log('rootArray>>>', rootArray, currEl);
        return rootArray.concat(currEl);
    }, []);
</code>```

答:
Since props.ingredients is an object and each entry within it is just a number, you can simply map over keys of the object and render it without the need for inner map </p>

```<code>let ingredientList = Object.keys(props.ingredients)
    .map((igKey, i) => {
        return <BurgerFilling key={igKey + i} type={igKey} />
    })
</code>```

Body:
Hi Guys I am new in react i am creating one burger builder app for practice i don't undestand the following code, can any one give the simple alternative for this code?

    props.ingredients: {
            salad: 0,
            eggs: 0,
            cheese: 0,
            meat: 0
        },

let ingredientList = Object.keys(props.ingredients)
    .map(igKey => {
        return [...Array(props.ingredients[igKey])].map((_, i) => {
            return <BurgerFilling key={igKey + i} type={igKey} />
        });
    })
    .reduce((rootArray, currEl) => {
        console.log('rootArray>>>', rootArray, currEl);
        return rootArray.concat(currEl);
    }, []);

Body:
Since props.ingredients is an object and each entry within it is just a number, you can simply map over keys of the object and render it without the need for inner map

let ingredientList = Object.keys(props.ingredients)
    .map((igKey, i) => {
        return <BurgerFilling key={igKey + i} type={igKey} />
    })


问:
Igraph shortest path gives an infinite value
I am trying to calculate the distance between a node and two targets, afterwards I compare the lengths of the routes calculated and save the smallest in a list. I know I can use networkx.shortest_path() however this solution takes a long time and the code takes too long to run. For this reason I opted to use Igraph. Here is the code:

```<code>import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
from shapely.wkt import loads as load_wkt
import numpy as np
import matplotlib.cm as cm
import igraph as ig
import matplotlib as mpl
import random as rd
ox.config(log_console=True, use_cache=True)

city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive')

G_nx = nx.relabel.convert_node_labels_to_integers(G)

ox.speed.add_edge_speeds(G_nx, hwy_speeds=20, fallback=20)

ox.speed.add_edge_travel_times(G_nx)

weight = 'travel_time'

coord_1 = (38.74817825481225, -9.160815118526642)  # Coordenada Hospital Santa Maria
coord_2 = (38.74110711410615, -9.152159572392323)  # Coordenada Hopstial Curry Cabral
coord_3 = (38.7287248180068, -9.139114834357233) # Hospital Dona Estefania
coord_4 = (38.71814053423293, -9.137885476529883) # Hospital Sao Jose
target_1 = ox.get_nearest_node(G_nx, coord_1)
target_2 = ox.get_nearest_node(G_nx, coord_2)
target_3 = ox.get_nearest_node(G_nx, coord_3)
target_4 = ox.get_nearest_node(G_nx, coord_4)

G_ig = ig.Graph(directed=True)
G_ig.add_vertices(list(G_nx.nodes()))
G_ig.add_edges(list(G_nx.edges()))
G_ig.vs['osmid'] = list(nx.get_node_attributes(G_nx, 'osmid').values())
G_ig.es[weight] = list(nx.get_edge_attributes(G_nx, weight).values())

assert len(G_nx.nodes()) == G_ig.vcount()
assert len(G_nx.edges()) == G_ig.ecount()

route_length=[]
list_nodes=[]

for node in G_nx.nodes:
    length_1 = G_ig.shortest_paths(source=node, target=target_1, weights=weight)[0][0]
    length_2 = G_ig.shortest_paths(source=node, target=target_2, weights=weight)[0][0]

    if length_1<length_2:
        route_length.append(length_1)
    else:
        route_length.append(length_2)
    list_nodes.append(node)
</code>```

If you print the list with the lengths of the routes some values will be 'inf' which obviously doesn't make sense. Can anyone help me understand why the length would be inf?

答: As Vincent Traag said the distance between two disconnected nodes in inf. So it means that for such results, the node and the source are not connected

Body:
I am trying to calculate the distance between a node and two targets, afterwards I compare the lengths of the routes calculated and save the smallest in a list. I know I can use networkx.shortest_path() however this solution takes a long time and the code takes too long to run. For this reason I opted to use Igraph. Here is the code:

import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
from shapely.wkt import loads as load_wkt
import numpy as np
import matplotlib.cm as cm
import igraph as ig
import matplotlib as mpl
import random as rd
ox.config(log_console=True, use_cache=True)

city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive')

G_nx = nx.relabel.convert_node_labels_to_integers(G)

ox.speed.add_edge_speeds(G_nx, hwy_speeds=20, fallback=20)

ox.speed.add_edge_travel_times(G_nx)

weight = 'travel_time'

coord_1 = (38.74817825481225, -9.160815118526642)  # Coordenada Hospital Santa Maria
coord_2 = (38.74110711410615, -9.152159572392323)  # Coordenada Hopstial Curry Cabral
coord_3 = (38.7287248180068, -9.139114834357233) # Hospital Dona Estefania
coord_4 = (38.71814053423293, -9.137885476529883) # Hospital Sao Jose
target_1 = ox.get_nearest_node(G_nx, coord_1)
target_2 = ox.get_nearest_node(G_nx, coord_2)
target_3 = ox.get_nearest_node(G_nx, coord_3)
target_4 = ox.get_nearest_node(G_nx, coord_4)

G_ig = ig.Graph(directed=True)
G_ig.add_vertices(list(G_nx.nodes()))
G_ig.add_edges(list(G_nx.edges()))
G_ig.vs['osmid'] = list(nx.get_node_attributes(G_nx, 'osmid').values())
G_ig.es[weight] = list(nx.get_edge_attributes(G_nx, weight).values())

assert len(G_nx.nodes()) == G_ig.vcount()
assert len(G_nx.edges()) == G_ig.ecount()

route_length=[]
list_nodes=[]

for node in G_nx.nodes:
    length_1 = G_ig.shortest_paths(source=node, target=target_1, weights=weight)[0][0]
    length_2 = G_ig.shortest_paths(source=node, target=target_2, weights=weight)[0][0]

    if length_1<length_2:
        route_length.append(length_1)
    else:
        route_length.append(length_2)
    list_nodes.append(node)

If you print the list with the lengths of the routes some values will be 'inf' which obviously doesn't make sense. Can anyone help me understand why the length would be inf?


问:
Is there a way to compare every array value with eachother effectively?
So Ive been trying to compare given double values in an array with eachother to return the smallest one, but the way I do it does not seem to work consistently and very efficient. Im feeling lost.</p>

```<code>public static double FindSmallestNum(double[] arr)
    {
            double max = 0;
      for (int x=0;x<arr.Length-1;x++){
                if ( arr[x]>= arr[x+1]){
                    if (max >= arr[x+1]){
                       max = arr[x+1];
                    }
                }
                else if (max >=arr[x]){
                        max = arr[x];
                }
                else {
                            max = arr[x];
                }
            }
            return max;
        }
</code>```

答:
If you are willing to use System.Linq (which it appears that you are, given the accepted answer), then you may as well just go straight to the Min() method:

```<code>public static double FindSmallestNum(double[] arr)
{
    return arr.Min();
}
</code>```

Although, given that it's a simple one-line method call, it's not clear that a helper method is really all that helpful in this case.

Problems with your code

In your sample code, it appears that the problem is that you set max = 0; (why do you call it max instead of min?) and then start doing comparisons to see if max is larger than items in the array. This can be problematic, since all positive numbers will be larger than max, so they will never be considered.

To fix this, first let's rename that variable to min, so we remember what we're doing, and then set it to the first value in the array. This way we know we're dealing with a number in our array, and all comparisons will be valid.

Next, we don't need to compare each item with the next item - that comparison is not relevant to finding the smallest of all the items. We only need to compare each item to the current value of min (and do the necessary reassignment if we find a lower number).

This would reduce the code to something like:

```<code>public static double FindSmallestNum(double[] input)
{
    if (input == null) throw new ArgumentNullException(nameof(input));
    if (input.Length == 0)
        throw new InvalidOperationException("array contains no elements");

    // Start with the first number
    double smallest = input[0];

    // Now compare the rest of the items with 'smallest'
    for (int index = 1; index < input.Length; index++)
    {
        if (input[index] < smallest) smallest = input[index];
    }

    return smallest;
}
</code>```

Body:
So Ive been trying to compare given double values in an array with eachother to return the smallest one, but the way I do it does not seem to work consistently and very efficient. Im feeling lost.

public static double FindSmallestNum(double[] arr)
    {
            double max = 0;
      for (int x=0;x<arr.Length-1;x++){
                if ( arr[x]>= arr[x+1]){
                    if (max >= arr[x+1]){
                       max = arr[x+1];
                    }
                }
                else if (max >=arr[x]){
                        max = arr[x];
                }
                else {
                            max = arr[x];
                }
            }
            return max;
        }

Body:
If you are willing to use System.Linq (which it appears that you are, given the accepted answer), then you may as well just go straight to the Min() method:

public static double FindSmallestNum(double[] arr)
{
    return arr.Min();
}

Although, given that it's a simple one-line method call, it's not clear that a helper method is really all that helpful in this case.

Problems with your code

In your sample code, it appears that the problem is that you set max = 0; (why do you call it max instead of min?) and then start doing comparisons to see if max is larger than items in the array. This can be problematic, since all positive numbers will be larger than max, so they will never be considered.

To fix this, first let's rename that variable to min, so we remember what we're doing, and then set it to the first value in the array. This way we know we're dealing with a number in our array, and all comparisons will be valid.

Next, we don't need to compare each item with the next item - that comparison is not relevant to finding the smallest of all the items. We only need to compare each item to the current value of min (and do the necessary reassignment if we find a lower number).

This would reduce the code to something like:

public static double FindSmallestNum(double[] input)
{
    if (input == null) throw new ArgumentNullException(nameof(input));
    if (input.Length == 0)
        throw new InvalidOperationException("array contains no elements");

    // Start with the first number
    double smallest = input[0];

    // Now compare the rest of the items with 'smallest'
    for (int index = 1; index < input.Length; index++)
    {
        if (input[index] < smallest) smallest = input[index];
    }

    return smallest;
}


问:
Why do i get different accuracies on sparse_categorical_accuracy and val_sparse_categorical_accuracy when i pass in the same data
I used the same dataset for training and validating my model and yet i get different training and validation accuracy/loss. shouldn't the accuracy/loss be the same since i'm using the same data?

Here is the code:

```<code>def create_model(dataset):
    model = tf.keras.models.Sequential([tf.keras.layers.BatchNormalization(),
                                        tf.keras.layers.Conv2D(32, (3, 3), activation='relu', ),
                                        tf.keras.layers.MaxPool2D(2, 2),

                                        tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
                                        tf.keras.layers.MaxPool2D(2, 2),

                                        tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
                                        tf.keras.layers.MaxPool2D(2, 2),

                                        tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
                                        tf.keras.layers.MaxPool2D(2, 2),

                                        tf.keras.layers.Dropout(0.5),
                                        tf.keras.layers.Flatten(),
                                        tf.keras.layers.Dense(128, activation='relu'),
                                        tf.keras.layers.Dense(2, activation='softmax')])

    model.compile(
        optimizer='adam',
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_accuracy'])
    model.fit(dataset, validation_data=dataset)
    return model

</code>```

I get out of this:

```<code>100/100 [==============================] - 178s 2s/step - loss: 0.6487 - sparse_categorical_accuracy: 0.6212 - val_loss: 0.5866 - val_sparse_categorical_accuracy: 0.7001

</code>```

Note that I only went through one epoch.

答: This is because Dropout layers doesn't work while validation. Also train accuracy is a mean average of all batch accuracies, while validation one is an accuracy of whole dataset.

Body:
I used the same dataset for training and validating my model and yet i get different training and validation accuracy/loss. shouldn't the accuracy/loss be the same since i'm using the same data?

Here is the code:

def create_model(dataset):
    model = tf.keras.models.Sequential([tf.keras.layers.BatchNormalization(),
                                        tf.keras.layers.Conv2D(32, (3, 3), activation='relu', ),
                                        tf.keras.layers.MaxPool2D(2, 2),

                                        tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
                                        tf.keras.layers.MaxPool2D(2, 2),

                                        tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
                                        tf.keras.layers.MaxPool2D(2, 2),

                                        tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
                                        tf.keras.layers.MaxPool2D(2, 2),

                                        tf.keras.layers.Dropout(0.5),
                                        tf.keras.layers.Flatten(),
                                        tf.keras.layers.Dense(128, activation='relu'),
                                        tf.keras.layers.Dense(2, activation='softmax')])

    model.compile(
        optimizer='adam',
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_accuracy'])
    model.fit(dataset, validation_data=dataset)
    return model

I get out of this:

100/100 [==============================] - 178s 2s/step - loss: 0.6487 - sparse_categorical_accuracy: 0.6212 - val_loss: 0.5866 - val_sparse_categorical_accuracy: 0.7001

Note that I only went through one epoch.


问:
photutils residual_image has stars when saving it to fits file
after doing PSF photometry with fixed stars using photutils I display the residual image and some stars are not fully removed. I tried saving the residual_image to a fits file to inspect it better but the resultant fits file has little boxes with the stars PSF in the position of the original star.
Do you know how can I save the residual_image to a fits file without including the inspected stars?
Here is the piece of code saving the image:

```<code>residual_image = photometry.get_residual_image()
fits.writeto('psf_residual.fits',data=residual_image,overwrite=True)
</code>```

Here is a section of the resultant image:
https://i.stack.imgur.com/TP3IE.png

答:
Solved.
After many tries, I discovered that the sigma I was using for the PSF model was too large, I was thinking it was too small [insert facepalm here]. </p>

Body:
after doing PSF photometry with fixed stars using photutils I display the residual image and some stars are not fully removed. I tried saving the residual_image to a fits file to inspect it better but the resultant fits file has little boxes with the stars PSF in the position of the original star.
Do you know how can I save the residual_image to a fits file without including the inspected stars?
Here is the piece of code saving the image:

residual_image = photometry.get_residual_image()
fits.writeto('psf_residual.fits',data=residual_image,overwrite=True)

Here is a section of the resultant image:
https://i.stack.imgur.com/TP3IE.png


问:
How do I register a parameter for a DbContext with Autofac?
I am using Entity Framework and Sql to work with a database.

My context class is:

```<code> public class AnimalBreedsContext : DbContext
 {
        public DbSet<AnimalBreed> AnimalBreeds { get; set; }

        public AnimalBreedsContext(DbContextOptions<AnimalBreedsContext> options) : base (options)
        {

        }
  }
</code>```

The class AnimalBreeds is a class that has some string properties like Name, etc.

Now I want to register the AnimalBreedsContext class with Autofac. I tried something like that:

```<code>class ContainerConfig
 {
     public static IContainer Configure()
     {
         var builder = new ContainerBuilder();

         var options = new DbContextOptionsBuilder<AnimalBreedsContext>()
                         .UseSqlServer("configString")
                         .Options;

         builder.RegisterType<AnimalBreedsContext>().WithParameter(options).AsSelf();

         return builder.Build();
      }
 }
</code>```

But the problem is that "parameter options can't be converted from AnimalBreedsContext to Autofac.Parameter".

Is there any other option so that I can register this class with Autofac?

答:
It looks like you aren't providing the correct arguments to WithParameter.  Here is the Autofac documentation showing all of the overloads.

Without wrapping the argument in one of the Autofac Parameter objects, it looks like you can provide the string name of the parameter as the first argument, then your actual parameter object as the second:

```<code>builder.RegisterType<AnimalBreedsContext>()
       .AsSelf()
       .WithParameter("options", options);
</code>```

Body:
I am using Entity Framework and Sql to work with a database.

My context class is:

 public class AnimalBreedsContext : DbContext
 {
        public DbSet<AnimalBreed> AnimalBreeds { get; set; }

        public AnimalBreedsContext(DbContextOptions<AnimalBreedsContext> options) : base (options)
        {

        }
  }

The class AnimalBreeds is a class that has some string properties like Name, etc.

Now I want to register the AnimalBreedsContext class with Autofac. I tried something like that:

class ContainerConfig
 {
     public static IContainer Configure()
     {
         var builder = new ContainerBuilder();

         var options = new DbContextOptionsBuilder<AnimalBreedsContext>()
                         .UseSqlServer("configString")
                         .Options;

         builder.RegisterType<AnimalBreedsContext>().WithParameter(options).AsSelf();

         return builder.Build();
      }
 }

But the problem is that "parameter options can't be converted from AnimalBreedsContext to Autofac.Parameter".

Is there any other option so that I can register this class with Autofac?

Body:
It looks like you aren't providing the correct arguments to WithParameter.  Here is the Autofac documentation showing all of the overloads.

Without wrapping the argument in one of the Autofac Parameter objects, it looks like you can provide the string name of the parameter as the first argument, then your actual parameter object as the second:

builder.RegisterType<AnimalBreedsContext>()
       .AsSelf()
       .WithParameter("options", options);


问:
Sticky hover state in chrome on buttons
I have a problem with the hover state in Chrome. There are a couple of bagdes on my site ... when I remove one of them, the next badge remains hovered ... even if I am not hovering with my mouse (same on mobile touch device (but in FF (is it using chrome engine?))). FF and Safari on desktop works fine.

Same Question here.

Couldnt find any solution yet. Can someone help?

答:
we found a solution to that problem. Simply modified the onClick ... the problem was the focus -> .blur() method

before:

```<code>onClick={onRemove}
</code>```

after

```<code>onClick={(event) => {event.currentTarget.blur() onRemove()}}
</code>```

Title: Sticky hover state in chrome on buttons

Body:
we found a solution to that problem. Simply modified the onClick ... the problem was the focus -> .blur() method

before:

onClick={onRemove}

after

onClick={(event) => {event.currentTarget.blur() onRemove()}}


问:
Combine get-ChildItem with ACL powershell
Im looking for some help on information on files using Power shell, we have got most of when we need apart from the owner information.

the code below returns a list of directories that are older then 1 year, but the problem is we cannot seem to get the Owner Information to show in there:

```<code>gci -r
"D:\Network Shares\ICT\ICT\Network Shares\ICT\Innovations\Robert Pitt" | ?
{
    $_.LastWriteTime -lt (Get-Date).AddYears(-1)} >> D:\temp\ICTFileAge.txt
}
</code>```

We know of the command called Get-ACL, but were unsure how to tie it all up.

Anyone have any ideas please, thanks

答:
Something like this?</p>

```<code>gci -r "D:\Network Shares\ICT\ICT\Network Shares\ICT\Innovations\Robert Pitt" |
? {$_.LastWriteTime -lt (Get-Date).AddYears(-1)} |
 % {$_ | add-member -name "Owner" -membertype noteproperty -value (get-acl $_.fullname).owner -passthru} |
  Select fullname,lastwritetime,owner
</code>```

Body:
Im looking for some help on information on files using Power shell, we have got most of when we need apart from the owner information.

the code below returns a list of directories that are older then 1 year, but the problem is we cannot seem to get the Owner Information to show in there:

gci -r
"D:\Network Shares\ICT\ICT\Network Shares\ICT\Innovations\Robert Pitt" | ?
{
    $_.LastWriteTime -lt (Get-Date).AddYears(-1)} >> D:\temp\ICTFileAge.txt
}

We know of the command called Get-ACL, but were unsure how to tie it all up.

Anyone have any ideas please, thanks

Body:
Something like this?

gci -r "D:\Network Shares\ICT\ICT\Network Shares\ICT\Innovations\Robert Pitt" |
? {$_.LastWriteTime -lt (Get-Date).AddYears(-1)} |
 % {$_ | add-member -name "Owner" -membertype noteproperty -value (get-acl $_.fullname).owner -passthru} |
  Select fullname,lastwritetime,owner


问:
How to match and find in a raw file with regex between two strings and get the whole strings between?
I'm going to extract some data from a site, I want to find the string between two specific string and return in, how can I handle it? I am using JavaScript.

I'm going to make it clear with adding the string I want to do extraction on,
for example this is the text that I got :

(0.08%) 40
48,180
48,460
asasasas

<tr data-market-row="price_try"
  data-title="
25920 aasas sasaa (0.12%) 30

25940 asasa (0.04%) 10

25930 sasaas (0.08%) 20

assasa25,990

sasasasa
"
  class="pointer " onclick="if (!window.__cfRLUnblockHandlers) return false; window.location='chart/price_try'"
  data-price="25,920" data-cf-modified-4bf6cd1a2128b0ccaf953372-="">
  skkss
  25,920
  (0.12%) 30
  25,860
  26,010
  sssss

<tr data-market-row="price_cny"
  data-title="
24830 saasa asasa (0.08%) 20

24820 222 ssa (0.12%) 30

24830 2ss 22222 (0.08%) 20

sasasas: 24,890

ssssaaa
"
  class="pointer " onclick="if (!window.__cfRLUnblockHandlers) return false; window.location='chart/price_cny'"
  data-price="24,830" data-cf-modified-4bf6cd1a2128b0ccaf953372-="">
  ssssss
  24,830
  (0.08%) 20
```

I want to retrieve all strings which string with <tr data-market-row="price_try" and ends with /price_try">

答:
assuming the string

```<code>let str = `<td class="nf"><span class="low">(0.08%) 40</span></td>
<td>48,180</td>
<td>48,460</td>
<td>asasasas</td>
<td class="chart-td"><a data-tooltip="saasasa" class="chart-icon" target="_blank" href="chart/price_aed"></a></td>
</tr>
<tr data-market-row="price_try"
  data-title="<div class='tooltip-row'><span class='tooltip-row-txt'>25920 aasas sasaa </span><span class='tooltip-row-change'><span class='type low'>(0.12%) 30</span></span></div><hr><div class='tooltip-row'><span class='tooltip-row-txt'>25940 asasa </span><span class='tooltip-row-change'><span class='type low'>(0.04%) 10</span></span></div><hr><div class='tooltip-row'><span class='tooltip-row-txt'>25930 sasaas </span><span class='tooltip-row-change'><span class='type low'>(0.08%) 20</span></span></div><hr> <div class='highlight'>assasa25,990</div><div class='tooltip-info'>sasasasa</div>"
  class="pointer " onclick="if (!window.__cfRLUnblockHandlers) return false; window.location='chart/price_try'"
  data-price="25,920" data-cf-modified-4bf6cd1a2128b0ccaf953372-="">
  <th><span class="mini-flag flag-tr"></span>skkss </th>
  <td class="nf">25,920</td>
  <td class="nf"><span class="low">(0.12%) 30</span></td>
  <td>25,860</td>
  <td>26,010</td>
  <td>sssss</td>
  <td class="chart-td"><a data-tooltip="sssss" class="chart-icon" target="_blank" href="chart/price_try"></a></td>
</tr>
<tr data-market-row="price_cny"
  data-title="<div class='tooltip-row'><span class='tooltip-row-txt'>24830 saasa asasa </span><span class='tooltip-row-change'><span class='type low'>(0.08%) 20</span></span></div><hr><div class='tooltip-row'><span class='tooltip-row-txt'>24820 222 ssa </span><span class='tooltip-row-change'><span class='type low'>(0.12%) 30</span></span></div><hr><div class='tooltip-row'><span class='tooltip-row-txt'>24830 2ss 22222 </span><span class='tooltip-row-change'><span class='type low'>(0.08%) 20</span></span></div><hr> <div class='highlight'>sasasas: 24,890</div><div class='tooltip-info'>ssssaaa</div>"
  class="pointer " onclick="if (!window.__cfRLUnblockHandlers) return false; window.location='chart/price_cny'"
  data-price="24,830" data-cf-modified-4bf6cd1a2128b0ccaf953372-="">
  <th><span class="mini-flag flag-cn"></span>ssssss </th>
  <td class="nf">24,830</td>
  <td class="nf"><span class="low">(0.08%) 20</span></td>`
</code>```

you can extract your thing with the following regex:

```<code>str.replace(/\r?\n|\r/g, '').match(/<tr data-market-row="price_try"(.*)\/price_try"><\/a><\/td><\/tr>/)[1];
</code>```

Body:
I'm going to extract some data from a site, I want to find the string between two specific string and return in, how can I handle it? I am using JavaScript.

I'm going to make it clear with adding the string I want to do extraction on,
for example this is the text that I got :

(0.08%) 40
48,180
48,460
asasasas

<tr data-market-row="price_try"
  data-title="
25920 aasas sasaa (0.12%) 30

25940 asasa (0.04%) 10

25930 sasaas (0.08%) 20

assasa25,990

sasasasa
"
  class="pointer " onclick="if (!window.__cfRLUnblockHandlers) return false; window.location='chart/price_try'"
  data-price="25,920" data-cf-modified-4bf6cd1a2128b0ccaf953372-="">
  skkss
  25,920
  (0.12%) 30
  25,860
  26,010
  sssss

<tr data-market-row="price_cny"
  data-title="
24830 saasa asasa (0.08%) 20

24820 222 ssa (0.12%) 30

24830 2ss 22222 (0.08%) 20

sasasas: 24,890

ssssaaa
"
  class="pointer " onclick="if (!window.__cfRLUnblockHandlers) return false; window.location='chart/price_cny'"
  data-price="24,830" data-cf-modified-4bf6cd1a2128b0ccaf953372-="">
  ssssss
  24,830
  (0.08%) 20

I want to retrieve all strings which string with <tr data-market-row="price_try" and ends with /price_try">

Body:
assuming the string

let str = `<td class="nf"><span class="low">(0.08%) 40</span></td>
<td>48,180</td>
<td>48,460</td>
<td>asasasas</td>
<td class="chart-td"><a data-tooltip="saasasa" class="chart-icon" target="_blank" href="chart/price_aed"></a></td>
</tr>
<tr data-market-row="price_try"
  data-title="<div class='tooltip-row'><span class='tooltip-row-txt'>25920 aasas sasaa </span><span class='tooltip-row-change'><span class='type low'>(0.12%) 30</span></span></div><hr><div class='tooltip-row'><span class='tooltip-row-txt'>25940 asasa </span><span class='tooltip-row-change'><span class='type low'>(0.04%) 10</span></span></div><hr><div class='tooltip-row'><span class='tooltip-row-txt'>25930 sasaas </span><span class='tooltip-row-change'><span class='type low'>(0.08%) 20</span></span></div><hr> <div class='highlight'>assasa25,990</div><div class='tooltip-info'>sasasasa</div>"
  class="pointer " onclick="if (!window.__cfRLUnblockHandlers) return false; window.location='chart/price_try'"
  data-price="25,920" data-cf-modified-4bf6cd1a2128b0ccaf953372-="">
  <th><span class="mini-flag flag-tr"></span>skkss </th>
  <td class="nf">25,920</td>
  <td class="nf"><span class="low">(0.12%) 30</span></td>
  <td>25,860</td>
  <td>26,010</td>
  <td>sssss</td>
  <td class="chart-td"><a data-tooltip="sssss" class="chart-icon" target="_blank" href="chart/price_try"></a></td>
</tr>
<tr data-market-row="price_cny"
  data-title="<div class='tooltip-row'><span class='tooltip-row-txt'>24830 saasa asasa </span><span class='tooltip-row-change'><span class='type low'>(0.08%) 20</span></span></div><hr><div class='tooltip-row'><span class='tooltip-row-txt'>24820 222 ssa </span><span class='tooltip-row-change'><span class='type low'>(0.12%) 30</span></span></div><hr><div class='tooltip-row'><span class='tooltip-row-txt'>24830 2ss 22222 </span><span class='tooltip-row-change'><span class='type low'>(0.08%) 20</span></span></div><hr> <div class='highlight'>sasasas: 24,890</div><div class='tooltip-info'>ssssaaa</div>"
  class="pointer " onclick="if (!window.__cfRLUnblockHandlers) return false; window.location='chart/price_cny'"
  data-price="24,830" data-cf-modified-4bf6cd1a2128b0ccaf953372-="">
  <th><span class="mini-flag flag-cn"></span>ssssss </th>
  <td class="nf">24,830</td>
  <td class="nf"><span class="low">(0.08%) 20</span></td>`

you can extract your thing with the following regex:

str.replace(/\r?\n|\r/g, '').match(/<tr data-market-row="price_try"(.*)\/price_try"><\/a><\/td><\/tr>/)[1];


问:
Onclick show div overlapping/hiding others
I'm trying to achieve 3 clickable
 that expand and hide/overlap others on click, while showing what's inside each clicked
. I only have JQuery as of right now.

My initial question is, what should I use? (Flexbox? CSS animation? React?)
Is it possible in vanilla html+css+js stack without having a bonky transition ?
I made an image to illustrate what I'm trying to say:

答:
I am answering my own question to show you the progress I made.
This is greatly starting to get form following both your advices.
 (Jsfiddle at the end).

HTML

```<code>   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StackCode</title>
    <link rel="stylesheet" href="dummy.css" />
</head>
<body>
<header>
</header>
<section class="section">
        <div class="service-box">
                <div class="service-story">
                            <div> <h1> Title </h1> </div>
                <img class="img-left" src="https://via.placeholder.com/250x700">
                            <div class="service-story-expand">
                                <h1>TITLE</h1>
                                <p>Sample text</p>
                                <img src="https://via.placeholder.com/100">
                            </div>
                 </div>
                 <div class="service-art">
                            <div> <h2> Title2 </h2></div>
                            <img class="img-middle" src="https://via.placeholder.com/250x700">
                            <div class="service-art-expand">
                                <h1>TITLE</h1>
                                <p>Sammple text</p>
                            </div>
                 </div>
                 <div class="service-motion">
                            <div> <h2> Title3 </h2></div>
                            <img class="img-right" src="https://via.placeholder.com/250x700">
                            <div class="service-motion-expand">
                                <h1>TITLE</h1>
                                <p>Sammple text</p>
                            </div>
                 </div>
            </div>
</section>
<script src="jquery-3.4.1.min.js"></script>
<script src="dummy.js"></script>
</body>
</html>
</code>```

CSS

```<code>*
{
    margin:0px;
    padding:0px;
}

html {
    overflow-x :hidden;
    background: black;
}

header
{
  height:20px;
    overflow: hidden;
    background-color: black;
    padding: 45 0 0 0;
    z-index: 0;
    width: 100%;
}

.section{
    width: 100%;
    background:grey;
    margin: auto;
}

.service-box{
  overflow: hidden;
    width: 90%;
    height: auto;
    margin:auto;
    display: flex;
    justify-content: space-evenly;
}

.service-story{
    height: auto;
    overflow: hidden;
    flex:1;
    order: 1;
    transition: flex .3s ease-out;
}

.service-story.clicked{
    background:white;
    height: auto;
    flex:6;
    transition: flex .3s ease-out;
}

.service-story-expand{
    display: none;
}

.service-art{
    overflow: hidden;
    flex:1;
    transition: flex .3s ease-out;
    order: 2;
}

.service-art.clicked{
    background:white;
    flex:6;
    transition: flex .3s ease-out;
}

.service-art-expand{
    display: none;
}

.service-motion{
    overflow: hidden;
    flex:1;
    transition: flex .3s ease-out;
    order: 3;
}

.service-motion.clicked{
    background:white;
    flex:6;
    transition: flex .3s ease-out;
}

.service-motion.clicked img{
    float: left;
}

.service-motion-expand{
    display: none;
}

.service-story.clicked img{
    width:auto;
  height:auto;
}
</code>```

Js + Jquery

```<code>$('.service-story').on('click', function(){
    $(this).toggleClass('clicked');
    $(this).show();
    $('.service-story-expand').show();
});

$('.service-art').on('click', function(){
    $(this).toggleClass('clicked');
    $(this).show();
    $('.service-story-expand').show();
});

$('.service-motion').on('click', function(){
    $(this).toggleClass('clicked');
    $(this).show();
    $('.service-motion-expand').show();
});
</code>```

I chose the solution of flexbox. This is not exactly what I was looking for, but it does the trick.
Now the problem I encounter are the following.

How to put content which is firstly hidden next to my images and not under ?

How to close other divs when one is open ?

How to hide content once a
 is clicked again ? (If I understand correctly, is a "If/Then/Else" situation)

I think the last two questions are frequently asked, so I'll start searching by myself, just showing my progress.

Thank you once again for your time, and I hope I did better on formating.

Here is a jsfiddle.
https://jsfiddle.net/7oa28cg4/

Ps: Also working on responsiveness, i'm learning it.

Body:
I am answering my own question to show you the progress I made.
This is greatly starting to get form following both your advices.
 (Jsfiddle at the end).

HTML

   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StackCode</title>
    <link rel="stylesheet" href="dummy.css" />
</head>
<body>
<header>
</header>
<section class="section">
        <div class="service-box">
                <div class="service-story">
                            <div> <h1> Title </h1> </div>
                <img class="img-left" src="https://via.placeholder.com/250x700">
                            <div class="service-story-expand">
                                <h1>TITLE</h1>
                                <p>Sample text</p>
                                <img src="https://via.placeholder.com/100">
                            </div>
                 </div>
                 <div class="service-art">
                            <div> <h2> Title2 </h2></div>
                            <img class="img-middle" src="https://via.placeholder.com/250x700">
                            <div class="service-art-expand">
                                <h1>TITLE</h1>
                                <p>Sammple text</p>
                            </div>
                 </div>
                 <div class="service-motion">
                            <div> <h2> Title3 </h2></div>
                            <img class="img-right" src="https://via.placeholder.com/250x700">
                            <div class="service-motion-expand">
                                <h1>TITLE</h1>
                                <p>Sammple text</p>
                            </div>
                 </div>
            </div>
</section>
<script src="jquery-3.4.1.min.js"></script>
<script src="dummy.js"></script>
</body>
</html>

CSS

*
{
    margin:0px;
    padding:0px;
}

html {
    overflow-x :hidden;
    background: black;
}

header
{
  height:20px;
    overflow: hidden;
    background-color: black;
    padding: 45 0 0 0;
    z-index: 0;
    width: 100%;
}

.section{
    width: 100%;
    background:grey;
    margin: auto;
}

.service-box{
  overflow: hidden;
    width: 90%;
    height: auto;
    margin:auto;
    display: flex;
    justify-content: space-evenly;
}

.service-story{
    height: auto;
    overflow: hidden;
    flex:1;
    order: 1;
    transition: flex .3s ease-out;
}

.service-story.clicked{
    background:white;
    height: auto;
    flex:6;
    transition: flex .3s ease-out;
}

.service-story-expand{
    display: none;
}

.service-art{
    overflow: hidden;
    flex:1;
    transition: flex .3s ease-out;
    order: 2;
}

.service-art.clicked{
    background:white;
    flex:6;
    transition: flex .3s ease-out;
}

.service-art-expand{
    display: none;
}

.service-motion{
    overflow: hidden;
    flex:1;
    transition: flex .3s ease-out;
    order: 3;
}

.service-motion.clicked{
    background:white;
    flex:6;
    transition: flex .3s ease-out;
}

.service-motion.clicked img{
    float: left;
}

.service-motion-expand{
    display: none;
}

.service-story.clicked img{
    width:auto;
  height:auto;
}

Js + Jquery

$('.service-story').on('click', function(){
    $(this).toggleClass('clicked');
    $(this).show();
    $('.service-story-expand').show();
});

$('.service-art').on('click', function(){
    $(this).toggleClass('clicked');
    $(this).show();
    $('.service-story-expand').show();
});

$('.service-motion').on('click', function(){
    $(this).toggleClass('clicked');
    $(this).show();
    $('.service-motion-expand').show();
});

I chose the solution of flexbox. This is not exactly what I was looking for, but it does the trick.
Now the problem I encounter are the following.

How to put content which is firstly hidden next to my images and not under ?

How to close other divs when one is open ?

How to hide content once a <div> is clicked again ? (If I understand correctly, is a "If/Then/Else" situation)

I think the last two questions are frequently asked, so I'll start searching by myself, just showing my progress.

Thank you once again for your time, and I hope I did better on formating.

Here is a jsfiddle.
https://jsfiddle.net/7oa28cg4/

Ps: Also working on responsiveness, i'm learning it.


问:
how can I add a object into a realm list at a certain place in the list (IOS Swift)
var projects: Results<ProjectsModel>?

Is it possible to insert an object into a Results list at a certain position?

I am trying to drag and drop cells in a collection view and I need to insert the item being dragged into the collection view.

projects.insert is not an option.

答:
Unsorted Realm Results objects do not maintain ordering.

From the docs

Note that the order of Results is only guaranteed to stay consistent
  when the query is sorted.

However, if your filter includes a sort clause then it will maintain ordering.

That being said, if you store an object in Realm and it fits the criteria of the Results filter and sort, it will automatically be added and sorted into the correct position automatically.

In other words, suppose your results object is sorted by a string property

```<code>class LetterObject: Object {
   @objc dynamic var letter = ""
}

let aLetter = LetterObject()
aLetter.letter = "a"

let cLetter = LetterObject()
cLetter.letter = "c"

let dLetter = LetterObject()
dLetter.letter = "d"
</code>```

and then populate a class var that holds the letters; a, c, d sorted by the .letter property.

```<code>self.letterResults = realm.objects(LetterObject.self).sorted(byKeyPath: "letter")
</code>```

then we add another letter object to Realm; b

```<code>let bLetter = LetterObject()
bLetter.letter = "b"

try! realm.write {
   realm.add(bLetter)
}
</code>```

the self.letterResults will automatically be updated to include that letter; a, b, c, d and sorted.

You will need to use notifications to watch for that event so you know when to update your UI.

Body:
Unsorted Realm Results objects do not maintain ordering.

From the docs

Note that the order of Results is only guaranteed to stay consistent
  when the query is sorted.

However, if your filter includes a sort clause then it will maintain ordering.

That being said, if you store an object in Realm and it fits the criteria of the Results filter and sort, it will automatically be added and sorted into the correct position automatically.

In other words, suppose your results object is sorted by a string property

class LetterObject: Object {
   @objc dynamic var letter = ""
}

let aLetter = LetterObject()
aLetter.letter = "a"

let cLetter = LetterObject()
cLetter.letter = "c"

let dLetter = LetterObject()
dLetter.letter = "d"

and then populate a class var that holds the letters; a, c, d sorted by the .letter property.

self.letterResults = realm.objects(LetterObject.self).sorted(byKeyPath: "letter")

then we add another letter object to Realm; b

let bLetter = LetterObject()
bLetter.letter = "b"

try! realm.write {
   realm.add(bLetter)
}

the self.letterResults will automatically be updated to include that letter; a, b, c, d and sorted.

You will need to use notifications to watch for that event so you know when to update your UI.


问:
is there a way to do onChange() on internent explorer only with Javascript, HTML, CSS (No Jquery)
is there a way to do onChange() on internent explorer only with Javascript, HTML, CSS (No Jquery). My code send the input to my function upon onChange(). It worked perfectly when I was using chrome. But I just notice that onChange() doesn't work on I.E like it does on chrome. Is there a way to make it work like it does on chrome Or is there something else that I could do which would call the function after I select an option? If not I have to change all 400 lines of my script code :(</p>

```<code><label>Choose a browser from this list:
        <input id = "input1" list="table1" name="myBrowser"
        style="width: 500px;"  onchange="castvote('input1','table1')" onclick="test('input1')"/>
</label>
    <datalist id="table1">
        <option value="Firefox">
        <option value="more options">
</code>```

答:
Below is a very simple example of adding listeners via vanilla js.
Now it has been updated to look for a class such as castVote and in a loop add the listener to each element

(function addCastVoteListeners() {
  const els = Array.prototype.slice.call(document.querySelectorAll('.castVote'));
  els.forEach(addCastVoteListener);
})();
function addCastVoteListener(el) {
  el.addEventListener('change', castVote);
}
function castVote() {
  console.log('cast vote');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Choose a browser from this list:
        <input id = "input1" list="table1" name="myBrowser" class="castVote"
        style="width: 500px;"/>
</label>
<datalist id="table1">
    <option value="Firefox">
    <option value="more options">
</datalist></code>```

Body:
is there a way to do onChange() on internent explorer only with Javascript, HTML, CSS (No Jquery). My code send the input to my function upon onChange(). It worked perfectly when I was using chrome. But I just notice that onChange() doesn't work on I.E like it does on chrome. Is there a way to make it work like it does on chrome Or is there something else that I could do which would call the function after I select an option? If not I have to change all 400 lines of my script code :(

Choose a browser from this list:
        <input id = "input1" list="table1" name="myBrowser"
        style="width: 500px;"  onchange="castvote('input1','table1')" onclick="test('input1')"/>

    <datalist id="table1">
        <option value="Firefox">
        <option value="more options">

Body:
Below is a very simple example of adding listeners via vanilla js.
Now it has been updated to look for a class such as castVote and in a loop add the listener to each element

(function addCastVoteListeners() {
  const els = Array.prototype.slice.call(document.querySelectorAll('.castVote'));
  els.forEach(addCastVoteListener);
})();
function addCastVoteListener(el) {
  el.addEventListener('change', castVote);
}
function castVote() {
  console.log('cast vote');
}

<label>Choose a browser from this list:
        <input id = "input1" list="table1" name="myBrowser" class="castVote"
        style="width: 500px;"/>
</label>
<datalist id="table1">
    <option value="Firefox">
    <option value="more options">
</datalist>


问:
Taking JSON values in a response and mapping them to a state object with keys?
[Noob to Javascript and React] I am using an API that returns an object with values like this. AAPL, AMZN, FB, GOOGL, can be anything based on the function's string array input.

```<code>{
        AAPL: { price: 329.99 },
        AMZN: { price: 2563.05 },
        FB: { price: 239.93 },
        GOOGL: { price: 1469.12 }
}
</code>```

How could I consider dynamically mapping a response like this into a state object like this? The id property doesn't exist, it needs to be created.

```<code>state = {
 stocks: [ { id: 1, name: 'AAPL', price: 329.99 }, { id: 2, name: 'AMZN', price: 2563.05 }, ...]
}
</code>```

I'm able to successfully print the stock names and their prices separately but I am having trouble figuring out how I could wire them into a state object like what's above.

```<code>    function getCurrentPriceOfBatchStocks(_stocks) {
        iex
            .symbols(_stocks)
            .price()
            .then(res => {
                console.log(typeof res);
                console.log(res);
                console.log(Object.keys(res));
                console.log(Object.values(res));
            });
    }
</code>```

答:
Here is an implementation. With Object.entries, you get an array with an array of [key, value] of your original object. And you can map this array to a different format.

You can check the result with the Run code snippet button.

let st = {
    AAPL: { price: 329.99 },
    AMZN: { price: 2563.05 },
    FB: { price: 239.93 },
    GOOGL: { price: 1469.12 }
}

let stocks = Object.entries(st).map(([key, value], index) => ({id: index + 1, name: key, price: value.price}))

console.log(stocks)```

Body:
[Noob to Javascript and React] I am using an API that returns an object with values like this. AAPL, AMZN, FB, GOOGL, can be anything based on the function's string array input.

{
        AAPL: { price: 329.99 },
        AMZN: { price: 2563.05 },
        FB: { price: 239.93 },
        GOOGL: { price: 1469.12 }
}

How could I consider dynamically mapping a response like this into a state object like this? The id property doesn't exist, it needs to be created.

state = {
 stocks: [ { id: 1, name: 'AAPL', price: 329.99 }, { id: 2, name: 'AMZN', price: 2563.05 }, ...]
}

I'm able to successfully print the stock names and their prices separately but I am having trouble figuring out how I could wire them into a state object like what's above.

    function getCurrentPriceOfBatchStocks(_stocks) {
        iex
            .symbols(_stocks)
            .price()
            .then(res => {
                console.log(typeof res);
                console.log(res);
                console.log(Object.keys(res));
                console.log(Object.values(res));
            });
    }


问:
Indent error is being triggered and I cannot find a solution
Code:

```<code>def funt():
  print(Fore.GREEN, end='')
  tool = input('Enter Desired Tool: ')
  if tool == 'web':
      try:
        print(Fore.CYAN, end='')
        site = input('Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        if response.status_code == 200:
          print(f'{Fore.GREEN}Online!')
          sleep(1)
        else:
          print(f'{Fore.RED}Offline!')
          sleep(1)

while True:
    funt()
</code>```

Location of Error is while True: .
The Error Is As Follows:

```<code>    while True:
    ^
IndentationError: unexpected unindent
</code>```

I cannot find a solution, there is not any sign of indentation in the while loop.

答:
You've missed except block for your try block

Here's some info on exception handling in python.

Body:
Code:

def funt():
  print(Fore.GREEN, end='')
  tool = input('Enter Desired Tool: ')
  if tool == 'web':
      try:
        print(Fore.CYAN, end='')
        site = input('Please Enter The Website Here: ')
        response = requests.get(site)
        requests.get(site)
        if response.status_code == 200:
          print(f'{Fore.GREEN}Online!')
          sleep(1)
        else:
          print(f'{Fore.RED}Offline!')
          sleep(1)

while True:
    funt()

Location of Error is while True: .
The Error Is As Follows:

    while True:
    ^
IndentationError: unexpected unindent

I cannot find a solution, there is not any sign of indentation in the while loop.


问:
Powershell Start-Process bugs out when using credentials
So I've set up some credentials to be imported from an encrypted text file, an am trying to use them in conjunction with the 'start process' cmdlet.
I'm new to powershell so cld be missing smoething obvious, but if i type  Start-Process powershell.exe it opens a new ps windows as expected, however trying StartProcess powershell.exe -Credential $cred doesnt work. I know its not about not having the access rights on the credentials provided, cos I get hit with the error message Start-Process: This command cannot be run due to the error ; The filename or extension is too long
This is confusing me as I havent changed the filename / source - all ive done is provided credentials. I've even confirmed that the $cred is indeed a credential, and if i type it into the terminal i do indeed get the username and System.Security.SecureString back.

Any Ideas?

Edit: My code looks like this:

```<code>[string]$pswd= Get-Content 'C:\Users\USER\pswd.txt'
[SecureString]$ss= $pswd | ConvertTo-SecureString -AsPlainText -Force
[string]$un ='USERNAME'
[PSCredential]$cred = New-Object System.Management.Automation.PSCredential ($un, $ss)
Start-Process powershell -Credential $cred
</code>```

And The Password is set like this:

```<code>[string]$Password='PASSWORD'
[SecureString]$SS = $Password | ConvertTo-SecureString -AsPlainText -Force
[string]$STR = $SS | ConvertFrom-SecureString
$STR | Set-Content -Path 'C:\Users\USER\pswd.txt'
</code>```

答:
OK, the issue is the way you're saving the secure string to read later. Try this:

```<code>$pwd = "Password"
$pwds = $pwd | ConvertTo-SecureString -AsPlainText -Force
$pwdse = ConvertFrom-SecureString -SecureString $pwds
$pwdse | Out-File "C:\Users\User\pswd.txt"
</code>```

Then to read it back in:

```<code>$pwd = Get-Content "C:\Users\User\pswd.txt" | ConvertTo-SecureString
</code>```

From then on, you can create your PSCredential object the same as normal and it should work fine.

Body:
So I've set up some credentials to be imported from an encrypted text file, an am trying to use them in conjunction with the 'start process' cmdlet.
I'm new to powershell so cld be missing smoething obvious, but if i type  Start-Process powershell.exe it opens a new ps windows as expected, however trying StartProcess powershell.exe -Credential $cred doesnt work. I know its not about not having the access rights on the credentials provided, cos I get hit with the error message Start-Process: This command cannot be run due to the error ; The filename or extension is too long
This is confusing me as I havent changed the filename / source - all ive done is provided credentials. I've even confirmed that the $cred is indeed a credential, and if i type it into the terminal i do indeed get the username and System.Security.SecureString back.

Any Ideas?

Edit: My code looks like this:

[string]$pswd= Get-Content 'C:\Users\USER\pswd.txt'
[SecureString]$ss= $pswd | ConvertTo-SecureString -AsPlainText -Force
[string]$un ='USERNAME'
[PSCredential]$cred = New-Object System.Management.Automation.PSCredential ($un, $ss)
Start-Process powershell -Credential $cred

And The Password is set like this:

[string]$Password='PASSWORD'
[SecureString]$SS = $Password | ConvertTo-SecureString -AsPlainText -Force
[string]$STR = $SS | ConvertFrom-SecureString
$STR | Set-Content -Path 'C:\Users\USER\pswd.txt'

Body:
OK, the issue is the way you're saving the secure string to read later. Try this:

$pwd = "Password"
$pwds = $pwd | ConvertTo-SecureString -AsPlainText -Force
$pwdse = ConvertFrom-SecureString -SecureString $pwds
$pwdse | Out-File "C:\Users\User\pswd.txt"

Then to read it back in:

$pwd = Get-Content "C:\Users\User\pswd.txt" | ConvertTo-SecureString

From then on, you can create your PSCredential object the same as normal and it should work fine.


问:
css clearing an absolutely positioned div
I have a page with divs 250px x 250px which are all positioned absolutely, when one of these divs are opened an ajax call is made which expands the div to show all its contents, these divs are restricted to 600px in width but can be any height depending on info being presented so when a div has alot of content it seems to stretch over my footer which is understandable due to the fact that the widgets hovering on the page.

My question though is can I somehow set my footer to clear this large widget as it seems to be stretching over it?

答:
There is no way of clearing an absolutely positioned div, absolutely positioned divs are taken completely out of the document flow. You can have a look at using a sticky footer which should keep your footer at the very bottom of the page which should visually fix up your page as the footer will no longer abruptly end.

However unless you restructure your HTML or use some javascript to check the height of the div, you wont be able to have the footer appear nicely underneath the div using pure CSS.


问:
IntersectionObserver not working in Safari or iOS
I have a piece of code that adds a different css class to elements depending on whether they're scrolled into or out of the viewport from top or bottom.

It uses the Intersection Observer because it is supposed to handle large amounts of elements better than scroll events.

However, I am facing two problems with this code:

It does not work in Safari (latest version)

It does not work on mobile Apple devices

This is odd because the IntersectionObserver should work fine on Safari and even mobile browsers on iOS.

You can find the code on jsFiddle or see the snippet here:

const config = {
  // Add root here so rootBounds in entry object is not null
  root: document,
  // Margin to when element should take action
  rootMargin: '-50px 0px',
  // Callback will be fired 30 times during intersection
  threshold: [...Array(30).keys()].map(x => x / 29)
};

let observer = new IntersectionObserver(function(entries, observer) {

  entries.forEach((entry, index) => {
    const element = entry.target;

    // Get root element (document) coords
    const rootTop = entry.rootBounds.top;
    const rootBottom = entry.rootBounds.height;

    // Get div coords
    const topBound = entry.boundingClientRect.top - 50; // margin in config
    const bottomBound = entry.boundingClientRect.bottom;

    let className;

    // Do calculations to get class names
    if (topBound < rootTop && bottomBound < rootTop) {
      className = "outview-top";
    } else if (topBound > rootBottom) {
      className = "outview-bottom";
    } else if (topBound < rootBottom && bottomBound > rootBottom) {
      className = "inview-bottom";
    } else if (topBound < rootTop && bottomBound > rootTop) {
      className = "inview-top";
    }
    element.setAttribute('data-view', className);

  });
}, config);

const viewbox = document.querySelectorAll('.viewme');
viewbox.forEach(image => {
  observer.observe(image);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: center;
}

.margins {
  position: fixed;
  top: 50px;
  bottom: 50px;
  border-top: 2px dashed;
  border-bottom: 2px dashed;
  z-index: 1;
  left: 0;
  width: 100%;
  pointer-events: none;
}

.hi {
  padding: 40vh 0;
  background: lightgray;
}

.box {
  width: 23%;
  min-width: 100px;
  height: 40vh;
  margin-bottom: 10px;
  background: lightblue;
  display: inline-block;
}

.viewme {
  transition: all .3s ease;
}

.viewme[data-view='inview-top'],
.viewme[data-view='inview-bottom'] {
  opacity: 1;
  transform: translateY(0);
}

.viewme[data-view='outview-top'] {
  opacity: 0;
  transform: translateY(-20px);
}

.viewme[data-view='outview-bottom'] {
  opacity: 0;
  transform: translateY(20px);
}</code>```

Scroll down and back up

```

So far, I have two hints as to what might cause these problems:

In the Safari developer console, it says there is a Type error between line 10 and 38 in my JS code

I have noticed that other scripts defining root: document do not work on iOS. Instead, they work when defining root: null. However, I can not use root: null because of rootBounds. I've tried to wrap my html in a div and set the id of the div as the root element but that didn't work (see here).

Any help to solve both problems is much appreciated. However, please do consider that I did not write the code above and don't understand it very well.

答:
Although I can't put my finger on the exact cause of the bug, I do have a solution:

Try using document.body as the root and define sizes and scroll behavior to both html and body.

I think this relates to document being more than a simple html node (I also tried using document.documentElement without success) and how Safari initializes the box model for it.

Anyway, here's the updated working fiddle https://jsfiddle.net/gion_13/okrcgejt/8/ and screencasts of the tests on iOS and Mac Safari:

Body:
I have a piece of code that adds a different css class to elements depending on whether they're scrolled into or out of the viewport from top or bottom.

It uses the Intersection Observer because it is supposed to handle large amounts of elements better than scroll events.

However, I am facing two problems with this code:

It does not work in Safari (latest version)

It does not work on mobile Apple devices

This is odd because the IntersectionObserver should work fine on Safari and even mobile browsers on iOS.

You can find the code on jsFiddle or see the snippet here:

const config = {
  // Add root here so rootBounds in entry object is not null
  root: document,
  // Margin to when element should take action
  rootMargin: '-50px 0px',
  // Callback will be fired 30 times during intersection
  threshold: [...Array(30).keys()].map(x => x / 29)
};

let observer = new IntersectionObserver(function(entries, observer) {

  entries.forEach((entry, index) => {
    const element = entry.target;

    // Get root element (document) coords
    const rootTop = entry.rootBounds.top;
    const rootBottom = entry.rootBounds.height;

    // Get div coords
    const topBound = entry.boundingClientRect.top - 50; // margin in config
    const bottomBound = entry.boundingClientRect.bottom;

    let className;

    // Do calculations to get class names
    if (topBound < rootTop && bottomBound < rootTop) {
      className = "outview-top";
    } else if (topBound > rootBottom) {
      className = "outview-bottom";
    } else if (topBound < rootBottom && bottomBound > rootBottom) {
      className = "inview-bottom";
    } else if (topBound < rootTop && bottomBound > rootTop) {
      className = "inview-top";
    }
    element.setAttribute('data-view', className);

  });
}, config);

const viewbox = document.querySelectorAll('.viewme');
viewbox.forEach(image => {
  observer.observe(image);
});

body {
  text-align: center;
}

.margins {
  position: fixed;
  top: 50px;
  bottom: 50px;
  border-top: 2px dashed;
  border-bottom: 2px dashed;
  z-index: 1;
  left: 0;
  width: 100%;
  pointer-events: none;
}

.hi {
  padding: 40vh 0;
  background: lightgray;
}

.box {
  width: 23%;
  min-width: 100px;
  height: 40vh;
  margin-bottom: 10px;
  background: lightblue;
  display: inline-block;
}

.viewme {
  transition: all .3s ease;
}

.viewme[data-view='inview-top'],
.viewme[data-view='inview-bottom'] {
  opacity: 1;
  transform: translateY(0);
}

.viewme[data-view='outview-top'] {
  opacity: 0;
  transform: translateY(-20px);
}

.viewme[data-view='outview-bottom'] {
  opacity: 0;
  transform: translateY(20px);
}

Scroll down and back up

So far, I have two hints as to what might cause these problems:

In the Safari developer console, it says there is a Type error between line 10 and 38 in my JS code

I have noticed that other scripts defining root: document do not work on iOS. Instead, they work when defining root: null. However, I can not use root: null because of rootBounds. I've tried to wrap my html in a div and set the id of the div as the root element but that didn't work (see here).

Any help to solve both problems is much appreciated. However, please do consider that I did not write the code above and don't understand it very well.


问:
Column width in QTableWidget
The column width 'I' in my table is too large. I tried with

```<code>self.table.setColumnWidth(1,8) # and also lower values
# or:
self.table.resizeColumnToContents(1)
</code>```

but the minimum width I get is the one you see in the image:

This is the whole code:

```<code>    self.table = QTableWidget(2,3,self)
    self.table.setHorizontalHeaderLabels(["Name","I","City"])
    self.table.setItem(0,0,QTableWidgetItem("Mark"))
    self.table.setItem(0,1,QTableWidgetItem("P"))
    self.table.setItem(0,2,QTableWidgetItem("London"))
    self.table.setItem(1,0,QTableWidgetItem("John"))
    self.table.setItem(1,1,QTableWidgetItem("M"))
    self.table.setItem(1,2,QTableWidgetItem("liverpool"))
    self.table.setColumnWidth(1,8)
    #self.table.resizeColumnToContents(1)
    self.table.setStyleSheet("QTableWidget{background-color:white;color:blue;font-size:11pt}QTableWidget::item{padding-left:0px;padding-right:0px}")
</code>```

答:
For example) How to fit the size of the last column to the table width

```<code>ui->QTableWidget->horizontalHeader()->setStretchLastSection(true);
</code>```

size of the last column can change as Table width.

You can also change the Row

```<code>ui->QTableWidget->resizeRowToContents();
</code>```

Title: Column width in QTableWidget

Body:
The column width 'I' in my table is too large. I tried with

self.table.setColumnWidth(1,8) # and also lower values
# or:
self.table.resizeColumnToContents(1)

but the minimum width I get is the one you see in the image:

This is the whole code:

    self.table = QTableWidget(2,3,self)
    self.table.setHorizontalHeaderLabels(["Name","I","City"])
    self.table.setItem(0,0,QTableWidgetItem("Mark"))
    self.table.setItem(0,1,QTableWidgetItem("P"))
    self.table.setItem(0,2,QTableWidgetItem("London"))
    self.table.setItem(1,0,QTableWidgetItem("John"))
    self.table.setItem(1,1,QTableWidgetItem("M"))
    self.table.setItem(1,2,QTableWidgetItem("liverpool"))
    self.table.setColumnWidth(1,8)
    #self.table.resizeColumnToContents(1)
    self.table.setStyleSheet("QTableWidget{background-color:white;color:blue;font-size:11pt}QTableWidget::item{padding-left:0px;padding-right:0px}")

Body:
For example) How to fit the size of the last column to the table width

ui->QTableWidget->horizontalHeader()->setStretchLastSection(true);

size of the last column can change as Table width.

You can also change the Row

ui->QTableWidget->resizeRowToContents();


问:
How to print the result of JSON to the output file?
The output of the JSON file has multiple responses like the one seen below

```<code>
"response_code":1

"scan_date":"2011-07-27 03:44:56"

"permalink":"https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296"

"verbose_msg":"Scan finished, information embedded"

"total":43

"positives":19

</code>```

The below code will get the value of "positives" in the JSON output and then print it to the file.

    # DOES THE HASH EXISTS IN VT DATABASE?
    if response == 0:
        print(hash + ": UNKNOWN")
        file = open(output,"a")
        file.write(hash + " 0")
        file.write("\n")
        file.close()

    # DOES THE HASH EXISTS IN VT DATABASE?
    elif response == 1:
        positives = int(json_response.get("positives"))
        if positives >= 3:
            print(hash + ": MALICIOUS")
            file = open(output,"a")
            file.write(hash + " " + str(positives))
            file.write("\n")
            file.close()
        else:
            print(hash + ": NOT MALICIOUS")
            file = open(output,"a")
            file.write(hash + " 0")
            file.write("\n")
            file.close()
    else: print(hash + ": CAN NOT BE SEARCHED")

```

<p>So the result of the current code will be something like the below</p>

```0136b7453cedf600d6f6aab7900901d3            19
```

<p>I am trying to get the value of "permalink" in the JSON results and print it in the same output file. So the output must look like the below</p>

```
0136b7453cedf600d6f6aab7900901d3 19 https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296

```

How do I achieve this?

Thanks

答:
You can read it the same way you read the positive values. </p>

```<code>elif response == 1:
    positives = int(json_response.get("positives"))
    permalink = json_response.get("permalink")
    if positives >= 3:`enter code here`
        print(hash + ": MALICIOUS" + " | URL:" + permalink)
        file = open(output,"a")`enter code here`
        file.write(hash + " " + str(positives))
        file.write("\n")
        file.close()
</code>```

Body:
The output of the JSON file has multiple responses like the one seen below

"response_code":1

"scan_date":"2011-07-27 03:44:56"

"permalink":"https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296"

"verbose_msg":"Scan finished, information embedded"

"total":43

"positives":19

The below code will get the value of "positives" in the JSON output and then print it to the file.

    # DOES THE HASH EXISTS IN VT DATABASE?
    if response == 0:
        print(hash + ": UNKNOWN")
        file = open(output,"a")
        file.write(hash + " 0")
        file.write("\n")
        file.close()

    # DOES THE HASH EXISTS IN VT DATABASE?
    elif response == 1:
        positives = int(json_response.get("positives"))
        if positives >= 3:
            print(hash + ": MALICIOUS")
            file = open(output,"a")
            file.write(hash + " " + str(positives))
            file.write("\n")
            file.close()
        else:
            print(hash + ": NOT MALICIOUS")
            file = open(output,"a")
            file.write(hash + " 0")
            file.write("\n")
            file.close()
    else: print(hash + ": CAN NOT BE SEARCHED")

So the result of the current code will be something like the below

0136b7453cedf600d6f6aab7900901d3            19

I am trying to get the value of "permalink" in the JSON results and print it in the same output file. So the output must look like the below

0136b7453cedf600d6f6aab7900901d3 19 https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296

How do I achieve this?

Thanks

Body:
You can read it the same way you read the positive values.

elif response == 1:
    positives = int(json_response.get("positives"))
    permalink = json_response.get("permalink")
    if positives >= 3:`enter code here`
        print(hash + ": MALICIOUS" + " | URL:" + permalink)
        file = open(output,"a")`enter code here`
        file.write(hash + " " + str(positives))
        file.write("\n")
        file.close()


问:
how can i show a notification when an admin asiggne an order to a deliverer laravel 7?
when i store new order i want th deliverer with "deliverer_id" get notified

```<code>    public function store(Request $request)
{
    $order = Order::create([

    'deliverer_id' => $request->input('deliverer_id'),

    'product_id' => $request->input('product_id'),

    'responsible_id'=>$request->input('responsible_id'),

    'quantity'=> $request->input('quantity'),

    'client_name' => $request->input('client_name'),

    ]);

    return redirect()->route('orders.index');
}
</code>```

i want to show a notification say there is a "new order" on deliverer view

```<code><li class="nav-item btn-rotate dropdown">
                    <a class="nav-link dropdown-toggle">
                        <i class="nc-icon nc-bell-55"></i>
                        <p>
                            <span>New order</span>
                        </p>
                    </a>
                    <div class="dropdown-menu dropdown-menu-right newor">
                        <a class="dropdown-item" href="#">New order</a>
                    </div>
                </li>
</code>```

答: You can try using Laravel default notification support https://laravel.com/docs/7.x/notifications. It will allow you to attach an notification to the user that will see the deliverer view. So in the view you can get the notifications by $user->unreadNotifications and if it isn,t empty you show the notification.

Body:
when i store new order i want th deliverer with "deliverer_id" get notified

    public function store(Request $request)
{
    $order = Order::create([

    'deliverer_id' => $request->input('deliverer_id'),

    'product_id' => $request->input('product_id'),

    'responsible_id'=>$request->input('responsible_id'),

    'quantity'=> $request->input('quantity'),

    'client_name' => $request->input('client_name'),

    ]);

    return redirect()->route('orders.index');
}

i want to show a notification say there is a "new order" on deliverer view

                            New order

                        New order


答:
const res={
        AAPL: { price: 329.99 },
        AMZN: { price: 2563.05 },
        FB: { price: 239.93 },
        GOOGL: { price: 1469.12 }
}

console.log(Object.entries(res).map((entry,index)=>{
return {
  id:index+1,
  name:entry[0],
...entry[1]
  }
}));```

Title: Taking JSON values in a response and mapping them to a state object with keys?


问:
fish shell tab completion program short description - howto?
With fish shell there is (among many others) a nice feature that displays a short description of the possible commands, like that:

How can I write such a description for my own commands? Specifically I would like to do that for python console_scripts.

10x.

答:
You can add such descriptions to your Fish functions, such as this example from VirtualFish's activate sub-command:

```<code>function __vf_activate --description "Activate a virtualenv"
    […]
end
</code>```

You can see the resulting output when typing vf and then the Tab key:

Body:
You can add such descriptions to your Fish functions, such as this example from VirtualFish's activate sub-command:

function __vf_activate --description "Activate a virtualenv"
    […]
end

You can see the resulting output when typing vf and then the Tab key:


问:
Redux: How do I dispatch action in useEffect only once?
I have a calendar app where a user can upload 1 - 4 images for each calendar page.

Expected Result:
When a user uploads a image with bad quality, I have a quality warning toast that should appear once for each image.

Current Result:
Right now the action showToast within the useEffect is triggered multiple times. So e.g. when I upload a new image, delete another image, etc. everytime this quality warning is triggered again.

My Approach:
I have tried to implement a local state in order to toggle a boolean (if warning was shown once, set to false). But I could only get it to work for all images (as soon as any image has bad quality, the local state is set to false). But I need it to be image specific.

If the quality warning for the specific image has been shown, then don't show it again.

Code:

```<code>export const useShowPoorImageQualityToast = (spreadId: string): void => {
    const dispatch = useDispatch();

    const [qualityToastIsShown, setQualityToastWasShown] = useState(false); // my approach

    const poorQualityContentIds = useSelector(
        (state: AppState) =>
            spreadWithImageContentsSelector(state, spreadId).filter((contentId) => {
                const qualityInformation = productImageQualitySelector(state, contentId);

                return qualityInformation !== undefined && qualityInformation.hasPoorQuality
            }),
        shallowEqual
    );

    useEffect(() => {
        const imageQualityWarningToast: ClosableToast = {
            mode: ToastMode.CLOSABLE,
            text: locale.photoQualityWarning.toast,
            severity: ToastSeverity.WARN,
            closable: false,
        };

        if (poorQualityContentIds.length > 0 && qualityToastIsShown === false) {

            dispatch(showToast(ToastType.NONE, imageQualityWarningToast));

            setQualityToastWasShown(!qualityToastIsShown); // my approach
        }
    }, [dispatch, poorQualityContentIds, qualityToastIsShown]);
};
</code>```

答:
I have worked on this kind of problem before, but I think it's not the most optimal one.

So what I did was instead of storing just one boolean, I stored the image id or some referrence for each image and then check that boolean stored inside that image id. This way you are only setting the flag for one specific image each time and only checking for that.

So, store something like this in your local state:

```<code>{
  image1: { warningShown: true },
  image2: { warningShown: false }
}
</code>```

Body:
I have a calendar app where a user can upload 1 - 4 images for each calendar page.

Expected Result:
When a user uploads a image with bad quality, I have a quality warning toast that should appear once for each image.

Current Result:
Right now the action showToast within the useEffect is triggered multiple times. So e.g. when I upload a new image, delete another image, etc. everytime this quality warning is triggered again.

My Approach:
I have tried to implement a local state in order to toggle a boolean (if warning was shown once, set to false). But I could only get it to work for all images (as soon as any image has bad quality, the local state is set to false). But I need it to be image specific.

If the quality warning for the specific image has been shown, then don't show it again.

Code:

export const useShowPoorImageQualityToast = (spreadId: string): void => {
    const dispatch = useDispatch();

    const [qualityToastIsShown, setQualityToastWasShown] = useState(false); // my approach

    const poorQualityContentIds = useSelector(
        (state: AppState) =>
            spreadWithImageContentsSelector(state, spreadId).filter((contentId) => {
                const qualityInformation = productImageQualitySelector(state, contentId);

                return qualityInformation !== undefined && qualityInformation.hasPoorQuality
            }),
        shallowEqual
    );

    useEffect(() => {
        const imageQualityWarningToast: ClosableToast = {
            mode: ToastMode.CLOSABLE,
            text: locale.photoQualityWarning.toast,
            severity: ToastSeverity.WARN,
            closable: false,
        };

        if (poorQualityContentIds.length > 0 && qualityToastIsShown === false) {

            dispatch(showToast(ToastType.NONE, imageQualityWarningToast));

            setQualityToastWasShown(!qualityToastIsShown); // my approach
        }
    }, [dispatch, poorQualityContentIds, qualityToastIsShown]);
};

Body:
I have worked on this kind of problem before, but I think it's not the most optimal one.

So what I did was instead of storing just one boolean, I stored the image id or some referrence for each image and then check that boolean stored inside that image id. This way you are only setting the flag for one specific image each time and only checking for that.

So, store something like this in your local state:

{
  image1: { warningShown: true },
  image2: { warningShown: false }
}


问:
How to change referenced numpy arrays to a slice of itself?
Consider the following operation and slicing applied to two numpy arrays:

```<code>In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([5,6,7,8])

In [4]: a[2:] = 0

In [5]: a = a[::2]

In [6]: b[2:] = 0

In [7]: b = b[::2]

In [8]: a
Out[8]: array([1, 0])

In [9]: b
Out[9]: array([5, 0])
</code>```

I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like

```<code>In [4]: for data in [a,b] :
   ...:     data[2:] = 0
   ...:     data = data[::2]
</code>```

I understand that it does not work because the effect of data = data[::2] is to make data to point a new object, not to change the original objects. So the values of a and b are not sliced:

```<code>In [5]: a
Out[5]: array([1, 2, 0, 0])

In [6]: b
Out[6]: array([5, 6, 0, 0])
</code>```

My question is:

How to slice a numpy array referenced by a variable?

In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for.

答:
There may be some confusion over creating array objects and assigning values.

Let me illustrate:

Define two arrays:

```<code>In [5]: a=np.arange(1,5); b=np.arange(5,10)
</code>```

Make a list of those two arrays:

```<code>In [6]: alist = [a,b]
</code>```

and a generic function that returns a new array (the fact that it's a view doesn't matter):

```<code>In [7]: def foo(i):
   ...:     return i[2:]
   ...:
</code>```

The function could be applied to the array referenced by a:

```<code>In [8]: foo(a)
Out[8]: array([3, 4])
</code>```

or to each of the arrays referenced by alist:

```<code>In [9]: [foo(i) for i in alist]
Out[9]: [array([3, 4]), array([7, 8, 9])]
</code>```

those arrays could be unpacked to variables (new or old names):

```<code>In [10]: a,d = [foo(i) for i in alist]
In [11]: a
Out[11]: array([3, 4])          # the new sliced array
In [12]: b
Out[12]: array([5, 6, 7, 8, 9])    # the original array
In [13]: d
Out[13]: array([7, 8, 9])           # a slice of b
</code>```

the original arrays are still present in alist.  The fact that a has a new value does not change alist:

```<code>In [14]: alist
Out[14]: [array([1, 2, 3, 4]), array([5, 6, 7, 8, 9])]
</code>```

unpacked assignment via map does the same thing:

```<code>In [15]: d,e = map(foo, alist)
In [16]: d,e
Out[16]: (array([3, 4]), array([7, 8, 9]))
</code>```

Making a dictionary of the sliced arrays also works:

```<code>In [17]: {key: foo(value) for key, value in zip(['e','d'],alist)}
Out[17]: {'e': array([3, 4]), 'd': array([7, 8, 9])}
</code>```

Body:
Consider the following operation and slicing applied to two numpy arrays:

In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([5,6,7,8])

In [4]: a[2:] = 0

In [5]: a = a[::2]

In [6]: b[2:] = 0

In [7]: b = b[::2]

In [8]: a
Out[8]: array([1, 0])

In [9]: b
Out[9]: array([5, 0])

I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like

In [4]: for data in [a,b] :
   ...:     data[2:] = 0
   ...:     data = data[::2]

I understand that it does not work because the effect of data = data[::2] is to make data to point a new object, not to change the original objects. So the values of a and b are not sliced:

In [5]: a
Out[5]: array([1, 2, 0, 0])

In [6]: b
Out[6]: array([5, 6, 0, 0])

My question is:

How to slice a numpy array referenced by a variable?

In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for.

Body:
There may be some confusion over creating array objects and assigning values.

Let me illustrate:

Define two arrays:

In [5]: a=np.arange(1,5); b=np.arange(5,10)

Make a list of those two arrays:

In [6]: alist = [a,b]

and a generic function that returns a new array (the fact that it's a view doesn't matter):

In [7]: def foo(i):
   ...:     return i[2:]
   ...:

The function could be applied to the array referenced by a:

In [8]: foo(a)
Out[8]: array([3, 4])

or to each of the arrays referenced by alist:

In [9]: [foo(i) for i in alist]
Out[9]: [array([3, 4]), array([7, 8, 9])]

those arrays could be unpacked to variables (new or old names):

In [10]: a,d = [foo(i) for i in alist]
In [11]: a
Out[11]: array([3, 4])          # the new sliced array
In [12]: b
Out[12]: array([5, 6, 7, 8, 9])    # the original array
In [13]: d
Out[13]: array([7, 8, 9])           # a slice of b

the original arrays are still present in alist.  The fact that a has a new value does not change alist:

In [14]: alist
Out[14]: [array([1, 2, 3, 4]), array([5, 6, 7, 8, 9])]

unpacked assignment via map does the same thing:

In [15]: d,e = map(foo, alist)
In [16]: d,e
Out[16]: (array([3, 4]), array([7, 8, 9]))

Making a dictionary of the sliced arrays also works:

In [17]: {key: foo(value) for key, value in zip(['e','d'],alist)}
Out[17]: {'e': array([3, 4]), 'd': array([7, 8, 9])}


问:
How can I disable lightbox2 on mobile
Just discovered this code and implementation of lightbox2 and added the needed code to some of my webpages.
Looks very good o desktop and also on tablet but I don't like the lightbox in mobile view.
The pictures that are shown on mobile are smaller than the 'normal' responsive view that I get when not using lightbox2.

So my question is in the title: How can I disable the lightbox on mobile?
Regards Arno

答:
Unfortunately this is not possible at this time. The Lightbox script on load will attach event handlers to the target images.

To get around this, you can use different markup on mobile and show hide the content with CSS media queries.

Title: How can I disable lightbox2 on mobile