问:
more efficient way of searching 2D array - break after match?
I have a 2D array of units students are studying. For each unit there are different numbers of functions (aka objectives) they are studying and for each function, different numbers of prompts they could be asked in an assessment. My data is a 2D array thus:

```<code>functions = [
  ["Unit 1",
    [ // function 1
      "prompt 1",
      "prompt 2",
      ...,
      "prompt n"],
    [ // function 2
  etc...
</code>```

My code creates assessments based on which units have been studied by pulling random prompts and then shuffling these into the array (sm1).

Some of these prompts have image files associated with them and all have audio files. The file names for these media files are based on where they occur in our material, e.g. u1f1p1.mp3

So my solution was to match this regularity by creating file names based on their position in the array. Here's my code to do that:

```<code>for (var a = 0; a < sm1.length; a++) {// for each of sm1's prompts
    for (var b = 0; b <= functions.length-6; b++) { // limit it to units 1-3 of 8 for this specific assessment
       for(var c = 1; c < functions[b].length; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
           for (var d = 0; d < functions[b][c].length; d++) { // for each prompt for each function for each unit
               if(functions[b][c][d] === sm1[a]) { // see if it matches
                    fileNames.push('u'+(b+1)+'f'+c+'p'+(d+1)); // create file name from index and add to fileNames[]
                }
            }
        }
    }
}
</code>```

This code works fine and, because speed is effectively irrelevant for our purposes, I could say job done. However, I know that this has to be hopelessly inefficient because not only is this a long loop, but it continues to run even after a match is found.

So, two questions:

What would be the most efficient way of finding a match?

How can I break once sm1[n] is found and go on to look for sm1[n+1]?

答:
As for efficiency well I'm unsure but as for breaking on a match it's actually quite simple.

One way (and probably the best way) you can do it is to put it in a function and return fileNames when you have found your match -

```<code>function findFileName(sm1, functions, fileNames) {
  for (var a = 0; a < sm1.length; a++) { // for each of sm1's prompts
    for (var b = 0; b <= functions.length - 6; b++) { // limit it to units 1-3 of 8 for this specific assessment
      for (var c = 1; c < functions[b].length; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
        for (var d = 0; d < functions[b][c].length; d++) { // for each prompt for each function for each unit
          if (functions[b][c][d] === sm1[a]) { // see if it matches
            fileNames.push('u' + (b + 1) + 'f' + c + 'p' + (d + 1)); // create file name from index and add to fileNames[]
            return fileNames;
          }
        }
      }
    }
  }
}
</code>```

If using a function isn't for you it can be done inline (hacky code follows; you have been warned).

Although the second clause of a for statement usually relies on the first clause (a < sm1.length) there's actually nothing stopping you from putting extra constraints in there that have nothing to do with the first clause.  So you could add a boolean variable before the first for check that on each iteration and set it to true when you find a match -

```<code>var matchFound = false;
for (var a = 0; a < sm1.length && !matchFound; a++) { // for each of sm1's prompts
  for (var b = 0; b <= functions.length - 6 && !matchFound; b++) { // limit it to units 1-3 of 8 for this specific assessment
    for (var c = 1; c < functions[b].length && !matchFound; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
      for (var d = 0; d < functions[b][c].length && !matchFound; d++) { // for each prompt for each function for each unit
        if (functions[b][c][d] === sm1[a]) { // see if it matches
          fileNames.push('u' + (b + 1) + 'f' + c + 'p' + (d + 1)); // create file name from index and add to fileNames[]
          matchFound = true;
        }
      }
    }
  }
}
</code>```

Body:
I have a 2D array of units students are studying. For each unit there are different numbers of functions (aka objectives) they are studying and for each function, different numbers of prompts they could be asked in an assessment. My data is a 2D array thus:

functions = [
  ["Unit 1",
    [ // function 1
      "prompt 1",
      "prompt 2",
      ...,
      "prompt n"],
    [ // function 2
  etc...

My code creates assessments based on which units have been studied by pulling random prompts and then shuffling these into the array (sm1).

Some of these prompts have image files associated with them and all have audio files. The file names for these media files are based on where they occur in our material, e.g. u1f1p1.mp3

So my solution was to match this regularity by creating file names based on their position in the array. Here's my code to do that:

for (var a = 0; a < sm1.length; a++) {// for each of sm1's prompts
    for (var b = 0; b <= functions.length-6; b++) { // limit it to units 1-3 of 8 for this specific assessment
       for(var c = 1; c < functions[b].length; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
           for (var d = 0; d < functions[b][c].length; d++) { // for each prompt for each function for each unit
               if(functions[b][c][d] === sm1[a]) { // see if it matches
                    fileNames.push('u'+(b+1)+'f'+c+'p'+(d+1)); // create file name from index and add to fileNames[]
                }
            }
        }
    }
}

This code works fine and, because speed is effectively irrelevant for our purposes, I could say job done. However, I know that this has to be hopelessly inefficient because not only is this a long loop, but it continues to run even after a match is found.

So, two questions:

What would be the most efficient way of finding a match?

How can I break once sm1[n] is found and go on to look for sm1[n+1]?

Body:
As for efficiency well I'm unsure but as for breaking on a match it's actually quite simple.

One way (and probably the best way) you can do it is to put it in a function and return fileNames when you have found your match -

function findFileName(sm1, functions, fileNames) {
  for (var a = 0; a < sm1.length; a++) { // for each of sm1's prompts
    for (var b = 0; b <= functions.length - 6; b++) { // limit it to units 1-3 of 8 for this specific assessment
      for (var c = 1; c < functions[b].length; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
        for (var d = 0; d < functions[b][c].length; d++) { // for each prompt for each function for each unit
          if (functions[b][c][d] === sm1[a]) { // see if it matches
            fileNames.push('u' + (b + 1) + 'f' + c + 'p' + (d + 1)); // create file name from index and add to fileNames[]
            return fileNames;
          }
        }
      }
    }
  }
}

If using a function isn't for you it can be done inline (hacky code follows; you have been warned).

Although the second clause of a for statement usually relies on the first clause (a < sm1.length) there's actually nothing stopping you from putting extra constraints in there that have nothing to do with the first clause.  So you could add a boolean variable before the first for check that on each iteration and set it to true when you find a match -

var matchFound = false;
for (var a = 0; a < sm1.length && !matchFound; a++) { // for each of sm1's prompts
  for (var b = 0; b <= functions.length - 6 && !matchFound; b++) { // limit it to units 1-3 of 8 for this specific assessment
    for (var c = 1; c < functions[b].length && !matchFound; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
      for (var d = 0; d < functions[b][c].length && !matchFound; d++) { // for each prompt for each function for each unit
        if (functions[b][c][d] === sm1[a]) { // see if it matches
          fileNames.push('u' + (b + 1) + 'f' + c + 'p' + (d + 1)); // create file name from index and add to fileNames[]
          matchFound = true;
        }
      }
    }
  }
}


来源: stackexchange

问:
Can someone look into a web servers folders?
More a web server security question.

Is it possible for someone to "probe" into a folder on a web server, even if an index file is in place?

I assume they can't, but if I wanted to store .pdf applications as random names (93fe3509edif094.pdf) I want to make sure there's no way to list all the pdfs in the folder.

Thank you.

答: Depends on the server. The server always decides what the client may and may not see. In your case, Apache, see Mitro's answer.</p>

ContentLicense: CC BY-SA 2.5


问:
Reducing code duplication while defining a commutative operation
I have a a set of overloads of a commutative binary function named overlap, which accepts two distinct types:

```<code>class A a; class B b;
bool overlap(A, B);
bool overlap(B, A);
</code>```

My function overlap returns true if and only if one shape overlaps the other - this is one common example used when discussing multimethods.

Because overlap(a, b) is equivalent to overlap(b, a), I only need to implement one "side" of the relation.  One repetitive solution is to write something like this:

```<code>bool overlap(A a, B b) { /* check for overlap */ }
bool overlap(B b, A a) { return overlap(a, b);   }
</code>```

But I would prefer not to write an extra N! / 2 trivial versions of the same function by allowing them to be generated instead, using a template.

```<code>template <typename T, typename U>
bool overlap(T&& t, U&& u)
{ return overlap(std::forward<U>(u), std::forward<T>(t)); }
</code>```

Unfortuately, this is prone to recurse infinitely, which is not acceptable: see
http://coliru.stacked-crooked.com/a/20851835593bd557

How can I prevent such infinite recursion?  Am I approaching the problem correctly?

答:
Here's a simple fix:

```<code>template <typename T, typename U>
void overlap(T t, U u)
{
    void overlap(U, T);
    overlap(u, t);
}
</code>```

The template itself declares the target function, which will be preferred over recursion because it is an exact match (be sure to take care of constness and reference-ness in your real case). If the function has not been implemented, you get a linker error:

```<code>/tmp/cc7zinK8.o: In function `void overlap<C, D>(C, D)':
main.cpp:(.text._Z7overlapI1C1DEvT_T0_[_Z7overlapI1C1DEvT_T0_]+0x20):
    undefined reference to `overlap(D, C)'
collect2: error: ld returned 1 exit status
</code>```

... which points directly at the missing function :)

ContentLicense: CC BY-SA 3.0

Body:
I have a a set of overloads of a commutative binary function named overlap, which accepts two distinct types:

class A a; class B b;
bool overlap(A, B);
bool overlap(B, A);

My function overlap returns true if and only if one shape overlaps the other - this is one common example used when discussing multimethods.

Because overlap(a, b) is equivalent to overlap(b, a), I only need to implement one "side" of the relation.  One repetitive solution is to write something like this:

bool overlap(A a, B b) { /* check for overlap */ }
bool overlap(B b, A a) { return overlap(a, b);   }

But I would prefer not to write an extra N! / 2 trivial versions of the same function by allowing them to be generated instead, using a template.

template <typename T, typename U>
bool overlap(T&& t, U&& u)
{ return overlap(std::forward(u), std::forward<T>(t)); }

Unfortuately, this is prone to recurse infinitely, which is not acceptable: see
http://coliru.stacked-crooked.com/a/20851835593bd557

How can I prevent such infinite recursion?  Am I approaching the problem correctly?

Body:
Here's a simple fix:

template <typename T, typename U>
void overlap(T t, U u)
{
    void overlap(U, T);
    overlap(u, t);
}

The template itself declares the target function, which will be preferred over recursion because it is an exact match (be sure to take care of constness and reference-ness in your real case). If the function has not been implemented, you get a linker error:

/tmp/cc7zinK8.o: In function `void overlap<C, D>(C, D)':
main.cpp:(.text._Z7overlapI1C1DEvT_T0_[_Z7overlapI1C1DEvT_T0_]+0x20):
    undefined reference to `overlap(D, C)'
collect2: error: ld returned 1 exit status

... which points directly at the missing function :)


问:
Minecraft Bukkit Runnable
I'm trying to create a minecraft plugin which shoots an arrow 5 times with a 10 tick delay between the shots.

Unfortunately I'm not really experienced with Java, but I'll try my best to understand the answers.

This is my Code:

public void run() {
    for (int i = 0; i <5; i++){
        player.playSound(player.getLocation(), Sound.SHOOT_ARROW, 1.0f, 1.0f);
        Arrow arrow = player.launchProjectile(Arrow.class);
        Events.removeArrows.put(arrow.getEntityId(), (byte) 1);
    }
}
```

At the moment this code snippet "shoots" 5 Arrows without delay. Now I'm stuck when it comes to adding a delay.

答:
```<code>BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(yourPlugin, new Runnable() {
    @Override
    public void run() {
        //Execute Arrow Code here
    }
}, 10L);
</code>```

That will execute the code within the run()method every 10 ticks, until stopped. To do so, use this.cancel(); within the Runnable.

Title: Minecraft Bukkit Runnable

Body:
I'm trying to create a minecraft plugin which shoots an arrow 5 times with a 10 tick delay between the shots.

Unfortunately I'm not really experienced with Java, but I'll try my best to understand the answers.

This is my Code:

public void run() {
    for (int i = 0; i <5; i++){
        player.playSound(player.getLocation(), Sound.SHOOT_ARROW, 1.0f, 1.0f);
        Arrow arrow = player.launchProjectile(Arrow.class);
        Events.removeArrows.put(arrow.getEntityId(), (byte) 1);
    }
}

At the moment this code snippet "shoots" 5 Arrows without delay. Now I'm stuck when it comes to adding a delay.

Body:
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(yourPlugin, new Runnable() {
    @Override
    public void run() {
        //Execute Arrow Code here
    }
}, 10L);

That will execute the code within the run()method every 10 ticks, until stopped. To do so, use this.cancel(); within the Runnable.


问:
OpenLayers4: How to give icon a bigger click radius
I am trying to make an Icon feature that I can click on easier on mobile phones. I have an icon set up nicely and when using a mouse to click on it there is no issue. However when using my finger or thumb on a mobile phone it is quite difficult to get an accurate click. I am using a ol.geom.Point and giving it an icon style. I tried an ol.geom.Circle but I can't get the icon style to work with it.

Here is an example of my working ol.geom.Point:

```<code>        for (i in spots) {
            var spot = spots[i];
            var coords = spot['coords'];
            var lat = parseFloat(coords.split(',')[0]);
            var lng = parseFloat(coords.split(',')[1]);
            var iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(ol.proj.fromLonLat([lng, lat])),
                type: 'spot'
            });
            iconFeature.setStyle(spotMarker);
            features.push(iconFeature);
        }
        vectorSourceSpots = new ol.source.Vector({
            features: features
        });
        var vectorLayer = new ol.layer.Vector({
            source: vectorSourceSpots
        });
        map.addLayer(vectorLayer);
