问:
Deserialize Open Street Map JSON in C#
If I have this JSON where there is a header with the tags version, generator, om3s and elements.  elements can be of type node or way and the associated JSON keys vary based on type.  I am trying to use JsonSubTypes to convert each element type to a C# class.

Example JSON:

```<code>[
  {
    "version": 0.6,
    "generator": "Overpass API 0.7.55.7 8b86ff77",
    "osm3s": {
      "timestamp_osm_base": "2019-05-21T18:03:02Z",
      "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
    },
    "elements": [
      {
        "type": "node",
        "id": 4949106384,
        "lat": 32.2686857,
        "lon": -107.738218,
        "tags": {
          "highway": "turning_circle"
        }
      },
      {
        "type": "way",
        "id": 14527404,
        "nodes": [
          142882281,
          3048075541,
          1598998260
        ],
        "tags": {
          "highway": "residential",
          "name": "West Apple Street",
          "tiger:cfcc": "A41",
          "tiger:county": "Luna, NM",
          "tiger:name_base": "Apple",
          "tiger:name_direction_prefix": "W",
          "tiger:name_type": "St",
          "tiger:reviewed": "no"
        }
      }
    ]
  }
]
</code>```

I am trying to deserialize it using:

```<code>var json = JsonConvert.DeserializeObject<OSMdata>(jsonText);
</code>```

Where OSMdata looks like:

```<code>[JsonConverter(typeof(JsonSubtypes), "type")]
[JsonSubtypes.KnownSubType(typeof(Element.Node), "node")]
[JsonSubtypes.KnownSubType(typeof(Element.Edge), "way")]

public abstract class OSMdata
{
    public float version { get; set; }
    public string generator { get; set; }
    public Osm3s osm3s { get; set; }
    public Element[] elements { get; set; }
}

public class Osm3s : OSMdata
{
    public DateTime timestamp_osm_base { get; set; }
    public string copyright { get; set; }
}

public class Element : OSMdata
{
    public class Node : Element
    {
        public string type { get; } = "node";
        public long id { get; set; }
        public float lat { get; set; }
        public float lon { get; set; }
        public NodeTags tags { get; set; }
    }

    public class NodeTags : Node
    {
        public string highway { get; set; }
        public string _ref { get; set; }
    }

    public class Edge : Element
    {
        public string type { get; } = "way";
        public long id { get; set; }
        public long[] nodes { get; set; }
        public EdgeTags tags { get; set; }
    }

    public class EdgeTags : Edge
    {
        public string highway { get; set; }
        public string name { get; set; }
        public string cfcc { get; set; }
        public string county { get; set; }
        public string oneway { get; set; }
    }
}
</code>```

Which returns:

```<code>Unhandled Exception: System.ArgumentNullException: Value cannot be null.
   at System.RuntimeType.MakeGenericType(Type[] instantiation)
   at JsonSubTypes.JsonSubtypes.CreateCompatibleList(Type targetContainerType, Type elementType)
   at JsonSubTypes.JsonSubtypes.ReadArray(JsonReader reader, Type targetType, JsonSerializer serializer)
   at JsonSubTypes.JsonSubtypes.ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at newapp.Program.Main(String[] args) in C:\Users\RDCRLDDH\source\repos\newapp\newapp\Program.cs:line 23
</code>```

While I don't understand this error and am looking for a solution, here are a few questions I would like clarity on:

Questions

Am I properly constructing the class OSMdata?  I think I am following the examples correctly, but am not sure if I am properly assigning the classes Node and Edge to the parent class OSMdata.

How will the deserializer know to assign the tag "tiger:cfcc" to the Cfcc property in EdgeTags?

答:
Declare your classes as follows:

    // no longer abstract
    public class OSMdata
    {
        public float version { get; set; }
        public string generator { get; set; }
        public Osm3s osm3s { get; set; }

        // for arrays or collection this line must be present here
        [JsonConverter(typeof(JsonSubtypes), "type")]
        public Element[] elements { get; set; }
    }

    // no need to inherits from OSMData
    public class Osm3s
    {
        public DateTime timestamp_osm_base { get; set; }
        public string copyright { get; set; }
    }

    [JsonConverter(typeof(JsonSubtypes), "type")]
    [JsonSubtypes.KnownSubType(typeof(Node), "node")]
    [JsonSubtypes.KnownSubType(typeof(Edge), "way")]
    public abstract class Element : OSMdata
    {
        public abstract string type { get; }
    }

    public class Node : Element
    {
        public override string type { get; } = "node";
        public long id { get; set; }
        public float lat { get; set; }
        public float lon { get; set; }
        public NodeTags tags { get; set; }
    }

    public class NodeTags
    {
        public string highway { get; set; }
        public string _ref { get; set; }
    }

    public class Edge : Element
    {
        public override string type { get; } = "way";
        public long id { get; set; }
        public long[] nodes { get; set; }
        public EdgeTags tags { get; set; }
    }

    public class EdgeTags
    {
        public string highway { get; set; }
        public string name { get; set; }
        public string cfcc { get; set; }
        public string county { get; set; }
        public string oneway { get; set; }
    }
```

<p>and deserialize with:</p>

<pre class="lang-cs prettyprint-override"><code>var json = JsonConvert.DeserializeObject<OSMdata>(jsonText);
</code>```

see running sample: https://dotnetfiddle.net/pdJ0ab

Title: Deserialize Open Street Map JSON in C#

Body:
If I have this JSON where there is a header with the tags version, generator, om3s and elements.  elements can be of type node or way and the associated JSON keys vary based on type.  I am trying to use JsonSubTypes to convert each element type to a C# class.

Example JSON:

[
  {
    "version": 0.6,
    "generator": "Overpass API 0.7.55.7 8b86ff77",
    "osm3s": {
      "timestamp_osm_base": "2019-05-21T18:03:02Z",
      "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
    },
    "elements": [
      {
        "type": "node",
        "id": 4949106384,
        "lat": 32.2686857,
        "lon": -107.738218,
        "tags": {
          "highway": "turning_circle"
        }
      },
      {
        "type": "way",
        "id": 14527404,
        "nodes": [
          142882281,
          3048075541,
          1598998260
        ],
        "tags": {
          "highway": "residential",
          "name": "West Apple Street",
          "tiger:cfcc": "A41",
          "tiger:county": "Luna, NM",
          "tiger:name_base": "Apple",
          "tiger:name_direction_prefix": "W",
          "tiger:name_type": "St",
          "tiger:reviewed": "no"
        }
      }
    ]
  }
]

I am trying to deserialize it using:

var json = JsonConvert.DeserializeObject<OSMdata>(jsonText);

Where OSMdata looks like:

[JsonConverter(typeof(JsonSubtypes), "type")]
[JsonSubtypes.KnownSubType(typeof(Element.Node), "node")]
[JsonSubtypes.KnownSubType(typeof(Element.Edge), "way")]

public abstract class OSMdata
{
    public float version { get; set; }
    public string generator { get; set; }
    public Osm3s osm3s { get; set; }
    public Element[] elements { get; set; }
}

public class Osm3s : OSMdata
{
    public DateTime timestamp_osm_base { get; set; }
    public string copyright { get; set; }
}

public class Element : OSMdata
{
    public class Node : Element
    {
        public string type { get; } = "node";
        public long id { get; set; }
        public float lat { get; set; }
        public float lon { get; set; }
        public NodeTags tags { get; set; }
    }

    public class NodeTags : Node
    {
        public string highway { get; set; }
        public string _ref { get; set; }
    }

    public class Edge : Element
    {
        public string type { get; } = "way";
        public long id { get; set; }
        public long[] nodes { get; set; }
        public EdgeTags tags { get; set; }
    }

    public class EdgeTags : Edge
    {
        public string highway { get; set; }
        public string name { get; set; }
        public string cfcc { get; set; }
        public string county { get; set; }
        public string oneway { get; set; }
    }
}

Which returns:

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
   at System.RuntimeType.MakeGenericType(Type[] instantiation)
   at JsonSubTypes.JsonSubtypes.CreateCompatibleList(Type targetContainerType, Type elementType)
   at JsonSubTypes.JsonSubtypes.ReadArray(JsonReader reader, Type targetType, JsonSerializer serializer)
   at JsonSubTypes.JsonSubtypes.ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at newapp.Program.Main(String[] args) in C:\Users\RDCRLDDH\source\repos\newapp\newapp\Program.cs:line 23

While I don't understand this error and am looking for a solution, here are a few questions I would like clarity on:

Questions

Am I properly constructing the class OSMdata?  I think I am following the examples correctly, but am not sure if I am properly assigning the classes Node and Edge to the parent class OSMdata.

How will the deserializer know to assign the tag "tiger:cfcc" to the Cfcc property in EdgeTags?

Body:
Declare your classes as follows:

    // no longer abstract
    public class OSMdata
    {
        public float version { get; set; }
        public string generator { get; set; }
        public Osm3s osm3s { get; set; }

        // for arrays or collection this line must be present here
        [JsonConverter(typeof(JsonSubtypes), "type")]
        public Element[] elements { get; set; }
    }

    // no need to inherits from OSMData
    public class Osm3s
    {
        public DateTime timestamp_osm_base { get; set; }
        public string copyright { get; set; }
    }

    [JsonConverter(typeof(JsonSubtypes), "type")]
    [JsonSubtypes.KnownSubType(typeof(Node), "node")]
    [JsonSubtypes.KnownSubType(typeof(Edge), "way")]
    public abstract class Element : OSMdata
    {
        public abstract string type { get; }
    }

    public class Node : Element
    {
        public override string type { get; } = "node";
        public long id { get; set; }
        public float lat { get; set; }
        public float lon { get; set; }
        public NodeTags tags { get; set; }
    }

    public class NodeTags
    {
        public string highway { get; set; }
        public string _ref { get; set; }
    }

    public class Edge : Element
    {
        public override string type { get; } = "way";
        public long id { get; set; }
        public long[] nodes { get; set; }
        public EdgeTags tags { get; set; }
    }

    public class EdgeTags
    {
        public string highway { get; set; }
        public string name { get; set; }
        public string cfcc { get; set; }
        public string county { get; set; }
        public string oneway { get; set; }
    }