</code>```

Here is the spotMarker style:

```<code>        var spotMarker = new ol.style.Style({
            image: new ol.style.Icon(({
                src: 'images/spot.png'
            }))
        });
</code>```

I've also tried with a ol.geom.Circle but I could not see my icon when I tried this:

```<code>        for (i in spots) {
            var spot = spots[i];
            var coords = spot['coords'];
            var lat = parseFloat(coords.split(',')[0]);
            var lng = parseFloat(coords.split(',')[1]);
            var iconFeature = new ol.Feature({
                geometry: new ol.geom.Circle(ol.proj.fromLonLat([lng, lat]), 5),
                type: 'spot'
            });
            iconFeature.setStyle(spotMarker);
            features.push(iconFeature);
        }
        vectorSourceSpots = new ol.source.Vector({
            features: features
        });
        var vectorLayer = new ol.layer.Vector({
            source: vectorSourceSpots
        });
        map.addLayer(vectorLayer);
</code>```

What I want is to have the icon remain the same size, but just to increase the click radius around the icon. Almost like an invisible circle a bit bigger than the icon with the same center.

Is this possible?

答:
You will use forEachFeatureAtPixel to add event on the features, then you can set hitTolerance on its options parameter.

check this api document: forEachFeatureAtPixel

you may need to write:

```<code>var addEvent = function(map, evt) {
    map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {

    }, {
        hitTolerance: 10
    });
};

map.on('click', function(evt) {
    addEvent(map, evt);
});
</code>```

Body:
I am trying to make an Icon feature that I can click on easier on mobile phones. I have an icon set up nicely and when using a mouse to click on it there is no issue. However when using my finger or thumb on a mobile phone it is quite difficult to get an accurate click. I am using a ol.geom.Point and giving it an icon style. I tried an ol.geom.Circle but I can't get the icon style to work with it.

Here is an example of my working ol.geom.Point:

        for (i in spots) {
            var spot = spots[i];
            var coords = spot['coords'];
            var lat = parseFloat(coords.split(',')[0]);
            var lng = parseFloat(coords.split(',')[1]);
            var iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(ol.proj.fromLonLat([lng, lat])),
                type: 'spot'
            });
            iconFeature.setStyle(spotMarker);
            features.push(iconFeature);
        }
        vectorSourceSpots = new ol.source.Vector({
            features: features
        });
        var vectorLayer = new ol.layer.Vector({
            source: vectorSourceSpots
        });
        map.addLayer(vectorLayer);

Here is the spotMarker style:

        var spotMarker = new ol.style.Style({
            image: new ol.style.Icon(({
                src: 'images/spot.png'
            }))
        });

I've also tried with a ol.geom.Circle but I could not see my icon when I tried this:

        for (i in spots) {
            var spot = spots[i];
            var coords = spot['coords'];
            var lat = parseFloat(coords.split(',')[0]);
            var lng = parseFloat(coords.split(',')[1]);
            var iconFeature = new ol.Feature({
                geometry: new ol.geom.Circle(ol.proj.fromLonLat([lng, lat]), 5),
                type: 'spot'
            });
            iconFeature.setStyle(spotMarker);
            features.push(iconFeature);
        }
        vectorSourceSpots = new ol.source.Vector({
            features: features
        });
        var vectorLayer = new ol.layer.Vector({
            source: vectorSourceSpots
        });
        map.addLayer(vectorLayer);

What I want is to have the icon remain the same size, but just to increase the click radius around the icon. Almost like an invisible circle a bit bigger than the icon with the same center.

Is this possible?

Body:
You will use forEachFeatureAtPixel to add event on the features, then you can set hitTolerance on its options parameter.

check this api document: forEachFeatureAtPixel

you may need to write:

var addEvent = function(map, evt) {
    map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {

    }, {
        hitTolerance: 10
    });
};

map.on('click', function(evt) {
    addEvent(map, evt);
});


问:
fingerprint a function with its arguments in r
I'd like to save computation time,
by avoiding running the same function with the same arguments multiple times.

given the following code:

```<code>f1 <- function(a,b) return(a+b)
f2 <- function(c,d,f) return(c*d*f)

x <- 3
y <- 4