and deserialize with:

var json = JsonConvert.DeserializeObject<OSMdata>(jsonText);

see running sample: https://dotnetfiddle.net/pdJ0ab


来源: stackexchange

问:
Create custom list data structure with "toList" function
I want to create my own list data structure called Nodes. Then I will use my ListConverter class, which contains the 'toList' function, and create an instance of it.

data Nodes a = Empty
             | Node a (Nodes a)

class ListConverter a where
    toList :: a -> [Integer]

instance (Integral a) => ListConverter (Nodes a) where
    toList Empty = []
    toList (Node x Empty) = [x]
    toList (Node x y) = x : toList y
```

<p>GHCi tells me, that the expected type is 'Integer' but is currently 'a'. Im very confused, because in the instance I give a type for a (Integral). Here's the error message:</p>

```error:
    * Couldn't match expected type `Integer' with actual type `a'
      `a' is a rigid type variable bound by
        the instance declaration
        at main.hs:7:10-48
    * In the expression: x
      In the expression: [x]
      In an equation for `toList': toList (Node x Empty) = [x]
    * Relevant bindings include
        x :: a (bound at main.hs:9:18)
        toList :: Nodes a -> [Integer] (bound at main.hs:8:5)
  |
9 |     toList (Node x Empty) = [x]
  |                              ^
```

答:
The problem with this instance is very simply stated. You have given the signature:

```<code>toList :: a -> [Integer]
</code>```

But your attempted instance actually has type Nodes a -> [a]. This doesn't work unless a is the Integer type - yet you've claimed it works for all Integral a. This includes other types such as Int.

One solution is just to restrict your instance:

```<code>instance ListConverter (Nodes Integer) where...
</code>```

This will work - but doesn't in my opinion really respect the spirit of what you probably intended the class for.

The best solution I think is to recognise that both lists and your Nodes type are paramaterised by another type, and define the class in such a way as to do the conversion over a common base class. That sounds more complicated than it is, I just mean:

```<code>class ListConverter l where
    toList :: l a -> [a]
</code>```

Then you can write an instance ListConverter Nodes where..., and just copy your existing toList definition. (Whose middle line, I will point out in passing, is redundant.)

ContentLicense: CC BY-SA 4.0

Body:
I want to create my own list data structure called Nodes. Then I will use my ListConverter class, which contains the 'toList' function, and create an instance of it.

data Nodes a = Empty
             | Node a (Nodes a)

class ListConverter a where
    toList :: a -> [Integer]

instance (Integral a) => ListConverter (Nodes a) where
    toList Empty = []
    toList (Node x Empty) = [x]
    toList (Node x y) = x : toList y

GHCi tells me, that the expected type is 'Integer' but is currently 'a'. Im very confused, because in the instance I give a type for a (Integral). Here's the error message:

error:
    * Couldn't match expected type `Integer' with actual type `a'
      `a' is a rigid type variable bound by
        the instance declaration
        at main.hs:7:10-48
    * In the expression: x
      In the expression: [x]
      In an equation for `toList': toList (Node x Empty) = [x]
    * Relevant bindings include
        x :: a (bound at main.hs:9:18)
        toList :: Nodes a -> [Integer] (bound at main.hs:8:5)
  |
9 |     toList (Node x Empty) = [x]
  |                              ^

Body:
The problem with this instance is very simply stated. You have given the signature:

toList :: a -> [Integer]

But your attempted instance actually has type Nodes a -> [a]. This doesn't work unless a is the Integer type - yet you've claimed it works for all Integral a. This includes other types such as Int.

One solution is just to restrict your instance:

instance ListConverter (Nodes Integer) where...

This will work - but doesn't in my opinion really respect the spirit of what you probably intended the class for.

The best solution I think is to recognise that both lists and your Nodes type are paramaterised by another type, and define the class in such a way as to do the conversion over a common base class. That sounds more complicated than it is, I just mean:

class ListConverter l where
    toList :: l a -> [a]

Then you can write an instance ListConverter Nodes where..., and just copy your existing toList definition. (Whose middle line, I will point out in passing, is redundant.)


问:
Use default value if item not found in array
So I've got my code trying to select an object from an array of objects, and if the object isn't found, I want to create my defaults.

```<code>lead_time = lead_times.select{|d| LeadTimeProfile.new unless d.day_of_week == day }
</code>```

however, from what I can tell, this is not returning me the devault LeadTimeProfile.

is there a way of doing this? Or have I got it right?

答:
Passing a lambda as a parameter also works.</p>

```<code>lead_time = lead_times.find(lambda { LeadTimeProfile.new } ){ |d| d.day_of_week == day }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I've got my code trying to select an object from an array of objects, and if the object isn't found, I want to create my defaults.

lead_time = lead_times.select{|d| LeadTimeProfile.new unless d.day_of_week == day }

however, from what I can tell, this is not returning me the devault LeadTimeProfile.

is there a way of doing this? Or have I got it right?

Body:
Passing a lambda as a parameter also works.

lead_time = lead_times.find(lambda { LeadTimeProfile.new } ){ |d| d.day_of_week == day }


问:
Trouble iterating array to average groups of 3 numbers and compare to other groups of 3 numbers
I have an array of 12 numbers. I am trying to create a loop that takes the first 3 and averages them. Then it compares if this is less than the next three and the three after that and so on.

I have tried elif but the there are too many conditions to state

```<code>import numpy as np
import math
array = [1,2,3,4,5,6,7,8,9,10,11,12]
for k in range(len(array)):
    target1 = array[k]
    target2 = array [k-1]
    if k<11:
        target3 = array[k+1]
    else:
        target3 = array[0]
</code>```

this is how i prevent IndexError: index 12 is out of bounds for axis 0 with size 12

```<code>    targets = [target1, target2, target3]
    target = np.mean(targets)
</code>```

I want to compare targets to the average of (k+2,k+3,k+4) and (k+5,k+6,k+7) and (k+8,k+9,k+10)

```<code>    sigma = 1
    if ((target-avg)/(math.sqrt(target))>= sigma:
        print(array[k])
</code>```

I cannot figure out how to get values for avg based off the sum of the other three zones of the array I am comparing to

I was thinking of doing this

```<code>    if k < 8:
            range1_target1 = array[k+2]
            range1_target2 = array[k+3]
            range1_target3 = array[k+4]
</code>```

but there were too many options for conditions to code efficiently

答:
First, define the average function, a function that calculates the average of the values in an iterable object:

```<code>def average(iterable):
    sum = 0
    for number in iterable:
        sum += number
    return sum / len(iterable)
</code>```

This function is pretty simple. It defines a variable called "sum" and sets its initial value to 0. It then loops through the parameter "iterable", adds each and every element's value in the iterable parameter to sum. It then divides the sum of all the values (the sum variable) by the length of iterable. It returns the result as a float.

An example: The function is called. The iterable argument is assigned to the list [25, 75, -100, 20]. The sum variable is initated to 0. Through looping on iterable, it adds 25, 75, -100, and 20 to sum. Sum ends up being 20. The length of iterable, as per Python's len() method, is 4. 20 / 4 = 5.0 (A float because one slash in Python always represents true division, and returns a floating point even if the result remains the same after being casted into an int. Use two slashes for integer division), and therefore the method returns 5.0.

Back to your program. In my opinion, you should get all the averages before comparing them. Define the averages list as follows.

```<code>averages = []
</code>```

Very simple. Sets the global variable "average" to an empty list.

Because you want the averages of every three numbers, you should make the iterated range's step 3, not 1. This is done as follows.

```<code>for counter in range(0, len(array), 3):
</code>```

The range constructor takes in a maximum of three parameters (start, stop, step). When it takes in three parameters, it starts counting at "start", counting by "step" and stopping at "stop." It records every number counted in an immutable iterable object. When it takes in two parameters, "step" is set to 1. When it takes in one parameter, "start" is set to 0, "stop" is set to the parameter, and "step" is set to 1.

You then want to append all the averages to the list "averages". It is done as follows.

```<code>    averages.append(average(array[counter: counter+3: 1]))
</code>```

The "append" method of a list adds the parameter it takes in to the end of the list. The [counter: counter+3: 1] is a slice index. The slice constructor is similar to range except it can be done with this format: start:stop[:step] and isn't iterable, but rather takes multiple elements from an iterable object and these indexes are determined by the parameters. The average of the values are recorded in the averages array.

You have now got all the averages. No need to worry about IndexError because slices ignore any out-of-range indexes without throwing Exceptions.

Next, we want to compare the averages to each other. Here's the code:

```<code>for i in range(0, len(averages)):
    for j in range(0, len(averages)):
        if i == j:
            #Avoid duplicate averages.
            continue
        if averages[i] < averages[j]:
            #averages[i] < averages[j].
            #Do something
            continue
        elif averages[i] == averages[j]:
            #averages[i] == averages[j].
            #Do something
            continue
        else:
            #averages[i] > averages[j]. Only possibility left.
            #Do something
            continue
</code>```

That's how it's done. We iterate on the indexes on averages instead of the averages itself to test for duplicates. If the indexes equal each other, then we continue on in the loop because we don't want to deal with them. Otherwise, we compare averages[i] to averages[j] and execute python statements based on the condition. You didn't specify what you wanted to do so I just handled them like duplicates, all though you shouldn't. The rest of the code is self explanatory.

Now, for the full code. No commentary:

```<code>def average(iterable):
    sum = 0
    for number in iterable:
        sum += number
    return sum / len(iterable)

#Same old array that you mentioned in your question
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

averages = []

for counter in range(0, len(array), 3):
    averages.append(average(array[counter: counter+3: 1]))

for i in range(0, len(averages)):
    for j in range(0, len(averages)):
        if i == j:
            #Avoid duplicate averages.
            continue
        if averages[i] < averages[j]:
            #averages[i] < averages[j].
            #Do something
            continue
        elif averages[i] == averages[j]:
            #averages[i] == averages[j].
            #Do something
            continue
        else:
            #averages[i] > averages[j]. Only possibility left.
            #Do something
            continue
</code>```

I tested my code by printing the result between two different averages with this code.

```<code>def average(iterable):
    sum = 0
    for number in iterable:
        sum += number
    return sum / len(iterable)

#Same old array that you mentioned in your question
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

averages = []

for counter in range(0, len(array), 3):
    averages.append(average(array[counter: counter+3: 1]))

for i in range(0, len(averages)):
    for j in range(0, len(averages)):
        if i == j:
            #Avoid duplicate averages.
            continue
        if averages[i] < averages[j]:
            #averages[i] < averages[j].
            #Do something
            print("averages[{}] < averages[{}]".format(i, j))
        elif averages[i] == averages[j]:
            #averages[i] == averages[j].
            #Do something
            print("averages[{}] = averages[{}]".format(i, j))
        else:
            #averages[i] > averages[j]. Only possibility left.
            #Do something
            print("averages[{}] > averages[{}]".format(i, j))

print("Averages: ", averages)

</code>```

And this was the output. Run the testing code above and you'll get the same result.

```<code>averages[0] < averages[1]
averages[0] < averages[2]
averages[0] < averages[3]
averages[1] > averages[0]
averages[1] < averages[2]
averages[1] < averages[3]
averages[2] > averages[0]
averages[2] > averages[1]
averages[2] < averages[3]
averages[3] > averages[0]
averages[3] > averages[1]
averages[3] > averages[2]
Averages:  [2.0, 5.0, 8.0, 11.0]
</code>```

Note: I coded this in Python 3.7

Body:
I have an array of 12 numbers. I am trying to create a loop that takes the first 3 and averages them. Then it compares if this is less than the next three and the three after that and so on.

I have tried elif but the there are too many conditions to state

import numpy as np
import math
array = [1,2,3,4,5,6,7,8,9,10,11,12]
for k in range(len(array)):
    target1 = array[k]
    target2 = array [k-1]
    if k<11:
        target3 = array[k+1]
    else:
        target3 = array[0]

this is how i prevent IndexError: index 12 is out of bounds for axis 0 with size 12

    targets = [target1, target2, target3]
    target = np.mean(targets)