f2(1,2,f1(x,y))
</code>```

let's assume that the computation of 'f' function argument is hard,
and I'd like to cash the result somehow, so that I'd know if it had ever been executed before.

here is my main question:

I assume I can generate a key myself for f1(3,4),
example: key <-  paste('f1',x,y), do my own bookkeeping and avoid running it again.

however, is it possible for f2 to generate such a key from f automatically and return it to me?
(for any function with any arguments)

if not / alternatively, before I pass f1(x,y) can I generate such a key in a generic manner,
that would work for any function with any arguments?

thanks much

答:
Interesting question. I never thought about this.

A quick google search found this package: R.cache.

The function addMemoization takes a function as argument, and returns a function that should cache its results.

I haven't used this package myself, so I don't know how well it works, but it seems to fit what you are looking for.

Body:
I'd like to save computation time,
by avoiding running the same function with the same arguments multiple times.

given the following code:

f1 <- function(a,b) return(a+b)
f2 <- function(c,d,f) return(c*d*f)

x <- 3
y <- 4

f2(1,2,f1(x,y))

let's assume that the computation of 'f' function argument is hard,
and I'd like to cash the result somehow, so that I'd know if it had ever been executed before.

here is my main question:

I assume I can generate a key myself for f1(3,4),
example: key <-  paste('f1',x,y), do my own bookkeeping and avoid running it again.

however, is it possible for f2 to generate such a key from f automatically and return it to me?
(for any function with any arguments)

if not / alternatively, before I pass f1(x,y) can I generate such a key in a generic manner,
that would work for any function with any arguments?

thanks much


问:
Error while validating XML
System.ArgumentNullException: value cannot be undefined

StackTrace:

```<code>   at System.Xml.Linq.XAttribute..ctor(XName name, Object value)
   at System.Xml.Schema.XNodeValidator.ValidateAttributes(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateElement(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateNodes(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateElement(XElement e)
   at System.Xml.Schema.XNodeValidator.Validate(XObject source, XmlSchemaObject partialValidationType, Boolean addSchemaInfo)
   at System.Xml.Schema.Extensions.Validate(XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, Boolean addSchemaInfo)
</code>```

Source code:

```<code>    var xmlPath = @"C:\XSDTEST\test.xml";

    XDocument doc = XDocument.Load(xmlPath);
    XmlSchemaSet xss = new XmlSchemaSet();

    xss.Add("",@"C:\XSDTEST\test.xsd");

    XmlReaderSettings xrs = new XmlReaderSettings();
    xrs.ValidationType = ValidationType.Schema;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
    xrs.Schemas = xss;

    doc.Validate(xss, new ValidationEventHandler((s, args) => { }), true);
</code>```

test.xsd:

```<code><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="Root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="Child1" minOccurs="1" maxOccurs="1"/>
                <xsd:element ref="Child2" minOccurs="1" maxOccurs="1"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="Child2" type="Child2ElemType"/>
    <xsd:complexType name="Child2ElemType">
        <xsd:attribute ref="align" default="left"/>
    </xsd:complexType>
    <xsd:attribute name="align" type="alignAttType"/>
    <xsd:simpleType name="alignAttType">
        <xsd:restriction base="xsd:NMTOKEN">
            <xsd:enumeration value="left"/>
            <xsd:enumeration value="right"/>
            <xsd:enumeration value="center"/>
            <xsd:enumeration value="justify"/>
            <xsd:enumeration value="char"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:schema>
</code>```

test.xml:

```<code><Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/XSDTEST/test.xsd">
    <Child1/>
    <Child2/>
</Root>
</code>```

The problem: default="left":

```<code><xsd:attribute ref="align" default="left"/>
</code>```

I think the validation process tries to create an "align" attribute with a default value, but the XAttribute constructor gets null, not "left".

If I set default value at <xsd:attribute name="align" type="alignAttType" default="left"/> it works fine.

If I set default value at <xsd:attribute ref="align" default="left"/> I will get the error.

Can I disable the creation of attributes with default values during the validation process?

or

What are the settings for correctly handling the default values?

答:
After loading schemas I founded temporary workaround:</p>

```<code>       foreach (XmlSchema schema in xss.Schemas())
            {
                foreach (System.Collections.DictionaryEntry ag in schema.AttributeGroups)
                {
                    if (ag.Value is XmlSchemaAttributeGroup)
                    {
                        var attributeGroup = (XmlSchemaAttributeGroup)ag.Value;

                        foreach (var attributeOrGroup in attributeGroup.Attributes)
                        {
                            if (attributeOrGroup is XmlSchemaAttribute)
                            {
                                var attribute = (XmlSchemaAttribute)attributeOrGroup;
                                if (attribute.DefaultValue != null)
                                {
                                    attribute.DefaultValue = null;
                                }
                                if (attribute.FixedValue != null)
                                {
                                    attribute.FixedValue = null;
                                }
                            }
                        }
                    }
                }
                foreach (System.Collections.DictionaryEntry st in schema.SchemaTypes)
                {
                    if (st.Value is XmlSchemaComplexType)
                    {
                        var c = (XmlSchemaComplexType)st.Value;

                        foreach (var g in c.Attributes)
                        {
                            if (g is XmlSchemaAttribute)
                            {
                                var attr = (XmlSchemaAttribute)g;
                                if (attr.DefaultValue != null)
                                {
                                    attr.DefaultValue = null;

                                }
                                if (attr.FixedValue != null)
                                {
                                    attr.FixedValue = null;
                                }

                            }
                        }
                    }
                }
            }
</code>```

Title: Error while validating XML

Body:
System.ArgumentNullException: value cannot be undefined

StackTrace:

   at System.Xml.Linq.XAttribute..ctor(XName name, Object value)
   at System.Xml.Schema.XNodeValidator.ValidateAttributes(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateElement(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateNodes(XElement e)
   at System.Xml.Schema.XNodeValidator.ValidateElement(XElement e)
   at System.Xml.Schema.XNodeValidator.Validate(XObject source, XmlSchemaObject partialValidationType, Boolean addSchemaInfo)
   at System.Xml.Schema.Extensions.Validate(XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, Boolean addSchemaInfo)

Source code:

    var xmlPath = @"C:\XSDTEST\test.xml";

    XDocument doc = XDocument.Load(xmlPath);
    XmlSchemaSet xss = new XmlSchemaSet();

    xss.Add("",@"C:\XSDTEST\test.xsd");

    XmlReaderSettings xrs = new XmlReaderSettings();
    xrs.ValidationType = ValidationType.Schema;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
    xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
    xrs.Schemas = xss;

    doc.Validate(xss, new ValidationEventHandler((s, args) => { }), true);

test.xsd:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="Root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="Child1" minOccurs="1" maxOccurs="1"/>
                <xsd:element ref="Child2" minOccurs="1" maxOccurs="1"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="Child2" type="Child2ElemType"/>
    <xsd:complexType name="Child2ElemType">
        <xsd:attribute ref="align" default="left"/>
    </xsd:complexType>
    <xsd:attribute name="align" type="alignAttType"/>
    <xsd:simpleType name="alignAttType">
        <xsd:restriction base="xsd:NMTOKEN">
            <xsd:enumeration value="left"/>
            <xsd:enumeration value="right"/>
            <xsd:enumeration value="center"/>
            <xsd:enumeration value="justify"/>
            <xsd:enumeration value="char"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:schema>

test.xml:

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/XSDTEST/test.xsd">
    <Child1/>
    <Child2/>
</Root>

The problem: default="left":

<xsd:attribute ref="align" default="left"/>

I think the validation process tries to create an "align" attribute with a default value, but the XAttribute constructor gets null, not "left".

If I set default value at <xsd:attribute name="align" type="alignAttType" default="left"/> it works fine.

If I set default value at <xsd:attribute ref="align" default="left"/> I will get the error.

Can I disable the creation of attributes with default values during the validation process?

or

What are the settings for correctly handling the default values?

Body:
After loading schemas I founded temporary workaround:

       foreach (XmlSchema schema in xss.Schemas())
            {
                foreach (System.Collections.DictionaryEntry ag in schema.AttributeGroups)
                {
                    if (ag.Value is XmlSchemaAttributeGroup)
                    {
                        var attributeGroup = (XmlSchemaAttributeGroup)ag.Value;

                        foreach (var attributeOrGroup in attributeGroup.Attributes)
                        {
                            if (attributeOrGroup is XmlSchemaAttribute)
                            {
                                var attribute = (XmlSchemaAttribute)attributeOrGroup;
                                if (attribute.DefaultValue != null)
                                {
                                    attribute.DefaultValue = null;
                                }
                                if (attribute.FixedValue != null)
                                {
                                    attribute.FixedValue = null;
                                }
                            }
                        }
                    }
                }
                foreach (System.Collections.DictionaryEntry st in schema.SchemaTypes)
                {
                    if (st.Value is XmlSchemaComplexType)
                    {
                        var c = (XmlSchemaComplexType)st.Value;

                        foreach (var g in c.Attributes)
                        {
                            if (g is XmlSchemaAttribute)
                            {
                                var attr = (XmlSchemaAttribute)g;
                                if (attr.DefaultValue != null)
                                {
                                    attr.DefaultValue = null;

                                }
                                if (attr.FixedValue != null)
                                {
                                    attr.FixedValue = null;
                                }

                            }
                        }
                    }
                }
            }


问:
Resources to compare Java to Objective-C (syntax and basics)
I have taught myself a lot of Objective-C over the past year and a half, and have even been able to publish some iOS apps on the App Store.  Concepts that were foreign to me before about object oriented programming are now second nature and I understand MVC, inheritance, polymorphism etc.  I'm now interested in learning to develop for the Android platform, which will entail learning Java.  I want to find resources that can match up Java basics with regards to syntax and structure with the same things from the Objective-C world.

The Wikipedia entry for Objective-C has exactly what I'm looking for with regards to how Objective-C relates to C++.  If there is a document, blog post or book dedicated to something like this for Java in relation to Objective-C I would be all over it like a bear on honey.  It should include things like

Class method declarations and implementations

instance method declarations and implementations

How to compose a method name (ie +/-(returntype)methodName:(type)argument; )

declaring properties

Thank you for all of your suggestions!

答: It looks like there's some decent info in these slides: http://jonathanlehr.files.wordpress.com/2009/09/objective-c-and-java.pdf if you can get past the generic introductions.</p>


问:
Powershell remoting issue
I am trying to use powershell remoting from Server A to server B using Enter-PSSession -Computername ServerB. Both servers are in the same domain. Remoting is enabled on server B using Enable-PSRemoting , which has worked fine. I can use Enter-PSSession -computername command from ServerA to other servers fine.

when trying Enter-PSSession -Computername ServerB from SErver A, it gives following error:

```<code>FullyqualifiedErrorId: CreateRemoteRunSpaceFailed
</code>```

Running winrm get winrm/config on serverB gives following:

```<code>Listener
    Address = *
    Transport = HTTP
    Port = 5985
    Hostname
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint
    ListeningOn = 127.0.0.1, 192.168.0.4, ::1, 2002:b40a:1a8b::b40a:1a8b, fe80::100:7f:fffe%12, fe80::200:5efe:180.10.26.139%14, fe80::681a:e480:25fd:e50e%13
</code>```

Firewall on all servers is off.

Any Idea on "FullyqualifiedErrorId: CreateRemoteRunSpaceFailed" error?

thanks
vb

答:
Trusted hosts and local accounts should not be used if the machines are in the same domain and the user has local admin rights.

The machines
Can you ping Server b from server a?

You said you can remote to other machines from Server A can you remote to Server B from other machines?

Has your user account got local admin rights on server B?

Title: Powershell remoting issue

Body:
I am trying to use powershell remoting from Server A to server B using Enter-PSSession -Computername ServerB. Both servers are in the same domain. Remoting is enabled on server B using Enable-PSRemoting , which has worked fine. I can use Enter-PSSession -computername command from ServerA to other servers fine.

when trying Enter-PSSession -Computername ServerB from SErver A, it gives following error:

FullyqualifiedErrorId: CreateRemoteRunSpaceFailed

Running winrm get winrm/config on serverB gives following:

Listener
    Address = *
    Transport = HTTP
    Port = 5985
    Hostname
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint
    ListeningOn = 127.0.0.1, 192.168.0.4, ::1, 2002:b40a:1a8b::b40a:1a8b, fe80::100:7f:fffe%12, fe80::200:5efe:180.10.26.139%14, fe80::681a:e480:25fd:e50e%13

Firewall on all servers is off.

Any Idea on "FullyqualifiedErrorId: CreateRemoteRunSpaceFailed" error?

thanks
vb


问:
Error when start a new project in cordova-ionic in Ubuntu
I have the next problem, i have installed cordova version
7.0.1 , node version 4.2.6 , but i have this error if all is correct in when  instal Node JS and Cordova y ionic?

why I have this problem?

```

sommer@sommer-AO532h:~$ cordova -v
7.0.1
sommer@sommer-AO532h:~$
sommer@sommer-AO532h:~$ ionic -v
ERR: Your Node.js version is v4.2.6. Please update to the latest Node 6 LTS version (or latest Node).
sommer@sommer-AO532h:~$ node -v
v4.2.6
sommer@sommer-AO532h:~$ ionic start todo blank --type ionic1
ERR: Your Node.js version is v4.2.6. Please update to the latest Node 6 LTS version (or latest Node).
sommer@sommer-AO532h:~$

```

答:
From the Requirements Section from ionic-cli GitHub Page -

Node 6 LTS (latest)

npm 3+

So you need Node 6 LTS to use   ionic-cli, The Ionic command line interface (CLI) i.e the one that you are using.

So update it first and then use ionic-cli.

Body:
I have the next problem, i have installed cordova version
7.0.1 , node version 4.2.6 , but i have this error if all is correct in when  instal Node JS and Cordova y ionic?

why I have this problem?

sommer@sommer-AO532h:~$ cordova -v
7.0.1
sommer@sommer-AO532h:~$
sommer@sommer-AO532h:~$ ionic -v
ERR: Your Node.js version is v4.2.6. Please update to the latest Node 6 LTS version (or latest Node).
sommer@sommer-AO532h:~$ node -v
v4.2.6
sommer@sommer-AO532h:~$ ionic start todo blank --type ionic1
ERR: Your Node.js version is v4.2.6. Please update to the latest Node 6 LTS version (or latest Node).
sommer@sommer-AO532h:~$


答:
You can rename the actual method to something like overlap_impl and call this one inside the template. I will break the recursion:

```<code>bool overlap_impl(A a, B b) { /* check for overlap */ }

template <typename T, typename U>
bool overlap(T&& t, U&& u)
{ return overlap_impl(std::forward<U>(u), std::forward<T>(t)); }

template<> bool overlap(A&& t, B&& u)
{ return overlap_impl(std::forward<A>(t), std::forward<B>(u)); }
</code>```

Title: Reducing code duplication while defining a commutative operation

Body:
You can rename the actual method to something like overlap_impl and call this one inside the template. I will break the recursion:

bool overlap_impl(A a, B b) { /* check for overlap */ }

template <typename T, typename U>
bool overlap(T&& t, U&& u)
{ return overlap_impl(std::forward<U>(u), std::forward<T>(t)); }

template<> bool overlap(A&& t, B&& u)
{ return overlap_impl(std::forward<A>(t), std::forward<B>(u)); }


问:
Is it possible to apply a CSS style to the container element?
I am looking for a selector which applies to any div element that contains an element identified by the p.my selector</p>

```<code><div>
 <p class="my">
  prova
 </p>
</div>
</code>```

答:
No, there is no specific parent selector in CSS, but I know two other ways:

You just give the
 a class or id.

You could install jquery and use:
$('p.my').parent().css({/*some css*/});

Body:
I am looking for a selector which applies to any div element that contains an element identified by the p.my selector

  prova

Body:
No, there is no specific parent selector in CSS, but I know two other ways:

You just give the <div> a class or id.

You could install jquery and use:
$('p.my').parent().css({/*some css*/});


问:
How to modify activation email content in Open edX Platform?
Someone has previously asked a question regarding the location of the activation email .txt file for the profile activation email that is sent out when a user registers on an Open edX platform.

I have located these files and made changes. Further, I have manually compiled the assets and restarted the lms, cms, and workers. My problem is that the old email is still sent when a user registers on the platform.

Can anyone help me understand what I need to do to make these changes happen? I've been working on this for a while and, to me, this seems like a straight forward problem. But I don't really understand what is happening, so am having trouble getting the desired output.

答:
Text activation emails are mako templates and they get compiled in a temporary location. The server is most likely not compiling them again after your modifications.

Try to clean the /tmp/mako_lms/<some_hash>/emails/ directory.

You can even remove everything in /tmp/mako_lms if you don't care about the penalty of mako recompiling everything again.

One liner:

```<code>sudo rm /tmp/mako_lms/*/emails/*
</code>```

Body:
Text activation emails are mako templates and they get compiled in a temporary location. The server is most likely not compiling them again after your modifications.

Try to clean the /tmp/mako_lms/<some_hash>/emails/ directory.

You can even remove everything in /tmp/mako_lms if you don't care about the penalty of mako recompiling everything again.

One liner:

sudo rm /tmp/mako_lms/*/emails/*


问:
virtual url representing page contents but not a different .html file
I have a website that consists of a single page coded in html that uses jquery to load web albums from picasa into a container depending on the link that the user clicks on.  This works fine, but I want the content loaded into the page to coincide with a url.  At the moment, when one of the album links is clicked, the photos load and a '#' is appended to the url.  How can I append the album name to the url instead, and have the browser understand that this album name coincides with the content loaded on the page by jquery.

Additionally, I want to be able to send someone a link to my website: kornweissphotography.com/steven/albumname where albumname is the name of one of my web albums and have the appropriate images load into the page.

website: www.kornweissphotography.com/steven

Thank you!

答: I'm pretty sure this is only possible using a server side scripting language (e.g. PHP) and rewriting the query string using the .htaccess file. I don't think client side languages can have any effect on the url </p>


问:
VB.NET Delete specific number of last characters in string in excel
I have a column where I have an ID. I have to match data from one file with other, however in one table there is pure ID, in the other there are ID+year, so I have to delete four last characters in every cell of that column. I tried this:

```<code>For i=2 to ArraySize
    ExWorkSheet.Cells(i, ColumnNumber) = ExWorkSheet.Cells(i, ColumnNumber).remove(len(string)-4,4)
Next
</code>```

This code works but it is very slow. I have 17k+ rows in table.
I also tried to use function replace, it is faster because it works on whole range, but it delete every string 2017(or 2016, etc.), even if it is in the middle of ID.

答:
same coding upper.</p>

```<code>Dim vDB, rngDB As Range
Set rngDB = ExWorkSheet.Cells(2, ColumnNumber).Resize(arraysize)
vDB = rngDB
For i = 1 To UBound(vDB, 1)
    vDB(i, 1) = Left(vDB(i, 1), Len(vDB(i, 1)) - 4)
Next i
rngDB = vDB
</code>```

Body:
I have a column where I have an ID. I have to match data from one file with other, however in one table there is pure ID, in the other there are ID+year, so I have to delete four last characters in every cell of that column. I tried this:

For i=2 to ArraySize
    ExWorkSheet.Cells(i, ColumnNumber) = ExWorkSheet.Cells(i, ColumnNumber).remove(len(string)-4,4)
Next

This code works but it is very slow. I have 17k+ rows in table.
I also tried to use function replace, it is faster because it works on whole range, but it delete every string 2017(or 2016, etc.), even if it is in the middle of ID.

Body:
same coding upper.

Dim vDB, rngDB As Range
Set rngDB = ExWorkSheet.Cells(2, ColumnNumber).Resize(arraysize)
vDB = rngDB
For i = 1 To UBound(vDB, 1)
    vDB(i, 1) = Left(vDB(i, 1), Len(vDB(i, 1)) - 4)
Next i
rngDB = vDB


问:
Azure ML- Execute Python Script -Datatime.date not working
I am getting the following error when I try to convert a datetime variable to date.

My Code

```<code>import datetime as dt

df['TXN_DATE_2'] = df['TXN_DATE'].dt.date
</code>```

Error

raise NotImplementedError('Python Bridge conversion table not
  implemented for type [{0}]'.format(value.getType()))
  NotImplementedError: Python Bridge conversion table not implemented
  for type [] Process returned with non-zero exit
  code 1

Can anyone please tell me what is going on.

答:
Please try to use the code below to convert as you want.

```<code>import pandas as pd
import datetime as dt
df['TXN_DATE_2'] = pd.to_datetime(df['TXN_DATE']).dt.date
</code>```

Hope it helps.

Body:
I am getting the following error when I try to convert a datetime variable to date.

My Code

import datetime as dt

df['TXN_DATE_2'] = df['TXN_DATE'].dt.date

Error

raise NotImplementedError('Python Bridge conversion table not
  implemented for type [{0}]'.format(value.getType()))
  NotImplementedError: Python Bridge conversion table not implemented
  for type [] Process returned with non-zero exit
  code 1

Can anyone please tell me what is going on.

Body:
Please try to use the code below to convert as you want.

import pandas as pd
import datetime as dt
df['TXN_DATE_2'] = pd.to_datetime(df['TXN_DATE']).dt.date

Hope it helps.


问:
Split multiple Strings in java
I'm new to Java and trying to split multiple strings and store it in a String array. The layman program follows:

```<code>    Scanner sc = new Scanner(System.in);
    String s1 = "Hello1 Hello2";
    String s2 = "Hello3 Hello4";
    String s3 = "Hello5 Hello6";
    String[] parts = s1.split(" ");
    parts = s2.split(" "); //Rewrites
    parts = s3.split(" "); //Rewrites
    for(String s4:parts) {
      System.out.print(s4 + " ");
    }
</code>```

The ouput of the program is obviously : Hello5 Hello6. (How to split a string in Java)

Regardless I expect the output Hello1 Hello2 Hello3 Hello4 Hello5 Hello6. Which is, the incoming string must not replace the existing Strings inside the array.

答:
Arrays are fixed-length, so all you can do is replace their existing elements, or create a new, separate array.

It is easier if you use a List, which can be variable-length, and use addAll to add the results of the split to that:

```<code>List<String> parts = new ArrayList<>();
parts.addAll(Arrays.asList(s1.split(" ")));
parts.addAll(Arrays.asList(s2.split(" ")));
parts.addAll(Arrays.asList(s3.split(" ")));
</code>```

Note that you have to use Arrays.asList here because split returns a String[], whereas addAll requires a collection of String, e.g. List<String>.

Title: Split multiple Strings in java

Body:
I'm new to Java and trying to split multiple strings and store it in a String array. The layman program follows:

    Scanner sc = new Scanner(System.in);
    String s1 = "Hello1 Hello2";
    String s2 = "Hello3 Hello4";
    String s3 = "Hello5 Hello6";
    String[] parts = s1.split(" ");
    parts = s2.split(" "); //Rewrites
    parts = s3.split(" "); //Rewrites
    for(String s4:parts) {
      System.out.print(s4 + " ");
    }

The ouput of the program is obviously : Hello5 Hello6. (How to split a string in Java)

Regardless I expect the output Hello1 Hello2 Hello3 Hello4 Hello5 Hello6. Which is, the incoming string must not replace the existing Strings inside the array.

Body:
Arrays are fixed-length, so all you can do is replace their existing elements, or create a new, separate array.

It is easier if you use a List, which can be variable-length, and use addAll to add the results of the split to that:

List<String> parts = new ArrayList<>();
parts.addAll(Arrays.asList(s1.split(" ")));
parts.addAll(Arrays.asList(s2.split(" ")));
parts.addAll(Arrays.asList(s3.split(" ")));

Note that you have to use Arrays.asList here because split returns a String[], whereas addAll requires a collection of String, e.g. List<String>.


问:
Send value from function to an other VC, swift3
I have this function, which is called when the user clicks on the image on the collectionView. There is a variable url (in the line print("IMAGE CLICKED:", url)) I want to send the value of the url to another viewController and set url in a UIImage.

Here is my unfinished function in the firstVC. From here I'd like to send the url to the secondVC.

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (liveCommunities?[indexPath.row].communityId)!
    let home = HomeViewController()
    home.showCommunityDetail()

    //url is the source for a image in another viewController
    //TODO: Send url to other viewController
    //There is no relation between the thwo viewControllers (only via tabbar)

    print("--------")
    print("IMAGE CLICKED:", url)
    print("--------")

}
</code>```

Is that possible? Thanks for your help in advance!

答: Yes you can. Use delegates. You can also post notifications and observe it in the previous controller. Please check this answer for using delegates. If you prefer to use Notifications, use this answer</p>

Body:
I have this function, which is called when the user clicks on the image on the collectionView. There is a variable url (in the line print("IMAGE CLICKED:", url)) I want to send the value of the url to another viewController and set url in a UIImage.

Here is my unfinished function in the firstVC. From here I'd like to send the url to the secondVC.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (liveCommunities?[indexPath.row].communityId)!
    let home = HomeViewController()
    home.showCommunityDetail()

    //url is the source for a image in another viewController
    //TODO: Send url to other viewController
    //There is no relation between the thwo viewControllers (only via tabbar)

    print("--------")
    print("IMAGE CLICKED:", url)
    print("--------")

}

Is that possible? Thanks for your help in advance!


问:
How to not split English into separate letters in the Stanford Chinese Parser
I am using the Stanford Segmenter at http://nlp.stanford.edu/software/segmenter.shtml in Python. For the Chinese segmenter, whenever it encounters a English word, it will split the word into many characters one by one, but I want to keep the characters together after the segmentation is done.

For example:

```<code>你好abc我好
</code>```

currently will become this after the segmentation

```<code>你好 a b c 我 好
</code>```

but I want it to become

```<code>你好 abc 我 好
</code>```

Is there a way to teach the segmenter to do that?  Is there a setting for this?

I Googlged this and to no answer, and tried to hack together a way(spending 6 hours on it) to do this by pulling out English characters from the text and then put them back in after the segmentation is done, but realized it is very difficult to do this in a efficient manner.  Any help on this would be greatly appreciated.

答:
After applying the Stanford tokenizer, I'd simply search for any pattern where a sequence of numbers or English letters are peppered with space and remove the spaces in this way:

```<code>re.sub(r'(?<=\w)\s(?=\w)', '', u'\u5982\u4f55 \u767b\u5f55 C o n c u r \u7cfb\u7edf \uff1f\n')
</code>```

Which gives:

```<code>u'\u5982\u4f55 \u767b\u5f55 Concur \u7cfb\u7edf \uff1f\n'
</code>```

Body:
I am using the Stanford Segmenter at http://nlp.stanford.edu/software/segmenter.shtml in Python. For the Chinese segmenter, whenever it encounters a English word, it will split the word into many characters one by one, but I want to keep the characters together after the segmentation is done.

For example:

你好abc我好

currently will become this after the segmentation

你好 a b c 我 好

but I want it to become

你好 abc 我 好

Is there a way to teach the segmenter to do that?  Is there a setting for this?

I Googlged this and to no answer, and tried to hack together a way(spending 6 hours on it) to do this by pulling out English characters from the text and then put them back in after the segmentation is done, but realized it is very difficult to do this in a efficient manner.  Any help on this would be greatly appreciated.

Body:
After applying the Stanford tokenizer, I'd simply search for any pattern where a sequence of numbers or English letters are peppered with space and remove the spaces in this way:

re.sub(r'(?<=\w)\s(?=\w)', '', u'\u5982\u4f55 \u767b\u5f55 C o n c u r \u7cfb\u7edf \uff1f\n')

Which gives:

u'\u5982\u4f55 \u767b\u5f55 Concur \u7cfb\u7edf \uff1f\n'


问:
Escape from JUnit testcase possible?
Is it possible to escape from a JUnit testcase (maybe via reflection) and to modify the test result?

Let's say we have a method

```<code>int foo() { ... }
</code>```

which is under test and a method

```<code>void fooTest() { ... }
</code>```

which tests foo() for correct implementation.

Is it somehow possible to cheat in foo() and to access (maybe via the stack trace and reflection) the test method / result so the test doesn't fail even when foo is incorrect?

答:
@Ignore is used to temporarily disable a test:

```<code>@Ignore
@Test
public void testMethod() { // enter code here }
</code>```

Reason can also be provided which is optional:

```<code>@Ignore("Under development")
@Test
public void testMethod() { // enter code here }
</code>```

@Ignore can be used at class level:

```<code>@Ignore
public class IgnoreTestClass {
      @Test public void testOne(){`enter code here`}
      @Test public void testTwo(){`enter code here`}
}
</code>```

Title: Escape from JUnit testcase possible?

Body:
Is it possible to escape from a JUnit testcase (maybe via reflection) and to modify the test result?

Let's say we have a method

int foo() { ... }

which is under test and a method

void fooTest() { ... }

which tests foo() for correct implementation.

Is it somehow possible to cheat in foo() and to access (maybe via the stack trace and reflection) the test method / result so the test doesn't fail even when foo is incorrect?

Body:
@Ignore is used to temporarily disable a test:

@Ignore
@Test
public void testMethod() { // enter code here }

Reason can also be provided which is optional:

@Ignore("Under development")
@Test
public void testMethod() { // enter code here }

@Ignore can be used at class level:

@Ignore
public class IgnoreTestClass {
      @Test public void testOne(){`enter code here`}
      @Test public void testTwo(){`enter code here`}
}


问:
Xamarin iOS: A EXC_CRASH, unable to understand what the log is about
I have a crash log saying about the crash but no idea what that crash is

```<code>  Incident Identifier: 12D4E7E8-D09B-44B6-9E5C-216223C75C76
CrashReporter Key:   4c344eeca1fe853d12dc884970218feefdb6cdc2
Hardware Model:      iPad4,1
Process:             Provider.iOS [556]
Path:                /private/var/containers/Bundle/Application/B37F718C-171F-43C7-99AB-AFF5CA5F3D86/Provider.iOS.app/Provider.iOS
Identifier:          com.application.cheetah
Version:             1.0.30 (1.0.0)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.application.cheetah [630]

Date/Time:           2017-07-06 15:55:01.9326 +1200
Launch Time:         2017-07-06 14:49:31.6289 +1200
OS Version:          iPhone OS 10.3.2 (14F89)
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Filtered syslog:
None found

Thread 0 name:  tid_403  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x0000000183ea5014 __pthread_kill + 8
1   libsystem_pthread.dylib         0x0000000183f6f264 pthread_kill + 112
2   libsystem_c.dylib               0x0000000183e199c4 abort + 140
3   Provider.iOS                    0x0000000101a71430 xamarin_printf (runtime.m:2167)
4   Provider.iOS                    0x000000010196fe48 mono_invoke_unhandled_exception_hook (exception.c:1120)
5   Provider.iOS                    0x0000000101929c20 mono_handle_exception_internal (mini-exceptions.c:1893)
6   Provider.iOS                    0x0000000101928c44 mono_handle_exception (mini-exceptions.c:2126)
7   Provider.iOS                    0x0000000101920bd4 mono_arm_throw_exception (exceptions-arm64.c:410)
8   Provider.iOS                    0x00000001003287b8 throw_exception + 168
9   Provider.iOS                    0x000000010021190c System_Runtime_ExceptionServices_ExceptionDispatchInfo_Throw + 44
10  Provider.iOS                    0x0000000100214004 System_Runtime_CompilerServices_AsyncMethodBuilderCore__c__ThrowAsyncb__6_0_object + 84
11  Provider.iOS                    0x0000000100c670d8 UIKit_UIKitSynchronizationContext__Postc__AnonStorey0__m__0 (UIKitSynchronizationContext.cs:24)
12  Provider.iOS                    0x0000000100c55644 Foundation_NSAsyncActionDispatcher_Apply (NSAction.cs:163)
13  Provider.iOS                    0x00000001002f3ac4 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 244
14  Provider.iOS                    0x0000000101938cfc mono_jit_runtime_invoke (mini-runtime.c:2510)
15  Provider.iOS                    0x00000001019b1b58 do_runtime_invoke (object.c:2860)
16  Provider.iOS                    0x00000001019b1ab4 mono_runtime_invoke (object.c:3018)
17  Provider.iOS                    0x0000000101880104 native_to_managed_trampoline_3(objc_object*, objc_selector*, _MonoMethod**, unsigned int) (registrar.m:106)
18  Provider.iOS                    0x000000010188065c -[__MonoMac_NSAsyncActionDispatcher xamarinApplySelector] (registrar.m:7022)
19  Foundation                      0x000000018599e4cc __NSThreadPerformPerform + 340
20  CoreFoundation                  0x0000000184e5942c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
21  CoreFoundation                  0x0000000184e58d9c __CFRunLoopDoSources0 + 540
22  CoreFoundation                  0x0000000184e569a8 __CFRunLoopRun + 744
23  CoreFoundation                  0x0000000184d86da4 CFRunLoopRunSpecific + 424
24  GraphicsServices                0x00000001867f0074 GSEventRunModal + 100
25  UIKit                           0x000000018b03a058 UIApplicationMain + 208
26  Provider.iOS                    0x0000000100cc33d4 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr (/<unknown>:1)
27  Provider.iOS                    0x0000000100c6bc6c UIKit_UIApplication_Main_string___intptr_intptr (UIApplication.cs:79)
28  Provider.iOS                    0x0000000100c6bc2c UIKit_UIApplication_Main_string___string_string (UIApplication.cs:63)
29  Provider.iOS                    0x0000000100041b44 Provider_iOS_Application_Main_string__ (Main.cs:17)
30  Provider.iOS                    0x00000001002f3ac4 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 244
31  Provider.iOS                    0x0000000101938cfc mono_jit_runtime_invoke (mini-runtime.c:2510)
32  Provider.iOS                    0x00000001019b1b58 do_runtime_invoke (object.c:2860)
33  Provider.iOS                    0x00000001019b4d7c do_exec_main_checked (object.c:4681)
34  Provider.iOS                    0x000000010191d558 mono_jit_exec (driver.g.c:1037)
35  Provider.iOS                    0x0000000101a7e1ec xamarin_main (monotouch-main.m:480)
36  Provider.iOS                    0x00000001018a6310 main (main.m:173)
37  libdyld.dylib                   0x0000000183d9559c start + 4
</code>```

Does anyone have any idea what this crash report refer to?

答:
It's hard to say, but I may suggest that the root cause of your app crash could be the result of memory leaks due to the fact that your app may allocate too much memory and then perhaps does not correctly release the memory after usage. From that log, you can't get more information. My suggestion will be to connect a device and build on it. Building on simulator may not work because desktop has significantly more available ram than a mobile device.

If it's not possible to reproduce on a connected device (sometimes that may happen). You can use one hack to get more information about the crash from a device. Since all your code is executable throw mono runtime, you can easily catch lots of crashed my wrapping your UIaaplication.Main function into a try-catch block, and save the exception string somewhere on the device.

in Main.cs

```<code>public class Application {
    static void Main(string[] args) {
        try {
            UIApplication.Main(args: args, principalClassName: null, delegateClassName: typeof(AppDelegate).Name);
        } catch (Exception e) {
            // save e.ToString() somewhere
        }
    }
}
</code>```

Body:
I have a crash log saying about the crash but no idea what that crash is

  Incident Identifier: 12D4E7E8-D09B-44B6-9E5C-216223C75C76
CrashReporter Key:   4c344eeca1fe853d12dc884970218feefdb6cdc2
Hardware Model:      iPad4,1
Process:             Provider.iOS [556]
Path:                /private/var/containers/Bundle/Application/B37F718C-171F-43C7-99AB-AFF5CA5F3D86/Provider.iOS.app/Provider.iOS
Identifier:          com.application.cheetah
Version:             1.0.30 (1.0.0)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.application.cheetah [630]

Date/Time:           2017-07-06 15:55:01.9326 +1200
Launch Time:         2017-07-06 14:49:31.6289 +1200
OS Version:          iPhone OS 10.3.2 (14F89)
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Filtered syslog:
None found

Thread 0 name:  tid_403  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x0000000183ea5014 __pthread_kill + 8
1   libsystem_pthread.dylib         0x0000000183f6f264 pthread_kill + 112
2   libsystem_c.dylib               0x0000000183e199c4 abort + 140
3   Provider.iOS                    0x0000000101a71430 xamarin_printf (runtime.m:2167)
4   Provider.iOS                    0x000000010196fe48 mono_invoke_unhandled_exception_hook (exception.c:1120)
5   Provider.iOS                    0x0000000101929c20 mono_handle_exception_internal (mini-exceptions.c:1893)
6   Provider.iOS                    0x0000000101928c44 mono_handle_exception (mini-exceptions.c:2126)
7   Provider.iOS                    0x0000000101920bd4 mono_arm_throw_exception (exceptions-arm64.c:410)
8   Provider.iOS                    0x00000001003287b8 throw_exception + 168
9   Provider.iOS                    0x000000010021190c System_Runtime_ExceptionServices_ExceptionDispatchInfo_Throw + 44
10  Provider.iOS                    0x0000000100214004 System_Runtime_CompilerServices_AsyncMethodBuilderCore__c__ThrowAsyncb__6_0_object + 84
11  Provider.iOS                    0x0000000100c670d8 UIKit_UIKitSynchronizationContext__Postc__AnonStorey0__m__0 (UIKitSynchronizationContext.cs:24)
12  Provider.iOS                    0x0000000100c55644 Foundation_NSAsyncActionDispatcher_Apply (NSAction.cs:163)
13  Provider.iOS                    0x00000001002f3ac4 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 244
14  Provider.iOS                    0x0000000101938cfc mono_jit_runtime_invoke (mini-runtime.c:2510)
15  Provider.iOS                    0x00000001019b1b58 do_runtime_invoke (object.c:2860)
16  Provider.iOS                    0x00000001019b1ab4 mono_runtime_invoke (object.c:3018)
17  Provider.iOS                    0x0000000101880104 native_to_managed_trampoline_3(objc_object*, objc_selector*, _MonoMethod**, unsigned int) (registrar.m:106)
18  Provider.iOS                    0x000000010188065c -[__MonoMac_NSAsyncActionDispatcher xamarinApplySelector] (registrar.m:7022)
19  Foundation                      0x000000018599e4cc __NSThreadPerformPerform + 340
20  CoreFoundation                  0x0000000184e5942c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
21  CoreFoundation                  0x0000000184e58d9c __CFRunLoopDoSources0 + 540
22  CoreFoundation                  0x0000000184e569a8 __CFRunLoopRun + 744
23  CoreFoundation                  0x0000000184d86da4 CFRunLoopRunSpecific + 424
24  GraphicsServices                0x00000001867f0074 GSEventRunModal + 100
25  UIKit                           0x000000018b03a058 UIApplicationMain + 208
26  Provider.iOS                    0x0000000100cc33d4 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr (/<unknown>:1)
27  Provider.iOS                    0x0000000100c6bc6c UIKit_UIApplication_Main_string___intptr_intptr (UIApplication.cs:79)
28  Provider.iOS                    0x0000000100c6bc2c UIKit_UIApplication_Main_string___string_string (UIApplication.cs:63)
29  Provider.iOS                    0x0000000100041b44 Provider_iOS_Application_Main_string__ (Main.cs:17)
30  Provider.iOS                    0x00000001002f3ac4 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 244
31  Provider.iOS                    0x0000000101938cfc mono_jit_runtime_invoke (mini-runtime.c:2510)
32  Provider.iOS                    0x00000001019b1b58 do_runtime_invoke (object.c:2860)
33  Provider.iOS                    0x00000001019b4d7c do_exec_main_checked (object.c:4681)
34  Provider.iOS                    0x000000010191d558 mono_jit_exec (driver.g.c:1037)
35  Provider.iOS                    0x0000000101a7e1ec xamarin_main (monotouch-main.m:480)
36  Provider.iOS                    0x00000001018a6310 main (main.m:173)
37  libdyld.dylib                   0x0000000183d9559c start + 4

Does anyone have any idea what this crash report refer to?

Body:
It's hard to say, but I may suggest that the root cause of your app crash could be the result of memory leaks due to the fact that your app may allocate too much memory and then perhaps does not correctly release the memory after usage. From that log, you can't get more information. My suggestion will be to connect a device and build on it. Building on simulator may not work because desktop has significantly more available ram than a mobile device.

If it's not possible to reproduce on a connected device (sometimes that may happen). You can use one hack to get more information about the crash from a device. Since all your code is executable throw mono runtime, you can easily catch lots of crashed my wrapping your UIaaplication.Main function into a try-catch block, and save the exception string somewhere on the device.

in Main.cs

public class Application {
    static void Main(string[] args) {
        try {
            UIApplication.Main(args: args, principalClassName: null, delegateClassName: typeof(AppDelegate).Name);
        } catch (Exception e) {
            // save e.ToString() somewhere
        }
    }
}


问:
Writing string with special chars to file in Ruby
I am using a Ruby script to process some text files. Basically, reading each line, sometimes doing some manipulation and then writing the line to an output text file.

This works well, except when the original line has a new line \n character in there. In this case, the script will "execute" the new line instead of copying it literally.

edit

```<code># output code:
modified_line # => "hello\nworld"

output.write(modified_line) # will output
hello
world

# output I am looking for:
hello\nworld
</code>```

How can I make Ruby just write the string variable verbatim, ignoring any included special chars?

答:
Assuming you do some file.write(string_variable).

Use would want to use String#dump which escapes all special characters. Like it says in the documentation:

Produces a version of str with all nonprinting characters replaced by
  \nnn notation and all special characters escaped.

So your code would look like

```<code>file.write(string_variable.dump)
</code>```

Body:
I am using a Ruby script to process some text files. Basically, reading each line, sometimes doing some manipulation and then writing the line to an output text file.

This works well, except when the original line has a new line \n character in there. In this case, the script will "execute" the new line instead of copying it literally.

edit

# output code:
modified_line # => "hello\nworld"

output.write(modified_line) # will output
hello
world

# output I am looking for:
hello\nworld

How can I make Ruby just write the string variable verbatim, ignoring any included special chars?

Body:
Assuming you do some file.write(string_variable).

Use would want to use String#dump which escapes all special characters. Like it says in the documentation:

Produces a version of str with all nonprinting characters replaced by
  \nnn notation and all special characters escaped.

So your code would look like

file.write(string_variable.dump)


问:
django - how to restrict number of pages an unauthenticated user can view
I am building a website using django (1.10). I want to restrict the number of pages that an unauthorised person (i.e. a user that is not logged in), can view.

The desired behaviour is that after visiting N different pages, the user is directed to a specific page.

In other web platforms I have used (Symfony), there is a way of doing this by writing custom "filters" and session variables - I think django provides similar affordances via it's concept of midleware - however, not sure if this is the way to go, to implement this requirement.

How best may I implement this requirement (unauthorised user directed to a custom page after viewing N different pages), using the django framework?

答:
Yes, a middleware is the right place. Middleware runs on every request and it has access to the current request and session, and the user object if the middleware is run after SessionMiddleware and AuthenticationMiddleware (depends on the order in the MIDDLEWARE_CLASSES setting).

You can save the number of pages seen on the setting, and if it's over the limit then return a HttpResponseRedirect from the middleware.

Of course the user can always throw away his session cookie or start an incognito browser tab, that can't be helped.

See the middleware documentation: https://docs.djangoproject.com/en/1.11/topics/http/middleware/ .


问:
MVC EF - System.Data.Entity.Infrastructure.DbUpdateException
I have two models :
UserProfile

```<code>public class UserProfile
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    public virtual ICollection<UserPost> UserPost { get; set; }
}
</code>```

UserPost:

```<code>public class UserPost
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public string Id { get; set; }
   public string PostTitle { get; set; }
   public virtual UserProfile UserProfile { get; set; }
   public string Contents { get; set; }
}
</code>```

UserProfile has a one-to-one relationship with AspNetUser.

UserProfile has a one-to-many relationship with UserPost.

When I'm adding UserPost to the database in the Create method in my controller I get a System.Data.Entity.Infrastructure.DbUpdateException

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize]
    public ActionResult Create([Bind(Include = "PostTitle, Content")] UserPost post)
    {
        if (ModelState.IsValid)
        {

            UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var user = UserManager.FindById(User.Identity.GetUserId());
            post.UserProfile = user.UserProfile;
            db.UserPosts.Add(post);
            db.SaveChanges();//error here
            return RedirectToAction("Index");
        }

        return View(post);
    }
</code>```

System.Data.Entity.Infrastructure.DbUpdateException occurred
    HResult=0x80131501
    Message=An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

Inner Exception 1: UpdateException: An error occurred while updating
  the entries. See the inner exception for details.

Inner Exception 2: SqlException: Cannot insert the value NULL into
  column 'Id', table 'aspnet-project12017.dbo.UserPosts'; column does
  not allow nulls. INSERT fails. The statement has been terminated.

答:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] means that the column marked with such attribute expected having auto-generated value from DBMS, and as a general convention that EF treats string & uniqueidentifier (GUID) columns as non auto-incremented, hence those columns value must be assigned in another way (i.e. by constructor assignment).

Common approach to solve null problem for primary key auto-incremented identity column is simply set it to numeric data type (e.g. int):

```<code>public class UserPost
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Id { get; set; } // change to numeric data type
   public string PostTitle { get; set; }
   public virtual UserProfile UserProfile { get; set; }
   public string Contents { get; set; }
}
</code>```

Then, when performing migrations, do these steps:

Sometimes EF expects by default that you're trying to insert into identity column. If this happens, set StoreGeneratedPattern.None & DatabaseGenerationOption.None to UserPost.Id temporarily:

```<code>protected void OnModelCreating(DbModelBuilder modelBuilder)
{
    // other entities

    modelBuilder.Entity<UserPost>()
       .HasKey(p => p.Id)
       .Property(p => p.Id)
       .StoreGeneratedPattern = StoreGeneratedPattern.None;

   // other entities
}
</code>```

Ensure that the model has been modified to include actual Id property (try to delete UserPost table in DB when required).

Run migration through Package Manager Console as this:

```<code>Add-Migration "Set Id as Identity Specification"
</code>```

In a generated class from DbMigration you will see two methods: Up() and Down(). Modify Up() part to set int datatype there (and re-run migration process when required):

```<code>public override void Up()
{
    CreateTable(
          "dbo.UserPost",
          c => new
          {
              Id = c.Int(nullable: false, identity: true),
              PostTitle = c.String(),
              Contents = c.String(),
          })
          .PrimaryKey(t => t.Id);
}
</code>```

If you still want string Id column as primary key for UserPost, you need to set it as [DatabaseGenerated(DatabaseGeneratedOption.None)] and assign values manually from class constructor (note that generated values must be unique at all or EF will tell you "cannot insert duplicate key in object"):

```<code>public class UserPost
{
    public UserPost()
    {
        Id = [[autogenerated value here]];
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id { get; set; }

    // other properties
}
</code>```

Related issues:

MVC5 EF6 Seed Method: Cannot insert NULL into column 'Id' table AspNetUsers

Cannot insert the value NULL into column 'Id' (Database first)

Code first - Cannot insert the value NULL into column 'Id'

Entity Framework Cannot insert the value NULL into column Identity Specification set to No

Body:
I have two models :
UserProfile

public class UserProfile
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    public virtual ICollection<UserPost> UserPost { get; set; }
}

UserPost:

public class UserPost
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public string Id { get; set; }
   public string PostTitle { get; set; }
   public virtual UserProfile UserProfile { get; set; }
   public string Contents { get; set; }
}

UserProfile has a one-to-one relationship with AspNetUser.

UserProfile has a one-to-many relationship with UserPost.

When I'm adding UserPost to the database in the Create method in my controller I get a System.Data.Entity.Infrastructure.DbUpdateException

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize]
    public ActionResult Create([Bind(Include = "PostTitle, Content")] UserPost post)
    {
        if (ModelState.IsValid)
        {

            UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var user = UserManager.FindById(User.Identity.GetUserId());
            post.UserProfile = user.UserProfile;
            db.UserPosts.Add(post);
            db.SaveChanges();//error here
            return RedirectToAction("Index");
        }

        return View(post);
    }

System.Data.Entity.Infrastructure.DbUpdateException occurred
    HResult=0x80131501
    Message=An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

Inner Exception 1: UpdateException: An error occurred while updating
  the entries. See the inner exception for details.

Inner Exception 2: SqlException: Cannot insert the value NULL into
  column 'Id', table 'aspnet-project12017.dbo.UserPosts'; column does
  not allow nulls. INSERT fails. The statement has been terminated.

Body:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] means that the column marked with such attribute expected having auto-generated value from DBMS, and as a general convention that EF treats string & uniqueidentifier (GUID) columns as non auto-incremented, hence those columns value must be assigned in another way (i.e. by constructor assignment).

Common approach to solve null problem for primary key auto-incremented identity column is simply set it to numeric data type (e.g. int):

public class UserPost
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int Id { get; set; } // change to numeric data type
   public string PostTitle { get; set; }
   public virtual UserProfile UserProfile { get; set; }
   public string Contents { get; set; }
}

Then, when performing migrations, do these steps:

Sometimes EF expects by default that you're trying to insert into identity column. If this happens, set StoreGeneratedPattern.None & DatabaseGenerationOption.None to UserPost.Id temporarily:

protected void OnModelCreating(DbModelBuilder modelBuilder)
{
    // other entities

    modelBuilder.Entity<UserPost>()
       .HasKey(p => p.Id)
       .Property(p => p.Id)
       .StoreGeneratedPattern = StoreGeneratedPattern.None;

   // other entities
}

Ensure that the model has been modified to include actual Id property (try to delete UserPost table in DB when required).

Run migration through Package Manager Console as this:

Add-Migration "Set Id as Identity Specification"

In a generated class from DbMigration you will see two methods: Up() and Down(). Modify Up() part to set int datatype there (and re-run migration process when required):

public override void Up()
{
    CreateTable(
          "dbo.UserPost",
          c => new
          {
              Id = c.Int(nullable: false, identity: true),
              PostTitle = c.String(),
              Contents = c.String(),
          })
          .PrimaryKey(t => t.Id);
}

If you still want string Id column as primary key for UserPost, you need to set it as [DatabaseGenerated(DatabaseGeneratedOption.None)] and assign values manually from class constructor (note that generated values must be unique at all or EF will tell you "cannot insert duplicate key in object"):

public class UserPost
{
    public UserPost()
    {
        Id = [[autogenerated value here]];
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id { get; set; }

    // other properties
}

Related issues:

MVC5 EF6 Seed Method: Cannot insert NULL into column 'Id' table AspNetUsers

Cannot insert the value NULL into column 'Id' (Database first)

Code first - Cannot insert the value NULL into column 'Id'

Entity Framework Cannot insert the value NULL into column Identity Specification set to No


问:
Android, Facebook SDK and Single Sign On: Either my App fails with "invalid_key" or Facebook App fails
In November 2010 Facebook introduced Single-Sign-On for Android-Applications. Supposedly you can just login into your Facebook-App, and dont need to login again in your other applications, if you connect with Facebook-Login. However I experienced, that one of the Applications, either the Facebook-App, or my App fails with the login.

If the Facebook-App is installed, and I'm logged in, I cant log into my onw App, but instead get an error

```<code>"invalid_key"
</code>```

If on the other hand, I first install my app, I'm logged into my App with Facebook-Login, and afterwards I install the Facebook App and try to logon their, the Facebook App fails and I cant login. Others seem to have the same issue: https://github.com/facebook/facebook-android-sdk/issues/closed#issue/140

Is there anybody out there you ran into the same issue and solved it?

答: Are the set of permissions same in both the application?</p>

Body:
In November 2010 Facebook introduced Single-Sign-On for Android-Applications. Supposedly you can just login into your Facebook-App, and dont need to login again in your other applications, if you connect with Facebook-Login. However I experienced, that one of the Applications, either the Facebook-App, or my App fails with the login.

If the Facebook-App is installed, and I'm logged in, I cant log into my onw App, but instead get an error

"invalid_key"

If on the other hand, I first install my app, I'm logged into my App with Facebook-Login, and afterwards I install the Facebook App and try to logon their, the Facebook App fails and I cant login. Others seem to have the same issue: https://github.com/facebook/facebook-android-sdk/issues/closed#issue/140

Is there anybody out there you ran into the same issue and solved it?


问:
FFmpeg: how to produce MP4 CENC (Common Encryption) videos
What is the correct syntax to do CENC encryption with ffmpeg?

The ffmpeg 3.0 release notes include "Common Encryption (CENC) MP4 encoding and decoding support", and the files libavformat/movenccenc.h and  libavformat/movenccenc.c seem to include everything needed to encrypt MP4 files according to the Common Encryption standard.

However, I can't find any documentation on this topic in the ffmpeg manual pages.

Regards

答:
Running ffmpeg -h muxer=mp4 will produce all the available options for the MP4 muxer, among which are

```<code>-encryption_scheme <string>     E....... Configures the encryption scheme, allowed values are none, cenc-aes-ctr
-encryption_key    <binary>     E....... The media encryption key (hex)
-encryption_kid    <binary>     E....... The media encryption key identifier (hex)
</code>```

These options and their values should be placed after all the inputs and before the output filename.

Body:
Running ffmpeg -h muxer=mp4 will produce all the available options for the MP4 muxer, among which are

-encryption_scheme <string>     E....... Configures the encryption scheme, allowed values are none, cenc-aes-ctr
-encryption_key    <binary>     E....... The media encryption key (hex)
-encryption_kid    <binary>     E....... The media encryption key identifier (hex)

These options and their values should be placed after all the inputs and before the output filename.


问:
Can the HTML5 Audio Player be configured to persist through page loads?
Apologies if this is a bit vague but I'm wondering if it would be possible to have the HTML5 audio player continue playing while navigating through various pages on the same site, rather than stopping and starting with each page load.</p>

答:
Not really. When you leave a page, everything gets torn down. You can store things in local or session storage, but DOM components, open connections, the in-memory data your were working with etc. get lost.

Your realistic option is to design a SPA where a user's navigation event does not correspond to the browser's one, and, in the ideal case, there is no browser navigation event. This way the audio player will be active for as long as the user is on your website.


问:
How can I display Firebase data on refreshing while using ion-refresher?
I have some asynchronous data in my Firbase database.I have used ion-refresher in the .html file. But when I am adding new data to firebase database,then the data gets loaded there and is simultaneously displayed in the view.I cannot make use of ion-refresher.How can I make so?

Code:

.html

```<code><ion-content padding>
   <ion-refresher (ionRefresh)="doRefresh($event)">
      <ion-refresher-content refreshingText="Refreshing...">
      </ion-refresher-content>
      </ion-refresher>
  <ion-list>

      <ion-item *ngFor="let data of datas | async" class="pqr">
        <ion-thumbnail item-left>
          <img src="assets/image/{{data.imageName}}">
        </ion-thumbnail>
        {{data.Comp}}<br> {{data.Demand}}
        <br>
        <p> {{data.Desig}}<br></p>
        {{data.Place}}<br> {{data.when}}
        <br>
      </ion-item>
</code>```

.ts

```<code>export class HomePage implements OnInit {
  datas: FirebaseListObservable<any[]>;
  // datas: FirebaseListObservable<Item[]>;

  constructor(public navCtrl: NavController, public authData: AuthData, public af: AngularFire) {
    //this.loadData();
  }
  ngOnInit() {
    this.datas = this.af.database.list('/datas');
  }

   doRefresh(refresher) {
   console.log('Begin async operation', refresher);

  setTimeout(() => {
  console.log('Async operation has ended');
      refresher.complete();
    }, 2000);
   }
</code>```

答:
I don't know what data you need to load.But here is how to do your thing.
You if you call whatever your data loading methods inside the constructor ior ngOnInit() it may load the data when you load the page.

To use ion refresher just call whatever data loading method inside the refresher method.

```<code>doRefresh(refresher) {
   console.log('Begin async operation', refresher);

  setTimeout(() => {

  loaddata();             //<-call your data load method here

  console.log('Async operation has ended');
      refresher.complete();
    }, 2000);
   }
</code>```

also look at here  https://alligator.io/ionic/refresher-ionic/

Body:
I have some asynchronous data in my Firbase database.I have used ion-refresher in the .html file. But when I am adding new data to firebase database,then the data gets loaded there and is simultaneously displayed in the view.I cannot make use of ion-refresher.How can I make so?

Code:

.html

<ion-content padding>
   <ion-refresher (ionRefresh)="doRefresh($event)">
      <ion-refresher-content refreshingText="Refreshing...">
      </ion-refresher-content>
      </ion-refresher>
  <ion-list>

      <ion-item *ngFor="let data of datas | async" class="pqr">
        <ion-thumbnail item-left>

        </ion-thumbnail>
        {{data.Comp}}
 {{data.Demand}}

 {{data.Desig}}

        {{data.Place}}
 {{data.when}}

      </ion-item>

.ts

export class HomePage implements OnInit {
  datas: FirebaseListObservable<any[]>;
  // datas: FirebaseListObservable<Item[]>;

  constructor(public navCtrl: NavController, public authData: AuthData, public af: AngularFire) {
    //this.loadData();
  }
  ngOnInit() {
    this.datas = this.af.database.list('/datas');
  }

   doRefresh(refresher) {
   console.log('Begin async operation', refresher);

  setTimeout(() => {
  console.log('Async operation has ended');
      refresher.complete();
    }, 2000);
   }

Body:
I don't know what data you need to load.But here is how to do your thing.
You if you call whatever your data loading methods inside the constructor ior ngOnInit() it may load the data when you load the page.

To use ion refresher just call whatever data loading method inside the refresher method.

doRefresh(refresher) {
   console.log('Begin async operation', refresher);

  setTimeout(() => {

  loaddata();             //<-call your data load method here

  console.log('Async operation has ended');
      refresher.complete();
    }, 2000);
   }

also look at here  https://alligator.io/ionic/refresher-ionic/


问:
How to session maintain in spring and hibernate Framework
I have small doubt about how to maintain session in Hibernate and spring framework. If using session time is defined in web.xml. That is also not use in my application. If progresses application while session is timeout. If you any one known about. Can you give any guidelines for me.</p>

答:
Hibernate has nothing to do with sessions unless you are persisting them to the database.

Spring does not have much to do with sessions either, it's mostly your Servlet container does the job, which is, as you said - web.xml.

However when you are using Spring Boot Web with @SpringMvcApplication and @EnableAutoConfiguration ( possibly made those up :) - you will use the embedded container with automatic & default Spring configuration, which you then should be looking up in Spring Boot reference guide


问:
How to find local maximum using wxmaxima
I have this; (x)=-(x^3+6*x^2-18*x)/(4*(x^2+2));
Have differentiated and tried to solve for x but get too many answers.
graph</p>

Body:
Use realroots to discard complex roots:

y:-(x^3+6*x^2-18*x)/(4*(x^2+2));
realroots(diff(y,x)=0),numer;
[x=-1.688117772340774,x=0.8158789575099945]


问:
Trying to remove the redundant code but unable to solve the issue, any assistance would be helpful
Following code creates a functional component with multiple arrays of object that I want to display in the UI, I am repeating a lot of code and I want to make it clean and remove any redundant code. The code works properly but the only issue is with refactoring the code and removing the redundant part.</p>
```<code>function About() {
    const title = "we are a team";
    // leadership array.
    const leadership = [
        {
            name: "abc",
            department: "abc",
            phone: "abc",
            email: "abc",
        },
        {
            name: "abc",
            department: "abc",
            phone: "abc",
            email: "abc",
        },
    ];

    // business array
    const business = [
        {
            name: "abc",
            department: "abc",
            email: "abc",
        },
        {
            name: "abc",
            department: "abc",
            email: "abc",
        },
    ];

    // mapping through the leadership array and displaying the content in the UI
    const row1 = leadership.map((row) => (
        <div className="column">
            <div className="card">
                <div className="container">
                    <h2>{row.name}</h2>
                    <p>{row.department}</p>
                    <p>{row.phone}</p>
                    <p>{row.email}</p>
                </div>
            </div>
        </div>
    ));

    // mapping through the leadership array and displaying the content in the UI
    const row2 = business.map((row) => (
        <div className="column">
            <div className="card">
                <div className="container">
                    <h2>{row.name}</h2>
                    <p>{row.department}</p>
                    <p>{row.email}</p>
                </div>
            </div>
        </div>
    ));

    // returning the content and rendering it in the UI
    return (
        <div className="home-component">
            <div className="home-content">
                <h1 style={stylesheader}> Meet the team </h1>
                <h2 style={stylehead}>{title}</h2>

                <h2 style={styles}> Leadership </h2>
                <div className="row" style={style1}>
                    {row1}
                </div>

                <h2 style={styles}> Business Development </h2>
                <div className="row" style={style1}>
                    {row2}
                </div>
            </div>
        </div>
    );
}

export default About;
</code>```

答:
You want to avoid repetition wherever possible, so in your code I would move each of the
 blocks into a simple function, such as:

```<code>h2Renderer(title, rowData) {
    return (
        <div>
            <h2 style={styles}>{ title }</h2>
            <div className="row" style={style1}>
              {
                rowData.map((row, index) => {
                    return (
                        <div key={ `h2row-${index}` } className="column">
                           <div className="card">
                              <div className="container">
                                  <h2>{row.name}</h2>
                                  <p>{row.department}</p>
                                  { row.phone ? <p>{row.phone}</p> : null }
                                  <p>{row.email}</p>
                              </div>
                            </div>
                        </div>
                    );
                });
              }
            </div>
        </div>
    );
}
</code>```

Since 'phone' seems to be optional, the "ternary expression" '{ row.phone ?
{row.phone}
 : null }' will add 'phone' if it is a property of the row object.

Call this h2Renderer() in your render function 'return' statement, for each set of rows, and also pass in the title:

```<code>return (
     <div className="home-component">
        <div className="home-header">
        <Header/>
        </div>
        <div className="home-content" >
            <h1 style={stylesheader}> Meet the team </h1>
            <h2 style={stylehead}>{title}</h2>
            { this.h2Renderer(" Leadership ", row1 ) }
            { this.h2Renderer(" Business Development ", row2 ) }
            { this.h2Renderer(" Algorithm Development ", row3 ) }
            { this.h2Renderer(" Software Development ", row4 ) }
        </div>
        <Footer/>
     </div>
    );
}
</code>```

Later on, I'm sure you can reduce the lines of code by passing in the arrays of data, and the 'title' headers as props to your component, and use the props in the h2Renderer instead of passing arguments.

ContentLicense: CC BY-SA 4.0

Body:
Following code creates a functional component with multiple arrays of object that I want to display in the UI, I am repeating a lot of code and I want to make it clean and remove any redundant code. The code works properly but the only issue is with refactoring the code and removing the redundant part.

function About() {
    const title = "we are a team";
    // leadership array.
    const leadership = [
        {
            name: "abc",
            department: "abc",
            phone: "abc",
            email: "abc",
        },
        {
            name: "abc",
            department: "abc",
            phone: "abc",
            email: "abc",
        },
    ];

    // business array
    const business = [
        {
            name: "abc",
            department: "abc",
            email: "abc",
        },
        {
            name: "abc",
            department: "abc",
            email: "abc",
        },
    ];

    // mapping through the leadership array and displaying the content in the UI
    const row1 = leadership.map((row) => (

{row.name}

{row.department}

{row.phone}

{row.email}

    ));

    // mapping through the leadership array and displaying the content in the UI
    const row2 = business.map((row) => (

{row.name}

{row.department}

{row.email}

    ));

    // returning the content and rendering it in the UI
    return (

 Meet the team

{title}

 Leadership

                    {row1}

 Business Development

                    {row2}

    );
}

export default About;

Body:
You want to avoid repetition wherever possible, so in your code I would move each of the <h2> blocks into a simple function, such as:

h2Renderer(title, rowData) {
    return (
        <div>
            <h2 style={styles}>{ title }</h2>
            <div className="row" style={style1}>
              {
                rowData.map((row, index) => {
                    return (
                        <div key={ `h2row-${index}` } className="column">
                           <div className="card">
                              <div className="container">
                                  <h2>{row.name}</h2>
                                  <p>{row.department}</p>
                                  { row.phone ? <p>{row.phone}</p> : null }
                                  <p>{row.email}</p>
                              </div>
                            </div>
                        </div>
                    );
                });
              }
            </div>
        </div>
    );
}

Since 'phone' seems to be optional, the "ternary expression" '{ row.phone ? <p>{row.phone}</p> : null }' will add 'phone' if it is a property of the row object.

Call this h2Renderer() in your render function 'return' statement, for each set of rows, and also pass in the title:

return (
     <div className="home-component">
        <div className="home-header">
        <Header/>
        </div>
        <div className="home-content" >
            <h1 style={stylesheader}> Meet the team </h1>
            <h2 style={stylehead}>{title}</h2>
            { this.h2Renderer(" Leadership ", row1 ) }
            { this.h2Renderer(" Business Development ", row2 ) }
            { this.h2Renderer(" Algorithm Development ", row3 ) }
            { this.h2Renderer(" Software Development ", row4 ) }
        </div>
        <Footer/>
     </div>
    );
}

Later on, I'm sure you can reduce the lines of code by passing in the arrays of data, and the 'title' headers as props to your component, and use the props in the h2Renderer instead of passing arguments.


问:
Javascript function remove from position in array
I have an array:

```<code>var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
</code>```

I need to remove each 3rd item from the array and add it to another array.

The final result should be:

```<code>var myArray = [12, 11 18, 30, 21, 18];

var secondArray = [13, 51, 20];
</code>```

How can i do that?

Body:
I have an array:

var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];

I need to remove each 3rd item from the array and add it to another array.

The final result should be:

var myArray = [12, 11 18, 30, 21, 18];

var secondArray = [13, 51, 20];

How can i do that?

Body:
var a = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var b = [ ];
var l = a.length;
for(i = 2; i < l; i += 2){
    b.push(a[i]);
    a.splice(i, 1);
    l--;
}
console.log("Array a: ", a);
console.log("Array b: ", b);