I want to compare targets to the average of (k+2,k+3,k+4) and (k+5,k+6,k+7) and (k+8,k+9,k+10)

    sigma = 1
    if ((target-avg)/(math.sqrt(target))>= sigma:
        print(array[k])

I cannot figure out how to get values for avg based off the sum of the other three zones of the array I am comparing to

I was thinking of doing this

    if k < 8:
            range1_target1 = array[k+2]
            range1_target2 = array[k+3]
            range1_target3 = array[k+4]

but there were too many options for conditions to code efficiently

Body:
First, define the average function, a function that calculates the average of the values in an iterable object:

def average(iterable):
    sum = 0
    for number in iterable:
        sum += number
    return sum / len(iterable)

This function is pretty simple. It defines a variable called "sum" and sets its initial value to 0. It then loops through the parameter "iterable", adds each and every element's value in the iterable parameter to sum. It then divides the sum of all the values (the sum variable) by the length of iterable. It returns the result as a float.

An example: The function is called. The iterable argument is assigned to the list [25, 75, -100, 20]. The sum variable is initated to 0. Through looping on iterable, it adds 25, 75, -100, and 20 to sum. Sum ends up being 20. The length of iterable, as per Python's len() method, is 4. 20 / 4 = 5.0 (A float because one slash in Python always represents true division, and returns a floating point even if the result remains the same after being casted into an int. Use two slashes for integer division), and therefore the method returns 5.0.

Back to your program. In my opinion, you should get all the averages before comparing them. Define the averages list as follows.

averages = []

Very simple. Sets the global variable "average" to an empty list.

Because you want the averages of every three numbers, you should make the iterated range's step 3, not 1. This is done as follows.

for counter in range(0, len(array), 3):

The range constructor takes in a maximum of three parameters (start, stop, step). When it takes in three parameters, it starts counting at "start", counting by "step" and stopping at "stop." It records every number counted in an immutable iterable object. When it takes in two parameters, "step" is set to 1. When it takes in one parameter, "start" is set to 0, "stop" is set to the parameter, and "step" is set to 1.

You then want to append all the averages to the list "averages". It is done as follows.

    averages.append(average(array[counter: counter+3: 1]))

The "append" method of a list adds the parameter it takes in to the end of the list. The [counter: counter+3: 1] is a slice index. The slice constructor is similar to range except it can be done with this format: start:stop[:step] and isn't iterable, but rather takes multiple elements from an iterable object and these indexes are determined by the parameters. The average of the values are recorded in the averages array.

You have now got all the averages. No need to worry about IndexError because slices ignore any out-of-range indexes without throwing Exceptions.

Next, we want to compare the averages to each other. Here's the code:

for i in range(0, len(averages)):
    for j in range(0, len(averages)):
        if i == j:
            #Avoid duplicate averages.
            continue
        if averages[i] < averages[j]:
            #averages[i] < averages[j].
            #Do something
            continue
        elif averages[i] == averages[j]:
            #averages[i] == averages[j].
            #Do something
            continue
        else:
            #averages[i] > averages[j]. Only possibility left.
            #Do something
            continue

That's how it's done. We iterate on the indexes on averages instead of the averages itself to test for duplicates. If the indexes equal each other, then we continue on in the loop because we don't want to deal with them. Otherwise, we compare averages[i] to averages[j] and execute python statements based on the condition. You didn't specify what you wanted to do so I just handled them like duplicates, all though you shouldn't. The rest of the code is self explanatory.

Now, for the full code. No commentary:

def average(iterable):
    sum = 0
    for number in iterable:
        sum += number
    return sum / len(iterable)

#Same old array that you mentioned in your question
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

averages = []

for counter in range(0, len(array), 3):
    averages.append(average(array[counter: counter+3: 1]))

for i in range(0, len(averages)):
    for j in range(0, len(averages)):
        if i == j:
            #Avoid duplicate averages.
            continue
        if averages[i] < averages[j]:
            #averages[i] < averages[j].
            #Do something
            continue
        elif averages[i] == averages[j]:
            #averages[i] == averages[j].
            #Do something
            continue
        else:
            #averages[i] > averages[j]. Only possibility left.
            #Do something
            continue

I tested my code by printing the result between two different averages with this code.

def average(iterable):
    sum = 0
    for number in iterable:
        sum += number
    return sum / len(iterable)

#Same old array that you mentioned in your question
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

averages = []

for counter in range(0, len(array), 3):
    averages.append(average(array[counter: counter+3: 1]))

for i in range(0, len(averages)):
    for j in range(0, len(averages)):
        if i == j:
            #Avoid duplicate averages.
            continue
        if averages[i] < averages[j]:
            #averages[i] < averages[j].
            #Do something
            print("averages[{}] < averages[{}]".format(i, j))
        elif averages[i] == averages[j]:
            #averages[i] == averages[j].
            #Do something
            print("averages[{}] = averages[{}]".format(i, j))
        else:
            #averages[i] > averages[j]. Only possibility left.
            #Do something
            print("averages[{}] > averages[{}]".format(i, j))

print("Averages: ", averages)

And this was the output. Run the testing code above and you'll get the same result.

averages[0] < averages[1]
averages[0] < averages[2]
averages[0] < averages[3]
averages[1] > averages[0]
averages[1] < averages[2]
averages[1] < averages[3]
averages[2] > averages[0]
averages[2] > averages[1]
averages[2] < averages[3]
averages[3] > averages[0]
averages[3] > averages[1]
averages[3] > averages[2]
Averages:  [2.0, 5.0, 8.0, 11.0]

Note: I coded this in Python 3.7


问:
How to register Service Factory Pattern using base interface with Castle Windsor
I am running into an issue and i can't figure out how to solve for it. I basically have a factory pattern set up as such:

This is my base interface

```<code>public interface IReportedIssueManager
{
    Task<BaseManagerResponse> ManageRequest(ReportedIssueRequest request);
}
</code>```

And then I have a factory class which will handle which service to return based on a certain type (createReportedXIssueManager, or createReportedYIssueManager, or createReportedZIssueManager). In my controller I would create an instance of this class and call this method and pass through a type:

```<code>public class ReportedIssueFactory : IReportedIssueFactory
    {
        private readonly ICreateReportedXIssueManager createReportedXIssueManager;
        private readonly ICreateReportedYIssueManager createReportedYIssueManager;
        private readonly ICreateReportedZIssueManager createReportedZIssueManager;

        public ReportedIssueFactory(
            ICreateReportedXIssueManager createReportedXIssueManager,
            ICreateReportedYIssueManager createReportedYIssueManager,
            ICreateReportedZIssueManager createReportedZIssueManager)
        {
            this.createReportedXIssueManager = createReportedXIssueManager;
            this.createReportedYIssueManager= createReportedYIssueManager;
            this.createReportedZIssueManager= createReportedZIssueManager;
        }

        public async Task<IReportedIssueManager> ReportIssue(int issueTypeId)
        {
            var issueType = (IssueType)issueTypeId;
            switch(issueType)
            {
                case IssueType.Listing:
                    return createReportedXIssueManager;
                case IssueType.Post:
                    return createReportedYIssueManager;
                case IssueType.User:
                    return createReportedZIssueManager;
                default:
                    throw new ValidationException(ReportedIssuesServiceResources.UnknownIssueType);
            }
        }
    }
</code>```

and each of those services are set up as such:

```<code>public interface ICreateReportedXIssueManager : IReportedIssueManager
    {
        Task<BaseManagerResponse> ManageRequest(CreateReportedXIssueRequest request);
    }

and

public interface ICreateReportedYIssueManager : IReportedIssueManager
    {
        Task<BaseManagerResponse> ManageRequest(CreateReportedYIssueRequest request);
    }

and

public interface ICreateReportedZIssueManager : IReportedIssueManager
    {
        Task<BaseManagerResponse> ManageRequest(CreateReportedZIssueRequest request);
    }
</code>```

and finally in my controller i would call something like this:

```<code>var manager = await _reportedIssueFactory.ReportIssue(IssueTypeId);
var response = await manager.ManageRequest(request);
</code>```

My problem is that since this is a factory pattern, i think Windsor expects a service of the same name as the base interface?

I get the following error:

No component for supporting the service System.Threading.Tasks.Task`1[[.....ReportedIssues.IReportedIssueManager]]

Does anyone know how to properly register to Windsor in this case? Any help greatly appreciated, thanks!

答:
Based on the error message, you're trying to inject Task<IReportedIssueManager> instead of your factory. That might be all you need to know.

You also don't need to have a "base interface" and then another interface for each implementation. The point of the one interface is that it can have multiple implementations. If we have multiple implementations of the one interface, then declaring inherited interfaces, one per implementation, is redundant.

In other words, whatever your factory returns will be an implementation of IReportedIssueManager cast as IReportedIssueManager. Downstream code won't know whether it also implements ICreateReportedXIssueManager, ICreateReportedYIssueManager, or ICreateReportedZIssueManager. There might be no reason at all for those interfaces to exist. Even if there is a reason, it's not relevant here if the caller expects and receives IReportedIssueManager.

Windsor provides a way to create a factory. It's not much more concise, but it does result in resolving everything from the container each time it's created.

First, regardless of how you implement the factory there's no reason for it to be asynchronous. It's just creating an object. Async is for longer-running I/O processes where the thread can be freed up to do something else while some response is pending. Here's a synchronous interface:

```<code>public interface IReportedIssueFactory
{
    // I used the enum here, but you could use the int instead.
    IReportedIssueManager CreateIssueManager(IssueType issueType);
}
</code>```

In your dependency registration, add the TypedFactoryFacility to your container:

```<code>container.AddFacility<TypedFactoryFacility>();
</code>```

Then register all of the implementations of IReportedIssueManager, giving them names (which will be important later.) Since the point is that they all implement IReportedIssueManager, for the purpose of this factory it doesn't matter if those classes implement other interfaces. Register them according to their concrete types.

For this example I'm using the names of types to name the dependencies just because it avoids adding a "magic string" constant. The actual names can be whatever you choose, but they're not important except that you use them elsewhere.

```<code>container.Register(
    Component.For<IReportedIssueManager, CreateReportedXIssueManager>()
        .Named(typeof(CreateReportedXIssueManager).FullName),
    Component.For<IReportedIssueManager, CreateReportedYIssueManager>()
        .Named(typeof(CreateReportedYIssueManager).FullName),
    Component.For<IReportedIssueManager, CreateReportedZIssueManager>()
        .Named(typeof(CreateReportedZIssueManager).FullName)
);
</code>```

Next, create a class which will take an input (in this case the issueTypeId) and return the name of the correct dependency:

```<code>public class IssueManagerSelector : DefaultTypedFactoryComponentSelector
{

    protected override string GetComponentName(MethodInfo method, object[] arguments)
    {
        var issueType = (IssueType)arguments[0];
        switch (issueType)
        {
            case IssueType.Listing:
                {
                    return typeof(CreateReportedXIssueManager).FullName;
                }
            case IssueType.Post:
                {
                    return typeof(CreateReportedYIssueManager).FullName;
                }
            case IssueType.User:
                {
                    return typeof(CreateReportedZIssueManager).FullName;
                }
            default:
                // So I didn't have to create an exception type as I tested.
                throw new Exception("Unknown type");
        }
    }
}
</code>```

Finally, register the following with your container:

```<code>container.Register(Component.For<IReportedIssueFactory>()
    .AsFactory(new IssueManagerSelector()));
</code>```

You don't need to actually create an implementation of IReportedIssueFactory. You can just inject the interface and Windsor supplies the implementation.

It will do the following:
- When you call CreateIssueManager it will pass your IssueType argument to the GetComponentName method of IssueManagerSelector.
- That method will select a component name and return it.
- The factory will then resolve the component with that name and return it.

The factory works by convention. Windsor assumes that a factory interface method that returns something is the "create" method. That's why we didn't need to give it a particular name.

Here's a unit test to ensure that it works as expected:

```<code>[TestMethod]
public void WindsorFactoryTest()
{
    var container = new WindsorContainer();
    container.AddFacility<TypedFactoryFacility>();
    container.Register(
        Component.For<IReportedIssueManager, CreateReportedXIssueManager>()
            .Named(typeof(CreateReportedXIssueManager).FullName),
        Component.For<IReportedIssueManager, CreateReportedYIssueManager>()
            .Named(typeof(CreateReportedYIssueManager).FullName),
        Component.For<IReportedIssueManager, CreateReportedZIssueManager>()
            .Named(typeof(CreateReportedZIssueManager).FullName)
    );
    container.Register(Component.For<IReportedIssueFactory>()
        .AsFactory(new IssueManagerSelector()));

    var factory = container.Resolve<IReportedIssueFactory>();
    Assert.IsInstanceOfType(factory.CreateIssueManager(IssueType.Listing), typeof(CreateReportedXIssueManager));
    Assert.IsInstanceOfType(factory.CreateIssueManager(IssueType.Post), typeof(CreateReportedYIssueManager));
    Assert.IsInstanceOfType(factory.CreateIssueManager(IssueType.User), typeof(CreateReportedZIssueManager));

}
</code>```

Finally, here is Windsor's documentation.

Body:
I am running into an issue and i can't figure out how to solve for it. I basically have a factory pattern set up as such:

This is my base interface

public interface IReportedIssueManager
{
    Task<BaseManagerResponse> ManageRequest(ReportedIssueRequest request);
}

And then I have a factory class which will handle which service to return based on a certain type (createReportedXIssueManager, or createReportedYIssueManager, or createReportedZIssueManager). In my controller I would create an instance of this class and call this method and pass through a type:

public class ReportedIssueFactory : IReportedIssueFactory
    {
        private readonly ICreateReportedXIssueManager createReportedXIssueManager;
        private readonly ICreateReportedYIssueManager createReportedYIssueManager;
        private readonly ICreateReportedZIssueManager createReportedZIssueManager;

        public ReportedIssueFactory(
            ICreateReportedXIssueManager createReportedXIssueManager,
            ICreateReportedYIssueManager createReportedYIssueManager,
            ICreateReportedZIssueManager createReportedZIssueManager)
        {
            this.createReportedXIssueManager = createReportedXIssueManager;
            this.createReportedYIssueManager= createReportedYIssueManager;
            this.createReportedZIssueManager= createReportedZIssueManager;
        }

        public async Task<IReportedIssueManager> ReportIssue(int issueTypeId)
        {
            var issueType = (IssueType)issueTypeId;
            switch(issueType)
            {
                case IssueType.Listing:
                    return createReportedXIssueManager;
                case IssueType.Post:
                    return createReportedYIssueManager;
                case IssueType.User:
                    return createReportedZIssueManager;
                default:
                    throw new ValidationException(ReportedIssuesServiceResources.UnknownIssueType);
            }
        }
    }

and each of those services are set up as such:

public interface ICreateReportedXIssueManager : IReportedIssueManager
    {
        Task<BaseManagerResponse> ManageRequest(CreateReportedXIssueRequest request);
    }

and

public interface ICreateReportedYIssueManager : IReportedIssueManager
    {
        Task<BaseManagerResponse> ManageRequest(CreateReportedYIssueRequest request);
    }

and

public interface ICreateReportedZIssueManager : IReportedIssueManager
    {
        Task<BaseManagerResponse> ManageRequest(CreateReportedZIssueRequest request);
    }

and finally in my controller i would call something like this:

var manager = await _reportedIssueFactory.ReportIssue(IssueTypeId);
var response = await manager.ManageRequest(request);

My problem is that since this is a factory pattern, i think Windsor expects a service of the same name as the base interface?

I get the following error:

No component for supporting the service System.Threading.Tasks.Task`1[[.....ReportedIssues.IReportedIssueManager]]

Does anyone know how to properly register to Windsor in this case? Any help greatly appreciated, thanks!

Body:
Based on the error message, you're trying to inject Task<IReportedIssueManager> instead of your factory. That might be all you need to know.

You also don't need to have a "base interface" and then another interface for each implementation. The point of the one interface is that it can have multiple implementations. If we have multiple implementations of the one interface, then declaring inherited interfaces, one per implementation, is redundant.

In other words, whatever your factory returns will be an implementation of IReportedIssueManager cast as IReportedIssueManager. Downstream code won't know whether it also implements ICreateReportedXIssueManager, ICreateReportedYIssueManager, or ICreateReportedZIssueManager. There might be no reason at all for those interfaces to exist. Even if there is a reason, it's not relevant here if the caller expects and receives IReportedIssueManager.

Windsor provides a way to create a factory. It's not much more concise, but it does result in resolving everything from the container each time it's created.

First, regardless of how you implement the factory there's no reason for it to be asynchronous. It's just creating an object. Async is for longer-running I/O processes where the thread can be freed up to do something else while some response is pending. Here's a synchronous interface:

public interface IReportedIssueFactory
{
    // I used the enum here, but you could use the int instead.
    IReportedIssueManager CreateIssueManager(IssueType issueType);
}

In your dependency registration, add the TypedFactoryFacility to your container:

container.AddFacility<TypedFactoryFacility>();

Then register all of the implementations of IReportedIssueManager, giving them names (which will be important later.) Since the point is that they all implement IReportedIssueManager, for the purpose of this factory it doesn't matter if those classes implement other interfaces. Register them according to their concrete types.

For this example I'm using the names of types to name the dependencies just because it avoids adding a "magic string" constant. The actual names can be whatever you choose, but they're not important except that you use them elsewhere.

container.Register(
    Component.For<IReportedIssueManager, CreateReportedXIssueManager>()
        .Named(typeof(CreateReportedXIssueManager).FullName),
    Component.For<IReportedIssueManager, CreateReportedYIssueManager>()
        .Named(typeof(CreateReportedYIssueManager).FullName),
    Component.For<IReportedIssueManager, CreateReportedZIssueManager>()
        .Named(typeof(CreateReportedZIssueManager).FullName)
);

Next, create a class which will take an input (in this case the issueTypeId) and return the name of the correct dependency:

public class IssueManagerSelector : DefaultTypedFactoryComponentSelector
{

    protected override string GetComponentName(MethodInfo method, object[] arguments)
    {
        var issueType = (IssueType)arguments[0];
        switch (issueType)
        {
            case IssueType.Listing:
                {
                    return typeof(CreateReportedXIssueManager).FullName;
                }
            case IssueType.Post:
                {
                    return typeof(CreateReportedYIssueManager).FullName;
                }
            case IssueType.User:
                {
                    return typeof(CreateReportedZIssueManager).FullName;
                }
            default:
                // So I didn't have to create an exception type as I tested.
                throw new Exception("Unknown type");
        }
    }
}

Finally, register the following with your container:

container.Register(Component.For<IReportedIssueFactory>()
    .AsFactory(new IssueManagerSelector()));

You don't need to actually create an implementation of IReportedIssueFactory. You can just inject the interface and Windsor supplies the implementation.

It will do the following:
- When you call CreateIssueManager it will pass your IssueType argument to the GetComponentName method of IssueManagerSelector.
- That method will select a component name and return it.
- The factory will then resolve the component with that name and return it.

The factory works by convention. Windsor assumes that a factory interface method that returns something is the "create" method. That's why we didn't need to give it a particular name.

Here's a unit test to ensure that it works as expected:

[TestMethod]
public void WindsorFactoryTest()
{
    var container = new WindsorContainer();
    container.AddFacility<TypedFactoryFacility>();
    container.Register(
        Component.For<IReportedIssueManager, CreateReportedXIssueManager>()
            .Named(typeof(CreateReportedXIssueManager).FullName),
        Component.For<IReportedIssueManager, CreateReportedYIssueManager>()
            .Named(typeof(CreateReportedYIssueManager).FullName),
        Component.For<IReportedIssueManager, CreateReportedZIssueManager>()
            .Named(typeof(CreateReportedZIssueManager).FullName)
    );
    container.Register(Component.For<IReportedIssueFactory>()
        .AsFactory(new IssueManagerSelector()));

    var factory = container.Resolve<IReportedIssueFactory>();
    Assert.IsInstanceOfType(factory.CreateIssueManager(IssueType.Listing), typeof(CreateReportedXIssueManager));
    Assert.IsInstanceOfType(factory.CreateIssueManager(IssueType.Post), typeof(CreateReportedYIssueManager));
    Assert.IsInstanceOfType(factory.CreateIssueManager(IssueType.User), typeof(CreateReportedZIssueManager));

}

Finally, here is Windsor's documentation.


问:
How to combine .txt files from multiple folders
I want to combine multiple .txt files in R from multiple folders. However, I'm running into trouble when I want to separate the data into different columns. Right now, the files combine but into one single column when there should be four.

I used list.files to find .txt files in the folders in my working directory. Then I used rbind and lapply to combine them with read.delim. (see below)

```<code>files = list.files(pattern = "*.txt")

myfiles = do.call(rbind, lapply(files, function(x) read.delim(x, header = FALSE, stringsAsFactors = FALSE)))
</code>```

The above code combines all of the .txt files, but the first 3 rows of each file are artifacts of the data download (basically just a naming feature) and are not pertinent to the data itself. So once the files are combined, the three lines repeat. I cannot use filter(), as I would have to manually go through the data (many thousands of lines). I would also like to repeat this process in another folder with a similar setup. So I'd like to be able to use the same code.

I think I can resolve the issue by removing the top 3 lines of each .txt file before combining them. Then I can set header = FALSE and just add in headers once the files are combined. But again, there are many hundreds of files, so I do not wish to do this manually. I'm not sure how to do this, though. Any suggestions?

Thank you for any help.

答:
Options, transcribed from the comment:

By itself, read.delim(..., skip = 3) will remove those leading duplicate rows. This will also remove the header row, so all of your frames will have generic column names, not a big problem.

To fix that, you can re-read the first row of one of the files (first?) to get the column names, with read.delim(..., nrows=1). If we used nrows=0, it reads all, so we need a minimum of 1 to limit the rows read; in the comment I included [0,], but since all you need is the column-names, it doesn't really affect things.

You can do it the first time with something like:

files = list.files(pattern = "*.txt")
myfiles = do.call(rbind, lapply(files, function(x) read.delim(x, skip = 3, header = FALSE, stringsAsFactors = FALSE)))
#                                                added this part ^^^^^^^^^
colnames(myfiles) <- colnames(read.delim(files[1], header=TRUE, nrows=1))
```

Body:
I want to combine multiple .txt files in R from multiple folders. However, I'm running into trouble when I want to separate the data into different columns. Right now, the files combine but into one single column when there should be four.

I used list.files to find .txt files in the folders in my working directory. Then I used rbind and lapply to combine them with read.delim. (see below)

files = list.files(pattern = "*.txt")

myfiles = do.call(rbind, lapply(files, function(x) read.delim(x, header = FALSE, stringsAsFactors = FALSE)))

The above code combines all of the .txt files, but the first 3 rows of each file are artifacts of the data download (basically just a naming feature) and are not pertinent to the data itself. So once the files are combined, the three lines repeat. I cannot use filter(), as I would have to manually go through the data (many thousands of lines). I would also like to repeat this process in another folder with a similar setup. So I'd like to be able to use the same code.

I think I can resolve the issue by removing the top 3 lines of each .txt file before combining them. Then I can set header = FALSE and just add in headers once the files are combined. But again, there are many hundreds of files, so I do not wish to do this manually. I'm not sure how to do this, though. Any suggestions?

Thank you for any help.


问:
Best practice to handle data from API call and render React components
I am somewhat new to React and looking for best practices for a particular situation within my React/Redux/Firebase PWA. Right now, the part I am concerned with is essentially a wrapper for the Yelp API.

I have a main component that queries the Yelp API when loaded (inside componentDidMount) based on user preferences received elsewhere in the app. This component also queries the API on a form submit with user inputs. It loops thru the data from both, and passes props to a child component. This view looks like a list of all the businesses received from the API. Here's what an example looks like:

```<code>"businesses": [
    {
      "rating": 4,
      "price": "$",
      "phone": "+14152520800",
      "id": "E8RJkjfdcwgtyoPMjQ_Olg",
      "alias": "four-barrel-coffee-san-francisco",
      "is_closed": false,
      "categories": [
        {
          "alias": "coffee",
          "title": "Coffee & Tea"
        }
      ],
      "review_count": 1738,
      "name": "Four Barrel Coffee",
      "url": "https://www.yelp.com/biz/four-barrel-coffee-san-francisco",
      "coordinates": {
        "latitude": 37.7670169511878,
        "longitude": -122.42184275
      },
      "image_url": "http://s3-media2.fl.yelpcdn.com/bphoto/MmgtASP3l_t4tPCL1iAsCg/o.jpg",
      "location": {
        "city": "San Francisco",
        "country": "US",
        "address2": "",
        "address3": "",
        "state": "CA",
        "address1": "375 Valencia St",
        "zip_code": "94103"
      },
      "distance": 1604.23,
      "transactions": ["pickup", "delivery"]
    },
    // ...
  ],
</code>```

As mentioned before, the main component passes down data to the child component, which renders each single object that list. This child component also creates a Link to another component based on the id of each business. This other component for now is simply the exact same look as one individual child component, just on a different URL. For example, the main component is "/venues" and the individual page for a business would be "/venue/E8RJkjfdcwgtyoPMjQ_Olg". The data is pulled from the Redux state (its a HOC), and filtered out to find that id.

The problem I'm running in to is when I refresh the page while on a businesses's individual page, Redux state is cleared out and hence is unable to render properly with the data. To try and work around this I attempted to have a service worker cache everything it would need, but this does not work. Refreshing ends up just showing the loading page I created, because its not making the call (which is expected - don't want it doing this) and its also not pulling data from the caches.

Is there a better way to accomplish getting data all the way to the individual business component after a refresh? Or a better way to cache the entire page/API response so it will render properly on a refresh?

I suppose I could have it reach out to the API for that specific business but I was trying to avoid that.

答:
Have you tried localStorage? there's a redux middleware for it. It looks something like this:

```<code>import {createStore, compose} from 'redux';
import persist from 'redux-localstorage';

const store = createStore(reducer, compose(...otherMiddleware, persist(['apiResponses'])))
</code>```

That should make the "apiResponses" section of your redux state persist through browser reloads.

Body:
I am somewhat new to React and looking for best practices for a particular situation within my React/Redux/Firebase PWA. Right now, the part I am concerned with is essentially a wrapper for the Yelp API.

I have a main component that queries the Yelp API when loaded (inside componentDidMount) based on user preferences received elsewhere in the app. This component also queries the API on a form submit with user inputs. It loops thru the data from both, and passes props to a child component. This view looks like a list of all the businesses received from the API. Here's what an example looks like:

"businesses": [
    {
      "rating": 4,
      "price": "$",
      "phone": "+14152520800",
      "id": "E8RJkjfdcwgtyoPMjQ_Olg",
      "alias": "four-barrel-coffee-san-francisco",
      "is_closed": false,
      "categories": [
        {
          "alias": "coffee",
          "title": "Coffee & Tea"
        }
      ],
      "review_count": 1738,
      "name": "Four Barrel Coffee",
      "url": "https://www.yelp.com/biz/four-barrel-coffee-san-francisco",
      "coordinates": {
        "latitude": 37.7670169511878,
        "longitude": -122.42184275
      },
      "image_url": "http://s3-media2.fl.yelpcdn.com/bphoto/MmgtASP3l_t4tPCL1iAsCg/o.jpg",
      "location": {
        "city": "San Francisco",
        "country": "US",
        "address2": "",
        "address3": "",
        "state": "CA",
        "address1": "375 Valencia St",
        "zip_code": "94103"
      },
      "distance": 1604.23,
      "transactions": ["pickup", "delivery"]
    },
    // ...
  ],

As mentioned before, the main component passes down data to the child component, which renders each single object that list. This child component also creates a Link to another component based on the id of each business. This other component for now is simply the exact same look as one individual child component, just on a different URL. For example, the main component is "/venues" and the individual page for a business would be "/venue/E8RJkjfdcwgtyoPMjQ_Olg". The data is pulled from the Redux state (its a HOC), and filtered out to find that id.

The problem I'm running in to is when I refresh the page while on a businesses's individual page, Redux state is cleared out and hence is unable to render properly with the data. To try and work around this I attempted to have a service worker cache everything it would need, but this does not work. Refreshing ends up just showing the loading page I created, because its not making the call (which is expected - don't want it doing this) and its also not pulling data from the caches.

Is there a better way to accomplish getting data all the way to the individual business component after a refresh? Or a better way to cache the entire page/API response so it will render properly on a refresh?

I suppose I could have it reach out to the API for that specific business but I was trying to avoid that.

Body:
Have you tried localStorage? there's a redux middleware for it. It looks something like this:

import {createStore, compose} from 'redux';
import persist from 'redux-localstorage';

const store = createStore(reducer, compose(...otherMiddleware, persist(['apiResponses'])))

That should make the "apiResponses" section of your redux state persist through browser reloads.


问:
Would it be faster to use server-side or client-side pagination/filtering/searching?
The current system that I am working on handles a variety of dataset sizes, most are around 100 but a handful of clients have 250,000 or more results. We need to handle a search across these results fields, pagination for varying page sizes up to 50, and filtering all results on a specific field.

Currently the server is setup to do all of these functions. Something to consider would be that a search would fire off a backend call, a column filter would fire off a backend call, etc. So lots of, most likely, faster calls to the backend.

The client could do these things on a cached large dataset, but it would probably be slower filtering/sorting when the dataset reaches the higher end of the spectrum.

Our primary considerations are speed and user experience. The backend approach would likely be faster & more frequent calls, but would cause lots of short load times and spinners for the user. The frontend would likely be a long initial load time and faster loads/data changes for the additional operations like filter/sort.

To those that have run into similar issues, what do you recommend? What were your concerns? Could you offer some good resources for this type of issue? Any and all assistance would be helpful.

PS sorry if this doesn't fit the standard code questions on SO, just looking for experienced help on this issue.

答:
in case of large date you have to use server side sorting, search and pagination

for performance you have to cache your http calls if you are calling the same endpoints within a given time period a couple of times.

you can find online many example of caching HTTP calls using RXJS, using handy operators like shareReplay that can cache and replay data for every subscriber and that makes you avoid making many calls to the server


问:
MongoDB is returning all Results in the find function
I'm trying to perform a simple find using MongoDB, I'm new on it, so I don't know what is wrong, but it seems that it's always bringing all the results without filtering it.

You can run the code here and see what is happening:
https://mongoplayground.net/

Collection - Paste it here https://mongoplayground.net/ - FIRST Text Area

[
  {
    "collection": "collection",
    "count": 10,
    "content": [
      {
        "_id": "apples",
        "qty": 5
      },
      {
        "_id": "bananas",
        "qty": 7
      },
      {
        "_id": "oranges",
        "qty": {
          "in stock": 8,
          "ordered": 12
        }
      },
      {
        "_id": "avocados",
        "qty": "fourteen"
      }
    ]
  }
]```
</div>
</div>
</p>

<p>Find - Paste it here https://mongoplayground.net/ - SECOND Text Area</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>db.collection.find({
  "content.qty": 5
})</code>```

Check the results and you will see the entire JSON as a result.
What Am I doing wrong? Thanks!

答:
You can use $filter with $project after your $match in order to get just one item from the array:

```<code>db.collection.aggregate([
  { $match: { "content.qty": 5 }},
  {
    $project: {
      collection: 1,
      count: 1,
      content: {
        $filter: {
          input: "$content",
          as: "item",
          cond: { $eq: [ "$$item.qty", 5 ]
          }
        }
      }
    }
  }
])
</code>```

Without having to unwind etc. You are getting all since $find returns the first document which matches and in your case that is the main doc.

See it working here

Body:
I'm trying to perform a simple find using MongoDB, I'm new on it, so I don't know what is wrong, but it seems that it's always bringing all the results without filtering it.

You can run the code here and see what is happening:
https://mongoplayground.net/

Collection - Paste it here https://mongoplayground.net/ - FIRST Text Area

[
  {
    "collection": "collection",
    "count": 10,
    "content": [
      {
        "_id": "apples",
        "qty": 5
      },
      {
        "_id": "bananas",
        "qty": 7
      },
      {
        "_id": "oranges",
        "qty": {
          "in stock": 8,
          "ordered": 12
        }
      },
      {
        "_id": "avocados",
        "qty": "fourteen"
      }
    ]
  }
]

Find - Paste it here https://mongoplayground.net/ - SECOND Text Area

db.collection.find({
  "content.qty": 5
})

Check the results and you will see the entire JSON as a result.
What Am I doing wrong? Thanks!

Body:
You can use $filter with $project after your $match in order to get just one item from the array:

db.collection.aggregate([
  { $match: { "content.qty": 5 }},
  {
    $project: {
      collection: 1,
      count: 1,
      content: {
        $filter: {
          input: "$content",
          as: "item",
          cond: { $eq: [ "$$item.qty", 5 ]
          }
        }
      }
    }
  }
])

Without having to unwind etc. You are getting all since $find returns the first document which matches and in your case that is the main doc.

See it working here


问:
How do I implement a list comprehension using map and filter?
Both map and filter can be implemented using list comprehension:

```<code>map f xs    = [f x | x <- xs]
filter p xs = [x | x <- xs, p x]
</code>```

I'd like to show that the converse holds as well using the following example:

```<code>[expr | p <- s]
</code>```

I've got so far:

```<code>map (\p -> expr) s
</code>```

But this works only when pattern matching with p succeeds on all elements of s. In a way, I first want to filter s using a pattern matching on p. Naturally, I tried looking into this question but I haven't been able to find a solution which didn't use list comprehension or LambdaCase.

答:
But this works only when pattern matching with p succeeds on all elements of s.

Indeed: the pattern matching behaviour you describe cannot, in general, be achieved with map and filter alone. Expressing comprehensions in such terms only works well in the simpler case of comprehensions with a single generator and patterns that won't fail. Rather, list comprehensions are specified in the Haskell Report in terms of concatMap. In particular, the clause about generators covers the possibility of pattern match failure:

```<code>--This is pseudo-Haskell; see the Report for the fine print.
[  <em>e</em> | <em>p</em> <- <em>l</em>,  <em>Q</em> ] = let ok <em>p</em> = [  <em>e</em> | <em>Q</em> ]
                          ok _ = []
                          in concatMap ok <em>l</em>
</code>```

The handling of match failures corresponds to what fail does in the desugaring of list monad do-blocks.

Body:
Both map and filter can be implemented using list comprehension:

map f xs    = [f x | x <- xs]
filter p xs = [x | x <- xs, p x]

I'd like to show that the converse holds as well using the following example:

[expr | p <- s]

I've got so far:

map (\p -> expr) s

But this works only when pattern matching with p succeeds on all elements of s. In a way, I first want to filter s using a pattern matching on p. Naturally, I tried looking into this question but I haven't been able to find a solution which didn't use list comprehension or LambdaCase.

Body:
But this works only when pattern matching with p succeeds on all elements of s.

Indeed: the pattern matching behaviour you describe cannot, in general, be achieved with map and filter alone. Expressing comprehensions in such terms only works well in the simpler case of comprehensions with a single generator and patterns that won't fail. Rather, list comprehensions are specified in the Haskell Report in terms of concatMap. In particular, the clause about generators covers the possibility of pattern match failure:

--This is pseudo-Haskell; see the Report for the fine print.
[  e | p <- l,  Q ] = let ok p = [  e | Q ]
                          ok _ = []
                          in concatMap ok l

The handling of match failures corresponds to what fail does in the desugaring of list monad do-blocks.


问:
VBA function to copy text from a single un-moving cell to paste to another cell, moving down one cell each paste/loop
I am trying to make a worksheet that will eventually be used for route optimization using an original base address and a list of locations. I currently have a macro that uses google maps api that will list distances and duration from the origin address to all of the addresses on the list. I am trying to pull the shortest duration found using the google maps api and have the associated address be used as the new origin so I can compare the distances and duration again. I have the worksheet setup so that the shortest duration address replaces the previous origin address, but I need to be able to copy and paste each of the new origin addresses into their own cells to essentially make a list of the order that they are used.

Basically, consider that cell G16 is where the first origin address is stored and after the first run of the distance/duration macro G16 will update to whatever address is the least furthest away from the origin address, therefor becoming the new origin. I then need to copy that origin address to cell G18 and repeat the distance/duration macro with each subsequent address from G16 being copied down 1 cell/row at a time. ie, the 1st address is copied to G18, the 2nd to G19, 3rd to G20, until all of the addresses are listed. The number of addresses is also variable and changes with each week so the range is inconsistent.

Please let me know if this makes any sense as it is kind of complicated to explain. Thank you!

答:
This should work:</p>

```<code>Cells(Rows.count, "G").End(xlUp).Offset(1, 0).Value = Range("G16").Value
</code>```

Body:
This should work:

Cells(Rows.count, "G").End(xlUp).Offset(1, 0).Value = Range("G16").Value


问:
Git packfile is truncated
When trying to pull using EGit with Eclipse I randomly get the error:

packfile is truncated

I don't know how and why this occurs. Even importing the project again doesn't help.
What's the problem here?

答: I had the same issue, i discovered it was due to the git 'default repository folder' in eclipse, mine was set to a network drive which had a space limit, once I changed to my C drive it worked without issue.</p>

Title: Git packfile is truncated


问:
Using wildcards with "convert". Or "convert"ing a group of files
I regularly scan in my Homework for class. My scanner exports raw jpg files to usb, and from there I can use gimp to edit and save the files as a pdf. One time saver I've found is to export my multi-page homeworks as a .mng file and then use the convert function to turn it into a pdf. I do it this way because Gimp automatically merges all layers when exporting to a pdf.

```<code>convert HW.mng HW.pdf
</code>```

this works well for individual files, but at the end of every week I can have dozens of files to convert.

I have tried using wildcards in the filenames for convert:

```<code>convert *.mng *.pdf
</code>```

This always runs successfully and never throws an error, but never produces any pdfs.

Both

```<code>convert HW*.mng HW*.pdf
</code>```

and

```<code>convert "HW*.mng" "HW*.pdf"
</code>```

yeild the error

```<code>convert: unable to open image `HW*.pdf': Invalid argument @ error/blob.c/OpenBlob/2712.
</code>```

which I think means the error lies in exporting with a wildcard.

Is there any way to convert all of a specific file type to another using convert? Or should I try using a different program?

答:
For convert in particular, use mogrify (which is part of ImageMagick as well) as suggested by Mark Setchell in a comment. mogrify can be used to edit/convert files in batches. The command for your case would be

mogrify -format pdf -- *.mng
```

Body:
I regularly scan in my Homework for class. My scanner exports raw jpg files to usb, and from there I can use gimp to edit and save the files as a pdf. One time saver I've found is to export my multi-page homeworks as a .mng file and then use the convert function to turn it into a pdf. I do it this way because Gimp automatically merges all layers when exporting to a pdf.

convert HW.mng HW.pdf

this works well for individual files, but at the end of every week I can have dozens of files to convert.

I have tried using wildcards in the filenames for convert:

convert *.mng *.pdf

This always runs successfully and never throws an error, but never produces any pdfs.

Both

convert HW*.mng HW*.pdf

and

convert "HW*.mng" "HW*.pdf"

yeild the error

convert: unable to open image `HW*.pdf': Invalid argument @ error/blob.c/OpenBlob/2712.

which I think means the error lies in exporting with a wildcard.

Is there any way to convert all of a specific file type to another using convert? Or should I try using a different program?


问:
Explicit Log Level instead of MinimumLevel for Serilog
Is there any way I can configure exactly ONE log level per file in serilog?

I know I can configure one file per "MinimumLevel", but that is not what I need.

答:
Serilog.Sinks.Map can be used for this without introducing too much duplication:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Map(le => le.Level, (level, wt) => wt.File($"C:\\Temp\\{level}-logs.txt"));
```


问:
How to pass reference to a WinForm control to a class when creating instance of this class?
How to pass a reference to a form object (i.e. TextBox) to a class, so I could specify what text box this instance needs to be working with when creating this instance?
Specific example:
I have a class that processes some text strings. I have few instances of this class.
I also have few text boxes on my form. I have a method in a class that shows some text in a text box. What do I need to do to tell to a specific instance of my class what text box to use when creating this instance? Should be in constructor, something like:

public MyClass (string textString, /ref to a text box/)

This is my class:

```<code> public class LogClass
{
    private readonly TextBox _textBox;

    private string logText;
    public string LogText
    {
        get
        {
            return logText;
        }

        set
        {
            logText = value;
        }
    }

    public void AddToLog(string textString)
    {

        try
        {
            if (string.IsNullOrEmpty(textString))
            {
                throw new ArgumentException("message", nameof(textString));
            }
            logText = logText+ "\n" + textString;
            _textBox.Text = logText;

        }
        catch (Exception)
        {

            throw;
        }

    }

    public LogClass(string initialText, TextBox textBox)
    {
        logText = initialText;
        _textBox = textBox;
        _textBox.Text = logText;

    }
}
</code>```

And this is my form:

```<code> public partial class LogWindow : Form
{

    LogClass myLog = new LogClass("this is initial string", logOutputBox);
    public LogWindow()
    {
        InitializeComponent();
    }

    public string LogTextToPass {
        get { return logOutputBox.Text; }
        set { logOutputBox.Text = value; }
    }

    private void buttonWriteLog_Click(object sender, EventArgs e)
    {
        myLog.AddToLog(inputText.Text);

    }

    private void logOutputBox_TextChanged(object sender, EventArgs e)
    {

    }
}
</code>```

Error CS0236 is on this line:

```<code>    LogClass myLog = new LogClass("this is initial string", logOutputBox);
</code>```

Error   CS0236  A field initializer cannot reference the non-static field, method, or property 'LogWindow.logOutputBox'
logOutputBox is highlighted

答:
You can pass it in any way you want. A constructor argument seems sensible, if the class isn't useable without a TextBox. In the constructor you can subscribe to the TextBox's events.</p>

```<code>class TextBoxHandler
{
    private readonly TextBox _textbox;

    public TextBoxHandler(TextBox textbox)
    {
        _textbox = textbox;
        _textbox.Click += HandleClick;
    }

    public void HandleClick(object sender, EventArgs e)
    {
        //Do something
    }
}
</code>```

Body:
How to pass a reference to a form object (i.e. TextBox) to a class, so I could specify what text box this instance needs to be working with when creating this instance?
Specific example:
I have a class that processes some text strings. I have few instances of this class.
I also have few text boxes on my form. I have a method in a class that shows some text in a text box. What do I need to do to tell to a specific instance of my class what text box to use when creating this instance? Should be in constructor, something like:

public MyClass (string textString, /ref to a text box/)

This is my class:

 public class LogClass
{
    private readonly TextBox _textBox;

    private string logText;
    public string LogText
    {
        get
        {
            return logText;
        }

        set
        {
            logText = value;
        }
    }

    public void AddToLog(string textString)
    {

        try
        {
            if (string.IsNullOrEmpty(textString))
            {
                throw new ArgumentException("message", nameof(textString));
            }
            logText = logText+ "\n" + textString;
            _textBox.Text = logText;

        }
        catch (Exception)
        {

            throw;
        }

    }

    public LogClass(string initialText, TextBox textBox)
    {
        logText = initialText;
        _textBox = textBox;
        _textBox.Text = logText;

    }
}

And this is my form:

 public partial class LogWindow : Form
{

    LogClass myLog = new LogClass("this is initial string", logOutputBox);
    public LogWindow()
    {
        InitializeComponent();
    }

    public string LogTextToPass {
        get { return logOutputBox.Text; }
        set { logOutputBox.Text = value; }
    }

    private void buttonWriteLog_Click(object sender, EventArgs e)
    {
        myLog.AddToLog(inputText.Text);

    }

    private void logOutputBox_TextChanged(object sender, EventArgs e)
    {

    }
}

Error CS0236 is on this line:

    LogClass myLog = new LogClass("this is initial string", logOutputBox);

Error   CS0236  A field initializer cannot reference the non-static field, method, or property 'LogWindow.logOutputBox'
logOutputBox is highlighted

Body:
You can pass it in any way you want. A constructor argument seems sensible, if the class isn't useable without a TextBox. In the constructor you can subscribe to the TextBox's events.

class TextBoxHandler
{
    private readonly TextBox _textbox;

    public TextBoxHandler(TextBox textbox)
    {
        _textbox = textbox;
        _textbox.Click += HandleClick;
    }

    public void HandleClick(object sender, EventArgs e)
    {
        //Do something
    }
}


问:
C - read specific line from file
I'm trying to read a specific line from a file and I can get the line number but I'm not sure how to go about doing it, this is what I have so far:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
  FILE *file;
  file = fopen("temp.txt","r");
  char tmp[256]={0x0};
  char *tmpline;
  int numline = 1;
  while(file != NULL && fgets(tmp, sizeof(tmp),file) !=NULL)
  {
    tmpline = strstr(tmp,"status:green");

    if(tmpline) {
      printf("%d - %s", numline, tmpline);
    }

    numline++;
  }
  if (file != NULL) fclose(file);

  return 0;
}
</code>```

The test file looks like:

```<code>s1.server.com
127.0.0.1
status:green

s2.server.com
127.0.0.1
status:red

s3.server.com
127.0.0.1
status:red

s4.server.com
127.0.0.1
status:green
</code>```

The output that I have is:

```<code>3 - status:green
15 - status:green
</code>```

But what I really want it to show is:

```<code>s1.server.com
s4.server.com
</code>```

I want it to search for "status:green" then go back a few lines to show which server it belongs to

答: Read the first and third lines in each group. Search for status:green and, if found, print the server name.

Title: C - read specific line from file

Body:
I'm trying to read a specific line from a file and I can get the line number but I'm not sure how to go about doing it, this is what I have so far:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
  FILE *file;
  file = fopen("temp.txt","r");
  char tmp[256]={0x0};
  char *tmpline;
  int numline = 1;
  while(file != NULL && fgets(tmp, sizeof(tmp),file) !=NULL)
  {
    tmpline = strstr(tmp,"status:green");

    if(tmpline) {
      printf("%d - %s", numline, tmpline);
    }

    numline++;
  }
  if (file != NULL) fclose(file);

  return 0;
}

The test file looks like:

s1.server.com
127.0.0.1
status:green

s2.server.com
127.0.0.1
status:red

s3.server.com
127.0.0.1
status:red

s4.server.com
127.0.0.1
status:green

The output that I have is:

3 - status:green
15 - status:green

But what I really want it to show is:

s1.server.com
s4.server.com

I want it to search for "status:green" then go back a few lines to show which server it belongs to


问:
SpringbootTest + TestContainers: how do I refresh the database after tests pollute the database
I am using an abstract class like this:

```<code>@SpringBootTest(classes = MyAppApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class AbstractIntegrationTest {

    static {
        PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer().withPassword("password")
                .withUsername("postgres").withDatabaseName("MyApp");
        postgreSQLContainer.start();

        System.setProperty("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
        System.setProperty("spring.datasource.password", postgreSQLContainer.getPassword());
        System.setProperty("spring.datasource.username", postgreSQLContainer.getUsername());

    }
</code>```

Then I have many tests that leverage that use that class like this:

```<code>public class moreTests extends AbstractIntegrationTest {

    TestRestTemplate restTemplate = new TestRestTemplate("my-user", "password");
    HttpHeaders headers = new HttpHeaders();

    @Test
    public void SimpleHealthCheck() {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/api/v1/healthcheck"),
                HttpMethod.GET, entity, String.class);
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    }

    @Test
    public void GetInst() {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/api/v1/institutions"),
                HttpMethod.GET, entity, String.class);
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    }
</code>```

However, some of my tests will pollute the database.  I'd like to control if a test runs with a fresh database or not.  What's the prescribed way to do this?

答:
you either use the @Before annotation to clean everything before executing your tests.

Or you clean in each test before you execute.

Each test should be independent from the other. So usually:

clear and set up expectations

run test

If test fails, your database will be in the failed state so you can check what happened.

Body:
I am using an abstract class like this:

@SpringBootTest(classes = MyAppApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class AbstractIntegrationTest {

    static {
        PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer().withPassword("password")
                .withUsername("postgres").withDatabaseName("MyApp");
        postgreSQLContainer.start();

        System.setProperty("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
        System.setProperty("spring.datasource.password", postgreSQLContainer.getPassword());
        System.setProperty("spring.datasource.username", postgreSQLContainer.getUsername());

    }

Then I have many tests that leverage that use that class like this:

public class moreTests extends AbstractIntegrationTest {

    TestRestTemplate restTemplate = new TestRestTemplate("my-user", "password");
    HttpHeaders headers = new HttpHeaders();

    @Test
    public void SimpleHealthCheck() {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/api/v1/healthcheck"),
                HttpMethod.GET, entity, String.class);
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    }

    @Test
    public void GetInst() {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/api/v1/institutions"),
                HttpMethod.GET, entity, String.class);
        assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
    }

However, some of my tests will pollute the database.  I'd like to control if a test runs with a fresh database or not.  What's the prescribed way to do this?


问:
VueJS - vue.config.js proxy configuration for build
I'm currently using devServer{proxy:{...}} in vue.config.js to configure proxy for api calls for avoiding CORS problems in my application. It works fine when I run npm run serve in localhost.

Now I need to deploy my application to a host, so I run npm run build, change the url's of my Ajax calls and it's not running... So what I indeed need is to configure my proxy for deployment (build), not for devServer.

What is the correct way to do that?

I've already tried:
server{proxy:{...}} and build{proxy:{...}}, but none of them are allowed when running npm run build.

Thank you!

答:
Vue CLI, by default, will not ship a webserver like the proxy, it will deploy bundled Javascript in a dist/ directory.

The proxy isn't meant to be deployed to production and that's why you're not finding information about deploying with it.

If you're serving a static /dist directory, find the instructions here for your provider (S3, Netlify, Firebase) and follow them.

Longer answer:

You're running into an issue because the proxy is not supposed to be used for production. The proxy Vue CLI is shipping with is webpack-dev-server. It is used by Vue CLI to enable you to serve your Javascript files locally during development.

There are security vulnerabilities if you use webpack-dev-server (aka the proxy) in prod. Don't do it.

Instead, you need to find the hosting provider you're using and follow the instructions here: https://cli.vuejs.org/guide/deployment.html to deploy your application. If your application is personal or can be public, I suggest using Netlify.

For example... In my production setup, we deploy to an AWS S3 bucket and serve content with either AWS Cloudfront CDN or the Fastly CDN. Our API urls are always the production server ones, and we use this setting in the proxy to pass through to our local server


问:
CSS text-overflow: ellipsis; not working?
I don't know why this simple CSS isn't working...

.app a {
  height: 18px;
  width: 140px;
  padding: 0;
  overflow: hidden;
  position: relative;
  margin: 0 5px 0 5px;
  text-align: center;
  text-decoration: none;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  Test Test Test Test Test Test
</div></code>```

Should cut off around the 4th "Test"

答:
MUST contain

```<code>  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
</code>```

MUST NOT contain

```<code>display: inline
</code>```

SHOULD contain

```<code>position: sticky
</code>```

Body:
I don't know why this simple CSS isn't working...

.app a {
  height: 18px;
  width: 140px;
  padding: 0;
  overflow: hidden;
  position: relative;
  margin: 0 5px 0 5px;
  text-align: center;
  text-decoration: none;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #000;
}

  Test Test Test Test Test Test

Should cut off around the 4th "Test"

Body:
MUST contain

  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;

MUST NOT contain

display: inline

SHOULD contain

position: sticky


问:
Django CreateView With ManyToManyField
I am trying to use a Django CreateView and ultimately update a ManyToMany Field if the user selects a certain value.  I can get the form to validate, but ultimately it isn't updating the manytomanyfield in the database.  Not sure what I'm doing wrong.  I have referenced this similar SO issue, Django ManyToMany CreateView Fields In Both Tables but it was of no help to me.  I recently found this link...Django CreateView: How to perform action upon save and it seems very close to the issue I'm having.  Thanks in advance for any thoughts.

My code:

```<code>class AuthorView(LoginRequiredMixin,CreateView):
    model = NewAuthor
    form_class = NewAuthorForm
    template_name = 'create_author.html'

    def form_valid(self, form):
        instance = form.save(commit=False)

        if instance.status == 'Submitted':

            if instance.choice == "Custom":
                instance.access.add(instance.created_by)
                form.save_m2m()

    return super(CreateAuthorView, self).form_valid(form)
</code>```

Here is my model:

```<code>class NewAuthor(models.Model):

CHOICES = (
    ('',''),
    ("Default",Default ),
    ("Custom",Custom ),
)

STATUS_CHOICES = (
    ("Submitted","Submitted"),
    ("Pending","Pending")
)

status = models.CharField(choices=STATUS_CHOICES,default="Submitted",max_length=20)
choice = models.CharField(choices=CHOICES,blank=True,max_length=300)
created_by = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING,related_name='created_by_user')
access = models.ManyToManyField(User,related_name="new_author_individual_access")
</code>```

This passes form validation, but doesn't save the created_by value in the manytomany field.  I have tried to incorporate form.save(commit=False) and a subsequent form.save(), but that doesn't seem to help either.  I am ultimately trying to add the created_by user to the manytomany field conditionally, but no luck so far.

As a quick update, if I add the form.save_m2m() to my code, it actually does add the created_by to the database...but I also get an error that says object has no attribute 'save_m2m'.  It actually adds the created_by but then quits because of this error.  Now if I add commit=False, no errors but the database doesn't get updated either.

答: This post was the answer to my problem.  Save Many-To-Many Field Django Forms ModelForms are great....but not with m2m apparently...That was exhausting...</p>

Title: Django CreateView With ManyToManyField

Body:
I am trying to use a Django CreateView and ultimately update a ManyToMany Field if the user selects a certain value.  I can get the form to validate, but ultimately it isn't updating the manytomanyfield in the database.  Not sure what I'm doing wrong.  I have referenced this similar SO issue, Django ManyToMany CreateView Fields In Both Tables but it was of no help to me.  I recently found this link...Django CreateView: How to perform action upon save and it seems very close to the issue I'm having.  Thanks in advance for any thoughts.

My code:

class AuthorView(LoginRequiredMixin,CreateView):
    model = NewAuthor
    form_class = NewAuthorForm
    template_name = 'create_author.html'

    def form_valid(self, form):
        instance = form.save(commit=False)

        if instance.status == 'Submitted':

            if instance.choice == "Custom":
                instance.access.add(instance.created_by)
                form.save_m2m()

    return super(CreateAuthorView, self).form_valid(form)

Here is my model:

class NewAuthor(models.Model):

CHOICES = (
    ('',''),
    ("Default",Default ),
    ("Custom",Custom ),
)

STATUS_CHOICES = (
    ("Submitted","Submitted"),
    ("Pending","Pending")
)

status = models.CharField(choices=STATUS_CHOICES,default="Submitted",max_length=20)
choice = models.CharField(choices=CHOICES,blank=True,max_length=300)
created_by = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING,related_name='created_by_user')
access = models.ManyToManyField(User,related_name="new_author_individual_access")

This passes form validation, but doesn't save the created_by value in the manytomany field.  I have tried to incorporate form.save(commit=False) and a subsequent form.save(), but that doesn't seem to help either.  I am ultimately trying to add the created_by user to the manytomany field conditionally, but no luck so far.

As a quick update, if I add the form.save_m2m() to my code, it actually does add the created_by to the database...but I also get an error that says object has no attribute 'save_m2m'.  It actually adds the created_by but then quits because of this error.  Now if I add commit=False, no errors but the database doesn't get updated either.


问:
How do you open extracted images from the MNIST database
Basically, I'm trying to get an image from the MNIST dataset and then show it on my computer. The problem is that when I try to open a single image (using the pillow Image.open() function), it says it can't 'read' it. I can't tell if it's a single thing that's not working or all of it. Really, I'm just messing around with new stuff.

I tried using the 'tensorflow.examples.tutorials.mnist', but it just keeps mucking up, I don't know why. Then I decided that I should just download the MNIST data and open that and now it's saying it can't 'read' 'numpy.ndarray'.

from PIL import Image
from tensorflow.contrib.learn.python.learn.datasets.mnist import extract_images, extract_labels

with open('train-images-idx3-ubyte (2).gz', 'rb') as f:
  train_images = extract_images(f)
with open('train-labels-idx1-ubyte (1).gz', 'rb') as f:
  train_labels = extract_labels(f)

with open('t10k-images-idx3-ubyte.gz', 'rb') as f:
  test_images = extract_images(f)
with open('t10k-labels-idx1-ubyte.gz', 'rb') as f:
  test_labels = extract_labels(f)

myImage = Image.open(train_images[0])
myImage.show()
```

I expected it to open the file but it just shows up with an error about opening train_images[0]

答:
Nevermind, I found out the answer.

What you needed to do was change the shape of the data using np.reshape() and then use Image.fromarray() instead of Image.open().
For example:

MyImage = train_images[0]
MyImage = MyImage.reshape(28, 28)
MyImage = Image.fromarray(MyImage)
```

Body:
Basically, I'm trying to get an image from the MNIST dataset and then show it on my computer. The problem is that when I try to open a single image (using the pillow Image.open() function), it says it can't 'read' it. I can't tell if it's a single thing that's not working or all of it. Really, I'm just messing around with new stuff.

I tried using the 'tensorflow.examples.tutorials.mnist', but it just keeps mucking up, I don't know why. Then I decided that I should just download the MNIST data and open that and now it's saying it can't 'read' 'numpy.ndarray'.

from PIL import Image
from tensorflow.contrib.learn.python.learn.datasets.mnist import extract_images, extract_labels

with open('train-images-idx3-ubyte (2).gz', 'rb') as f:
  train_images = extract_images(f)
with open('train-labels-idx1-ubyte (1).gz', 'rb') as f:
  train_labels = extract_labels(f)

with open('t10k-images-idx3-ubyte.gz', 'rb') as f:
  test_images = extract_images(f)
with open('t10k-labels-idx1-ubyte.gz', 'rb') as f:
  test_labels = extract_labels(f)

myImage = Image.open(train_images[0])
myImage.show()

I expected it to open the file but it just shows up with an error about opening train_images[0]