问:
Extracting raster values to point features with reduce regions. Error: "User memory limit exceeded"
I am very new to Earth Engine and Javascript so I wouldn't be surprised if the solution to my problem is extremely simple. Anyways, I've been trying to fix this in days and I'm not doing anyhow better.

I'm trying to get the cumulative cost distance between some areas of interest and some tide gauges in the coastal U.S. To do this, I first calculated the pixel cost based on a national elevation map. Then, I calculated the cumulative cost thanks to the built-in function cumulativeCost. That went all pretty well. Now I'm trying to extract the cumulative cost values at the position of the tide gauges. To do this, someone suggested me to use the reduceRegions method. I've tried the following code but unsuccessfully.

I'm going to post my whole code so that is replicable. Please note that the part with which I have a problem is the second one.

Thanks so much in advance.

```<code>// IMPORTS
var imageCollection =
ee.ImageCollection("users/brazzolanicoletta/sourceRasters"),
sourceVis = {"opacity":1,"bands":["b1"],"min":1,"max":1,"gamma":1},
DEMVis = {"opacity":1,"bands":
["elevation"],"min":-73.50744474674659,"max":374.555654458347,"gamma":1},
imageVisParam = {"opacity":1,"bands":
["elevation"],"min":-0.02534169006347656,"max":3.6601884765625,"palette":
["0345ff","000000"]},
imageVisParam2 = {"opacity":1,"bands":
["elevation"],"min":-0.02534169006347656,"max":3.6601884765625,"palette":
["0345ff","000000"]},
cosVisParam = {"opacity":1,"bands":
["cumulative_cost"],"max":4170.014060708561,"palette":
["ff0303","efff05","4eff05","002bff","ff01f7","000000"]},
imageVisParam3 = {"opacity":1,"bands":
["cumulative_cost"],"max":4028.1446098656247,"gamma":1};

//get IDs for images in image collection
var getID = function(image){ return image.set('ID', image.id());};
var okID = imageCollection.map(function(image) { return image.set('ID',
image.id());});

// Set general estethic parameters
var dem_vis = {bands:"elevation", min:0, max:0.05,
palette:"#0345ff,#000000"};
var cost_vis = {bands:"cumulative_cost", min:0, max:10000,
palette:"ff0303,efff05,4eff05,002bff,ff01f7,000000"}

// PART 1: Cumulative Cost based on source rasters
 //import elevation map
var dem = ee.Image('USGS/NED');

// pixel cost calculation
var elThreshold = ee.Number(5); //set elevation threshold
var subDEM = dem.updateMask(dem.lt(elThreshold)); //mask pixel above
elevation threshold
var costDEM = (subDEM.add(30)).divide(1000); //calculate the cost of each
pixel (height + width pixel (30m)) in km

// Add DEM to the map
Map.addLayer(costDEM, dem_vis, "SRTM");

// Cumulative cost
var calcCumCost = function(img) {
return costDEM.cumulativeCost({
source:img,
maxDistance:1E5});
}; //write a function that perform the cumulative cost calculation for each
image given the cost of the pixel

var demCost = ee.ImageCollection(okID.map(calcCumCost)); // caulcuate
cumulative cost for each source raster in the image collection

// PART 2 - Reduce Region: extract cumulative cost for tide gauges

var tideGauges =
ee.FeatureCollection('ft:1e1ik7ZklKbRSRVS50Ml_prHBTZ0WbNgW73fw7Ald');
//import fusion table of tide gauges

// WORK IN PROGRESS
// Empty Collection to fill
var ft = ee.FeatureCollection(ee.List([]));

// function that extract values from cumulative cost rasters and reduce it
for points region
var fill = function(img) {
 // gets the values for the points in the current img
var ft2 = img.reduceRegions(tideGauges, ee.Reducer.first(),30);
// set ID
var ID = ee.Feature(null, {'id':img.id()});

// writes the ID in each feature
 var ft3 = ft2.map(function(f){return f.set("id", ID)});
// merges the FeatureCollections
return ft.merge(ft3);
};

// Apply the function to each image in the ImageCollection
var newft = ee.FeatureCollection(demCost.map(fill));
print(newft, 'Potentially: region-reduced cost');
</code>```

答: The maxDistance on your cumulativeCost function translates into a neighborhood of 3000 pixels (at 30m), which means each tile needs to bring in a 44 million neighbor pixels, which is just too much memory.  You're going to have to lower the maxDistance or increase the scale of the reduceRegion.</p>

Body:
I am very new to Earth Engine and Javascript so I wouldn't be surprised if the solution to my problem is extremely simple. Anyways, I've been trying to fix this in days and I'm not doing anyhow better.

I'm trying to get the cumulative cost distance between some areas of interest and some tide gauges in the coastal U.S. To do this, I first calculated the pixel cost based on a national elevation map. Then, I calculated the cumulative cost thanks to the built-in function cumulativeCost. That went all pretty well. Now I'm trying to extract the cumulative cost values at the position of the tide gauges. To do this, someone suggested me to use the reduceRegions method. I've tried the following code but unsuccessfully.

I'm going to post my whole code so that is replicable. Please note that the part with which I have a problem is the second one.

Thanks so much in advance.

// IMPORTS
var imageCollection =
ee.ImageCollection("users/brazzolanicoletta/sourceRasters"),
sourceVis = {"opacity":1,"bands":["b1"],"min":1,"max":1,"gamma":1},
DEMVis = {"opacity":1,"bands":
["elevation"],"min":-73.50744474674659,"max":374.555654458347,"gamma":1},
imageVisParam = {"opacity":1,"bands":
["elevation"],"min":-0.02534169006347656,"max":3.6601884765625,"palette":
["0345ff","000000"]},
imageVisParam2 = {"opacity":1,"bands":
["elevation"],"min":-0.02534169006347656,"max":3.6601884765625,"palette":
["0345ff","000000"]},
cosVisParam = {"opacity":1,"bands":
["cumulative_cost"],"max":4170.014060708561,"palette":
["ff0303","efff05","4eff05","002bff","ff01f7","000000"]},
imageVisParam3 = {"opacity":1,"bands":
["cumulative_cost"],"max":4028.1446098656247,"gamma":1};

//get IDs for images in image collection
var getID = function(image){ return image.set('ID', image.id());};
var okID = imageCollection.map(function(image) { return image.set('ID',
image.id());});

// Set general estethic parameters
var dem_vis = {bands:"elevation", min:0, max:0.05,
palette:"#0345ff,#000000"};
var cost_vis = {bands:"cumulative_cost", min:0, max:10000,
palette:"ff0303,efff05,4eff05,002bff,ff01f7,000000"}

// PART 1: Cumulative Cost based on source rasters
 //import elevation map
var dem = ee.Image('USGS/NED');

// pixel cost calculation
var elThreshold = ee.Number(5); //set elevation threshold
var subDEM = dem.updateMask(dem.lt(elThreshold)); //mask pixel above
elevation threshold
var costDEM = (subDEM.add(30)).divide(1000); //calculate the cost of each
pixel (height + width pixel (30m)) in km

// Add DEM to the map
Map.addLayer(costDEM, dem_vis, "SRTM");

// Cumulative cost
var calcCumCost = function(img) {
return costDEM.cumulativeCost({
source:img,
maxDistance:1E5});
}; //write a function that perform the cumulative cost calculation for each
image given the cost of the pixel

var demCost = ee.ImageCollection(okID.map(calcCumCost)); // caulcuate
cumulative cost for each source raster in the image collection

// PART 2 - Reduce Region: extract cumulative cost for tide gauges

var tideGauges =
ee.FeatureCollection('ft:1e1ik7ZklKbRSRVS50Ml_prHBTZ0WbNgW73fw7Ald');
//import fusion table of tide gauges

// WORK IN PROGRESS
// Empty Collection to fill
var ft = ee.FeatureCollection(ee.List([]));

// function that extract values from cumulative cost rasters and reduce it
for points region
var fill = function(img) {
 // gets the values for the points in the current img
var ft2 = img.reduceRegions(tideGauges, ee.Reducer.first(),30);
// set ID
var ID = ee.Feature(null, {'id':img.id()});

// writes the ID in each feature
 var ft3 = ft2.map(function(f){return f.set("id", ID)});
// merges the FeatureCollections
return ft.merge(ft3);
};

// Apply the function to each image in the ImageCollection
var newft = ee.FeatureCollection(demCost.map(fill));
print(newft, 'Potentially: region-reduced cost');


来源: stackexchange

问:
create a trigger a student is not taking repeat course(mysql)
I am using mysql to do a student elective system, register system has a data table, the table field is the sno (student  id) and cno (course id), how do I create a trigger in mysql to prevent students choose to repeat courses?</p>

答:
Set the register table with student id and course id together as primary key. If you can avoid trigger it's easier this way.

If you want to go for the trigger:

```<code>delimiter //
drop trigger if exists limitCoursesTrigger //
create trigger limitCoursesTrigger before insert on register_table
for each row
begin
    declare msg varchar(128);
    if exists(select * from register_table where studentid=new.studentid and courseid=new.courseid)
    then
        set msg = concat('Error: The student has already registered for this course !');
        signal sqlstate '45000' set message_text = msg;
    end if;
end //
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Set the register table with student id and course id together as primary key. If you can avoid trigger it's easier this way.

If you want to go for the trigger:

delimiter //
drop trigger if exists limitCoursesTrigger //
create trigger limitCoursesTrigger before insert on register_table
for each row
begin
    declare msg varchar(128);
    if exists(select * from register_table where studentid=new.studentid and courseid=new.courseid)
    then
        set msg = concat('Error: The student has already registered for this course !');
        signal sqlstate '45000' set message_text = msg;
    end if;
end //


问:
How do I filter rows of an array so that only records with a particular value are displayed?
Imagine I am running 2 queries each one against a different database.

The query result from source #1 will be stored in an array.
The query result from source #2 will also be stored in an array.

Source #2 records will contain a foreign key that may or may not match up with particular records in an ID field in source #1.

So if I were to loop through source #1 and then I wanted to display only the source #2 records that matched the ID of source #1 is there a handy command within PHP that will allow me to get the filtered results that I could run once each time I ran the loop.

What I would like to avoid is having a loop within a loop to check the result before determining if it should be displayed (hopefully a built in filter command if available will have less overhead).

Any suggestions on commands that filter an array within PHP?

答: Sounds like a job for array_intersect.</p>

ContentLicense: CC BY-SA 2.5

Body: Sounds like a job for array_intersect.


问:
How to ignore unpacked parts of a tuple as argument of a lambda?
In Python, by convention, the underscore (_) is often used to throw away parts of an unpacked tuple, like so

```<code>>>> tup = (1,2,3)
>>> meaningfulVariableName,_,_ = tup
>>> meaningfulVariableName
1
</code>```

I'm trying to do the same for a tuple argument of a lambda. It seems unfair that it can only be done with 2-tuples...

```<code>>>> map(lambda (meaningfulVariableName,_): meaningfulVariableName*2, [(1,10), (2,20), (3,30)]) # This is fine
[2, 4, 6]

>>> map(lambda (meaningfulVariableName,_,_): meaningfulVariableName*2, [(1,10,100), (2,20,200), (3,30,300)]) # But I need this!
SyntaxError: duplicate argument '_' in function definition (<pyshell#24>, line 1)
</code>```

Any ideas why, and what the best way to achieve this is?

答:
As it is in the comments, just use stared arguments
to throw an remaining arguments in "_":

```<code>lambda x, *_: x*2
</code>```

If you were using these in a map statement, as Python does not map each item in a tuple to a different parameter, you could use itertools.starmap, that does that:

```<code>from itertools import starmap
result = map(lambda x, *_: x, [(0,1,2),])
</code>```

But there is no equivalent to that on the key parameter to sort or sorted.

If you won't be using arguments in the middle of the tuple,
just number those:

```<code>lambda x, _1, _2, _3, w: x*2 + w
</code>```

If you get a complaint from some linter tool about the parameters not being used: the purpose of the linter is to suggest mor readable code. My personal preference is not to let that to be in the way of practicity, and if this happens, I just turn off the linter for that line of code, without a second thought.

Otherwise, you will really have to do the "beautiful" thing - just use good sense if it is to please you and your team, or solely to please the linter. In this case, it is to write a full fledged function, and pretend
to consume the unused arguments.

```<code>def my_otherwise_lambda(x, unused_1, unused_2, w):
     """My make linter-happy docstring here"""
     unused_1, unused_2  # Use the unused variables
     return 2 * x + w
</code>```

Short of having a problem with the linter, is the purpose is to have the lambda parameter readable, then habing a full-fledged function is the recomended anyway. lambda was really close of being stripped of the language in v. 3.0, in order to commit to readability.

And last, but not least, if the semantics of the value in your tuples is that meaningful, maybe you should consider using a class to hold the values in there. In that way you could just pass the instances of that class to the lambda funcion and check the values bytheir respective names.

Namedtuple is one that would work well:
from collections import namedtuple

```<code>vector = namedtuple("vector", "x y z")

mydata = [(1,10,100), (2,20,200), (3,30,300)]
mydata = [vector(*v) for v in mydata]

sorted_data = sorted(mydata, lambda v: v.x * 2)
</code>```

Body:
In Python, by convention, the underscore (_) is often used to throw away parts of an unpacked tuple, like so

>>> tup = (1,2,3)
>>> meaningfulVariableName,_,_ = tup
>>> meaningfulVariableName
1

I'm trying to do the same for a tuple argument of a lambda. It seems unfair that it can only be done with 2-tuples...

>>> map(lambda (meaningfulVariableName,_): meaningfulVariableName*2, [(1,10), (2,20), (3,30)]) # This is fine
[2, 4, 6]

>>> map(lambda (meaningfulVariableName,_,_): meaningfulVariableName*2, [(1,10,100), (2,20,200), (3,30,300)]) # But I need this!
SyntaxError: duplicate argument '_' in function definition (<pyshell#24>, line 1)

Any ideas why, and what the best way to achieve this is?

Body:
As it is in the comments, just use stared arguments
to throw an remaining arguments in "_":

lambda x, *_: x*2

If you were using these in a map statement, as Python does not map each item in a tuple to a different parameter, you could use itertools.starmap, that does that:

from itertools import starmap
result = map(lambda x, *_: x, [(0,1,2),])

But there is no equivalent to that on the key parameter to sort or sorted.

If you won't be using arguments in the middle of the tuple,
just number those:

lambda x, _1, _2, _3, w: x*2 + w

If you get a complaint from some linter tool about the parameters not being used: the purpose of the linter is to suggest mor readable code. My personal preference is not to let that to be in the way of practicity, and if this happens, I just turn off the linter for that line of code, without a second thought.

Otherwise, you will really have to do the "beautiful" thing - just use good sense if it is to please you and your team, or solely to please the linter. In this case, it is to write a full fledged function, and pretend
to consume the unused arguments.

def my_otherwise_lambda(x, unused_1, unused_2, w):
     """My make linter-happy docstring here"""
     unused_1, unused_2  # Use the unused variables
     return 2 * x + w

Short of having a problem with the linter, is the purpose is to have the lambda parameter readable, then habing a full-fledged function is the recomended anyway. lambda was really close of being stripped of the language in v. 3.0, in order to commit to readability.

And last, but not least, if the semantics of the value in your tuples is that meaningful, maybe you should consider using a class to hold the values in there. In that way you could just pass the instances of that class to the lambda funcion and check the values bytheir respective names.

Namedtuple is one that would work well:
from collections import namedtuple

vector = namedtuple("vector", "x y z")

mydata = [(1,10,100), (2,20,200), (3,30,300)]
mydata = [vector(*v) for v in mydata]

sorted_data = sorted(mydata, lambda v: v.x * 2)


问:
spray json: cannot convert to Array[myClass]
I am learning scala/spray json in my project and trying to convert an input json to an array of scala objects , but thats throwing the below error:

```<code>Error:(52, 43) not enough arguments for method convertTo: (implicit evidence$1: spray.json.JsonReader[Array[A$A57.this.myClass]])Array[A$A57.this.myClass].
Unspecified value parameter evidence$1.
lazy val output = ref.parseJson.convertTo[Array[myClass]];}
                                         ^
Error:(52, 43) Cannot find JsonReader or JsonFormat type class for Array[A$A57.this.myClass]
lazy val output = ref.parseJson.convertTo[Array[myClass]];}
</code>```

^

Here is my code snippet:

```<code>import spray.json.{JsArray, JsObject, _}
import spray.json.{JsArray, JsFalse, JsNumber, JsObject, JsString, JsTrue, JsValue, JsonFormat, _}

case class myClass (
                                                name: String,
                                                source: Map[String, Any],
                                                target: Map[String, Any])

trait myJsonProtocol extends DefaultJsonProtocol {
  implicit object AnyJsonFormat extends JsonFormat[Any] {
    def write(x: Any) = x match {
      case b: Boolean if b == true => JsTrue
      case b: Boolean if b == false => JsFalse
      case n: Int => JsNumber(n)
      case l: Long => JsNumber(l)
      case f: Float => JsNumber(f.toString)
      case d: Double => JsNumber(d.toString)
      case s: String => JsString(s)
      case a: Array[Any] => arrayFormat[Any].write(a)
      case m: Map[String, Any]@unchecked => mapFormat[String, Any].write(m)
      case x => serializationError("error Cannot determine object type " + x.getClass.getName)
    }

    def read(value: JsValue) = value match {
      case JsTrue => true
      case JsFalse => false
      case JsNumber(n) =>
        if (n.isValidInt) n.intValue()
        else if (n.isValidLong) n.longValue()
        else if (n.isDecimalFloat) n.floatValue()
        else if (n.isDecimalDouble) n.doubleValue()
        else n.intValue()
      case JsString(s) => s.toString
      case a: JsArray => arrayFormat[Any].read(a)
      case o: JsObject => mapFormat[String, Any].read(o)
      case x => deserializationError("error: Cannot deserialize " + x)
    }
  }

  implicit val myFormat = jsonFormat3(myClass.apply)
}

val ref = """[{
                           "name": "test-db",
                           "source": {
                           "mydbport": 50000
                           },
                           "target": {
                           "type": "newdb"
                           }
                           }]"""
val output = ref.parseJson.convertTo[Array[myClass]]
</code>```

I took the above code as reference from Serialize Map[String, Any] with spray json but not able to serialize Map[String,Any]
Let me know what is wrong with the above code.

Regards,
Gary

答:
For implicit methods to work, they need to be in scope from an instance of the class. As the trait is nowhere instantiated, this doesn't work. You could use an object instead of trait.

An example how you could get that to work is:

```<code>…
object myJsonProtocol extends DefaultJsonProtocol {
  implicit object AnyJsonFormat extends JsonFormat[Any] {
    …
  }

  implicit val myFormat = jsonFormat3(myClass.apply)
}

import myJsonProtocol.myFormat

val ref = """[{
                           "name": "test-db",
                           "source": {
                           "mydbport": 50000
                           },
                           "target": {
                           "type": "newdb"
                           }
                           }]"""
val output = ref.parseJson.convertTo[Array[myClass]]
</code>```

Body:
I am learning scala/spray json in my project and trying to convert an input json to an array of scala objects , but thats throwing the below error:

Error:(52, 43) not enough arguments for method convertTo: (implicit evidence$1: spray.json.JsonReader[Array[A$A57.this.myClass]])Array[A$A57.this.myClass].
Unspecified value parameter evidence$1.
lazy val output = ref.parseJson.convertTo[Array[myClass]];}
                                         ^
Error:(52, 43) Cannot find JsonReader or JsonFormat type class for Array[A$A57.this.myClass]
lazy val output = ref.parseJson.convertTo[Array[myClass]];}

^

Here is my code snippet:

import spray.json.{JsArray, JsObject, _}
import spray.json.{JsArray, JsFalse, JsNumber, JsObject, JsString, JsTrue, JsValue, JsonFormat, _}

case class myClass (
                                                name: String,
                                                source: Map[String, Any],
                                                target: Map[String, Any])

trait myJsonProtocol extends DefaultJsonProtocol {
  implicit object AnyJsonFormat extends JsonFormat[Any] {
    def write(x: Any) = x match {
      case b: Boolean if b == true => JsTrue
      case b: Boolean if b == false => JsFalse
      case n: Int => JsNumber(n)
      case l: Long => JsNumber(l)
      case f: Float => JsNumber(f.toString)
      case d: Double => JsNumber(d.toString)
      case s: String => JsString(s)
      case a: Array[Any] => arrayFormat[Any].write(a)
      case m: Map[String, Any]@unchecked => mapFormat[String, Any].write(m)
      case x => serializationError("error Cannot determine object type " + x.getClass.getName)
    }

    def read(value: JsValue) = value match {
      case JsTrue => true
      case JsFalse => false
      case JsNumber(n) =>
        if (n.isValidInt) n.intValue()
        else if (n.isValidLong) n.longValue()
        else if (n.isDecimalFloat) n.floatValue()
        else if (n.isDecimalDouble) n.doubleValue()
        else n.intValue()
      case JsString(s) => s.toString
      case a: JsArray => arrayFormat[Any].read(a)
      case o: JsObject => mapFormat[String, Any].read(o)
      case x => deserializationError("error: Cannot deserialize " + x)
    }
  }

  implicit val myFormat = jsonFormat3(myClass.apply)
}

val ref = """[{
                           "name": "test-db",
                           "source": {
                           "mydbport": 50000
                           },
                           "target": {
                           "type": "newdb"
                           }
                           }]"""
val output = ref.parseJson.convertTo[Array[myClass]]

I took the above code as reference from Serialize Map[String, Any] with spray json but not able to serialize Map[String,Any]
Let me know what is wrong with the above code.

Regards,
Gary

Body:
For implicit methods to work, they need to be in scope from an instance of the class. As the trait is nowhere instantiated, this doesn't work. You could use an object instead of trait.

An example how you could get that to work is:

…
object myJsonProtocol extends DefaultJsonProtocol {
  implicit object AnyJsonFormat extends JsonFormat[Any] {
    …
  }

  implicit val myFormat = jsonFormat3(myClass.apply)
}

import myJsonProtocol.myFormat

val ref = """[{
                           "name": "test-db",
                           "source": {
                           "mydbport": 50000
                           },
                           "target": {
                           "type": "newdb"
                           }
                           }]"""
val output = ref.parseJson.convertTo[Array[myClass]]


问:
Cstdint Missing Error When Installing Pydaedalus with PiP
I am working on an application which involves route finding (a completely different subject), but for testing I need example mazes to test on. A colleague suggested I use pydaedalus to generate large scale mazes in the format I need. I am using the following code to try and install the module:

```<code>$pip3.6 install pydaedalus
</code>```

This returns the following error:

```<code>-Wno-error=format-security
In file included from daedalus/_maze.cpp:467:
In file included from daedalus/wrapper.h:8:
daedalus/src/util.h:31:10: fatal error: 'cstdint' file not found
#include <cstdint>
             ^
1 error generated.
error: command '/usr/bin/clang' failed with exit status 1
</code>```

I have done some research and have found nothing which addresses this. I have also done some (limited) C++ development using cstdint, which has always worked.

I came across this question, but it appears to address a separate issue.

I am developing in OSX 10.10.5

Any help that you can provide is much appreciated!

答:
These compile errors are down to daedalus's requirement of the C++11 standard, which is sometimes a bit tricky to get working on Mac OS X.  One idea might be to check to make sure your Xcode is completely up to date.
 The page you linked also suggests to try linking against clang's standard library instead of the GCC standard library.  I'm not sure if this will work, or if it will give you linking errors on build or when you import daedalus into python, but you could give it a shot anyway:

```<code>CFLAGS='-stdlib=libc++' pip3.6 install pydaedalus
</code>```

Another idea would be to encourage pip to use the clang++ frontend, which your link also suggests might help.  You should be able to set this with the environment variable CXX (or, just possibly, CC).

```<code>CXX=clang++ pip3.6 install pydaedalus
</code>```

Try various combinations of those environment settings (e.g., CXX and CFLAGS), and hopefully something will work eventually.

Body:
I am working on an application which involves route finding (a completely different subject), but for testing I need example mazes to test on. A colleague suggested I use pydaedalus to generate large scale mazes in the format I need. I am using the following code to try and install the module:

$pip3.6 install pydaedalus

This returns the following error:

-Wno-error=format-security
In file included from daedalus/_maze.cpp:467:
In file included from daedalus/wrapper.h:8:
daedalus/src/util.h:31:10: fatal error: 'cstdint' file not found
#include <cstdint>
             ^
1 error generated.
error: command '/usr/bin/clang' failed with exit status 1

I have done some research and have found nothing which addresses this. I have also done some (limited) C++ development using cstdint, which has always worked.

I came across this question, but it appears to address a separate issue.

I am developing in OSX 10.10.5

Any help that you can provide is much appreciated!

Body:
These compile errors are down to daedalus's requirement of the C++11 standard, which is sometimes a bit tricky to get working on Mac OS X.  One idea might be to check to make sure your Xcode is completely up to date.
 The page you linked also suggests to try linking against clang's standard library instead of the GCC standard library.  I'm not sure if this will work, or if it will give you linking errors on build or when you import daedalus into python, but you could give it a shot anyway:

CFLAGS='-stdlib=libc++' pip3.6 install pydaedalus

Another idea would be to encourage pip to use the clang++ frontend, which your link also suggests might help.  You should be able to set this with the environment variable CXX (or, just possibly, CC).

CXX=clang++ pip3.6 install pydaedalus

Try various combinations of those environment settings (e.g., CXX and CFLAGS), and hopefully something will work eventually.


问:
Select of indices with wrong names in TypeORM
When I try to select a Person with .find() it does a select as it should. But the select has several fields in it i did not declare like like this. Example:
Field:

...
@Index("mail_blog_yn",["mail_blog_yn",])
...
export class person {
 ...
   @ManyToOne(type=>lov_jn_kz, mail_blog_yn=>mail_blog_yn.persons4)
   @JoinColumn()
   mail_blog_yn:lov_jn_kz;
 ...
}
```
<p>Info: The Entity was generated with TypeOrm-Model-Generator </p>
<p>The select looks like this in the log:</p>
<pre class="lang-sql prettyprint-override"><code>...
`person`.`mailBlogYnKeyTypKz` AS `person_mailBlogYnKeyTypKz`
...
</code>```

Here the code and the Connection setup:

typeorm.createConnection({
  type: "mysql",
  host: "localhost",
  port: 3306,
  username: Configuration.Database.user,
  password: Configuration.Database.password,
  database: Configuration.Database.database,
  entities: [
   ...
    person,
   ....
  ],
  synchronize: false,
  logging: true
}).then(connection => {
  const modelRepository: typeorm.Repository<person> =     connection.getRepository(person);
  modelRepository.find({
    "username" : 'x'
 }).then(( persons: person[]) => {
    console.log(JSON.stringify(persons));

  });
}).catch(error => console.log(error));
```

Here is the Person.ts and the complete SQL statement and some data about my table person.
Select-Problem.zip

答:
Yes, its a Issue of the generator. (See here: Typeorm Issue 1253 )

```<code>@ManyToOne(type=>lov_jn_kz, mail_blog_yn=>mail_blog_yn.persons4)
@JoinColumn()
mail_blog_yn:lov_jn_kz;
</code>```

should be:

```<code>@ManyToOne(type=>lov_jn_kz, mail_blog_yn=>mail_blog_yn.persons4)
@JoinColumn({ name: "mail_blog_yn" })
mail_blog_yn:lov_jn_kz;
</code>```

This fixes the issue but doing by hand is not an option for me, so typeorm-model-generator should definitely fix this.

Keep track of this issue on typeorm-model-generator: Issue #13

ContentLicense: CC BY-SA 4.0

Body:
When I try to select a Person with .find() it does a select as it should. But the select has several fields in it i did not declare like like this. Example:
Field:

...
@Index("mail_blog_yn",["mail_blog_yn",])
...
export class person {
 ...
   @ManyToOne(type=>lov_jn_kz, mail_blog_yn=>mail_blog_yn.persons4)
   @JoinColumn()
   mail_blog_yn:lov_jn_kz;
 ...
}

Info: The Entity was generated with TypeOrm-Model-Generator

The select looks like this in the log:

...
`person`.`mailBlogYnKeyTypKz` AS `person_mailBlogYnKeyTypKz`
...

Here the code and the Connection setup:

typeorm.createConnection({
  type: "mysql",
  host: "localhost",
  port: 3306,
  username: Configuration.Database.user,
  password: Configuration.Database.password,
  database: Configuration.Database.database,
  entities: [
   ...
    person,
   ....
  ],
  synchronize: false,
  logging: true
}).then(connection => {
  const modelRepository: typeorm.Repository<person> =     connection.getRepository(person);
  modelRepository.find({
    "username" : 'x'
 }).then(( persons: person[]) => {
    console.log(JSON.stringify(persons));

  });
}).catch(error => console.log(error));

Here is the Person.ts and the complete SQL statement and some data about my table person.
Select-Problem.zip

Body:
Yes, its a Issue of the generator. (See here: Typeorm Issue 1253 )

@ManyToOne(type=>lov_jn_kz, mail_blog_yn=>mail_blog_yn.persons4)
@JoinColumn()
mail_blog_yn:lov_jn_kz;

should be:

@ManyToOne(type=>lov_jn_kz, mail_blog_yn=>mail_blog_yn.persons4)
@JoinColumn({ name: "mail_blog_yn" })
mail_blog_yn:lov_jn_kz;

This fixes the issue but doing by hand is not an option for me, so typeorm-model-generator should definitely fix this.

Keep track of this issue on typeorm-model-generator: Issue #13


问:
Python: How to check off a checkbox with Browser splinter?
Once I add the following item to cart: http://www.supremenewyork.com/shop/accessories/wau85w4km/cxv3ybp1w and go to the  check out page: https://www.supremenewyork.com/checkout, there is a terms and conditions checkbox that I’m attempting to check off with Browser’s splinter but I’m not able to do so:

e.g. Tried the following but all encountered an error:

```<code>from splinter import Browser

browser = Browser("chrome")
browser.find_by_id('order_terms').click()
#Error: selenium.common.exceptions.WebDriverException: Message: unknown error

browser.check('order[terms]').click()
#Error: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

browser.find_by_name('order[terms]').click()
#Error: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
</code>```

What could I be doing wrong? And how can I go about checking the checkbox with the Browser splinter?

Thank you in advance and will be sure to upvote/accept answer

答:
Two major things to point out:

to avoid timing issues, you need to have "explicit waits" in your script - waiting for elements to be visible or present before proceeding to the next actions

this checkbox can and should be clicked by clicking the whole label element containing the input and other auxiliary elements

Here is the complete code:

```<code>from splinter import Browser

browser = Browser("chrome")
browser.visit("http://www.supremenewyork.com/shop/accessories/wau85w4km/cxv3ybp1w")
browser.wait_time = 10

try:
    browser.is_element_visible_by_css("input[name=commit]", 10)
    browser.find_by_css("input[name=commit]").first.click()

    browser.is_element_visible_by_css("a.checkout", 10)
    browser.find_by_css("a.checkout").first.click()

    browser.is_element_present_by_css("label.terms", 10)
    browser.find_by_css('label.terms').click()
finally:
    browser.quit()
</code>```

Here is a working code that goes to the main page, navigates to the third product in the scroller, adds it to cart, checks out and accepts the terms of use, time.sleep() at the end is just for you to see the result:

```<code>from splinter import Browser

browser = Browser("chrome")
browser.visit("http://www.supremenewyork.com/shop")
browser.wait_time = 10

try:
    # open a product
    browser.is_element_visible_by_css("#shop-scroller > li > a", 10)
    browser.find_by_css("#shop-scroller > li > a")[2].click()

    # add to cart
    browser.is_element_visible_by_css("input[name=commit]", 10)
    browser.find_by_css("input[name=commit]").first.click()

    # checkout
    browser.is_element_visible_by_css("a.checkout", 10)
    browser.find_by_css("a.checkout").first.click()

    # accept terms and conditions
    browser.is_element_present_by_css("label.terms", 10)
    browser.find_by_css('label.terms').click()

    import time
    time.sleep(10)
finally:
    browser.quit()
</code>```

Body:
Once I add the following item to cart: http://www.supremenewyork.com/shop/accessories/wau85w4km/cxv3ybp1w and go to the  check out page: https://www.supremenewyork.com/checkout, there is a terms and conditions checkbox that I’m attempting to check off with Browser’s splinter but I’m not able to do so:

e.g. Tried the following but all encountered an error:

from splinter import Browser

browser = Browser("chrome")
browser.find_by_id('order_terms').click()
#Error: selenium.common.exceptions.WebDriverException: Message: unknown error

browser.check('order[terms]').click()
#Error: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

browser.find_by_name('order[terms]').click()
#Error: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

What could I be doing wrong? And how can I go about checking the checkbox with the Browser splinter?

Thank you in advance and will be sure to upvote/accept answer

Body:
Two major things to point out:

to avoid timing issues, you need to have "explicit waits" in your script - waiting for elements to be visible or present before proceeding to the next actions

this checkbox can and should be clicked by clicking the whole label element containing the input and other auxiliary elements

Here is the complete code:

from splinter import Browser

browser = Browser("chrome")
browser.visit("http://www.supremenewyork.com/shop/accessories/wau85w4km/cxv3ybp1w")
browser.wait_time = 10

try:
    browser.is_element_visible_by_css("input[name=commit]", 10)
    browser.find_by_css("input[name=commit]").first.click()

    browser.is_element_visible_by_css("a.checkout", 10)
    browser.find_by_css("a.checkout").first.click()

    browser.is_element_present_by_css("label.terms", 10)
    browser.find_by_css('label.terms').click()
finally:
    browser.quit()

Here is a working code that goes to the main page, navigates to the third product in the scroller, adds it to cart, checks out and accepts the terms of use, time.sleep() at the end is just for you to see the result:

from splinter import Browser

browser = Browser("chrome")
browser.visit("http://www.supremenewyork.com/shop")
browser.wait_time = 10

try:
    # open a product
    browser.is_element_visible_by_css("#shop-scroller > li > a", 10)
    browser.find_by_css("#shop-scroller > li > a")[2].click()

    # add to cart
    browser.is_element_visible_by_css("input[name=commit]", 10)
    browser.find_by_css("input[name=commit]").first.click()

    # checkout
    browser.is_element_visible_by_css("a.checkout", 10)
    browser.find_by_css("a.checkout").first.click()

    # accept terms and conditions
    browser.is_element_present_by_css("label.terms", 10)
    browser.find_by_css('label.terms').click()

    import time
    time.sleep(10)
finally:
    browser.quit()


问:
Python2 + 3 : How to install modules for Python3 installed from sources and offline?
I'm using RedHat Linux 6 and currently I only have 2.6.X version available from internal Linux repository. So I installed Python2 package(s) from repository and in parallel I installed python3 from sources into /opt directory :

```<code>$ ll /usr/bin/python3
lrwxrwxrwx. 1 root root 29 Jul  4 15:04 /usr/bin/python3 -> /opt/python-3.5.2/bin/python3
</code>```

Problem is now that I don't know how to install modules for Python3 installed from sources and so not in default directory (modules for Python2 are installed from internal repository) without breaking Python 2 install.

Moreover the server does not have access to internet.

How could I manage my Python 3 install to get modules ? I read multiple docs but I cannot figure out how to proceed.

Thx,
Tom

答:
So if you have downloaded python from source e.g.
tar -zxvf python-3.6.3.tgz
cd python-3.6.3.tgz
./configure
make
make install

Now rename python to python3
mv python python3

Now install the module
./python3 -m pip install pandas

Body:
I'm using RedHat Linux 6 and currently I only have 2.6.X version available from internal Linux repository. So I installed Python2 package(s) from repository and in parallel I installed python3 from sources into /opt directory :

$ ll /usr/bin/python3
lrwxrwxrwx. 1 root root 29 Jul  4 15:04 /usr/bin/python3 -> /opt/python-3.5.2/bin/python3

Problem is now that I don't know how to install modules for Python3 installed from sources and so not in default directory (modules for Python2 are installed from internal repository) without breaking Python 2 install.

Moreover the server does not have access to internet.

How could I manage my Python 3 install to get modules ? I read multiple docs but I cannot figure out how to proceed.

Thx,
Tom


问:
Bazel failed to include a external static library .a
-- Question solved --

This question is solved. Thanks for all the help!

The problem and the reason is briefly stated as following for other readers in the future:

[Environment]

Ubuntu 14.04, Bazel, C++

[Question]

I want to include an external library. So I download the source file and make it as as a static lib .a.

I correctly set the BUILD, WORKSPACE and related files. However, when compile, it alerts the error:

```<code>Linking of rule '//main' failed (Exit 1)
main: error: undefined reference to 'void ex_lib::compute(double*, double const*, double const*)'
collect2: error: ld returned 1 exit status
</code>```

I tried with the .lo and alwayslink method here but doesn't work.

Alternate to "`--whole-archive`" in bazel

[Reason]

It is because that the external library source files contains duplicate header files. So I fix the header file problem. Make the .a again. Then everything works.

So nothing wrong with the bazel. It is the library itself that cause the problem. But the error information is confusing and I think it is caused by bazel.

答: What you can do to investigate further is to run the clean bazel build with --subcommands to see individual command lines of actions executed. Then you can cd into the sandbox, and execute the same gcc command as bazel does and debug what's wrong. Or you can try to get linking to work by handwriting gcc command, and pasting here both the command bazel generated, and your desired command. Is it possible that you have multiple liegroups libs installed on the system and gcc is getting one that's incompatible with headers you're including?

Body:
-- Question solved --

This question is solved. Thanks for all the help!

The problem and the reason is briefly stated as following for other readers in the future:

[Environment]

Ubuntu 14.04, Bazel, C++

[Question]

I want to include an external library. So I download the source file and make it as as a static lib .a.

I correctly set the BUILD, WORKSPACE and related files. However, when compile, it alerts the error:

Linking of rule '//main' failed (Exit 1)
main: error: undefined reference to 'void ex_lib::compute(double*, double const*, double const*)'
collect2: error: ld returned 1 exit status

I tried with the .lo and alwayslink method here but doesn't work.

Alternate to "`--whole-archive`" in bazel

[Reason]

It is because that the external library source files contains duplicate header files. So I fix the header file problem. Make the .a again. Then everything works.

So nothing wrong with the bazel. It is the library itself that cause the problem. But the error information is confusing and I think it is caused by bazel.


问:
C#-Array Covariance In Generic Classes
I know that C# supports covariance in arrays like this :

```<code>object[] array = new string[3];
</code>```

But I'm getting an error when it tries to compile the below code

```<code>class Dummy<K,T> where T:K
{
    public void foo()
    {
        K[] arr = new T[4];
    }
}
</code>```

It says "Cannot implicitly convert type 'T[]' to 'K[]' "

Why I'm getting this error ???

答:
You have to specify that both T and K are reference types. Array covariance only works with reference types. Change the declaration to:

```<code>class Dummy<K,T> where T : class, K
</code>```

and it works fine. You don't have to specify that K is a reference type, because if T is a reference type and it derives from or implements K, then K must be a reference type too. (At least I assume that's the reasoning. It doesn't hurt to add where K : class as well for clarity.)

Title: C#-Array Covariance In Generic Classes

Body:
I know that C# supports covariance in arrays like this :

object[] array = new string[3];

But I'm getting an error when it tries to compile the below code

class Dummy<K,T> where T:K
{
    public void foo()
    {
        K[] arr = new T[4];
    }
}

It says "Cannot implicitly convert type 'T[]' to 'K[]' "

Why I'm getting this error ???

Body:
You have to specify that both T and K are reference types. Array covariance only works with reference types. Change the declaration to:

class Dummy<K,T> where T : class, K

and it works fine. You don't have to specify that K is a reference type, because if T is a reference type and it derives from or implements K, then K must be a reference type too. (At least I assume that's the reasoning. It doesn't hurt to add where K : class as well for clarity.)

OwnerDisplayName: Jon Skeet

LastEditorDisplayName: Jon Skeet


问:
How to Retrieve JTable Data as an Array
I've populated a JTable through a DefaultTableModel with the (Object[][] data, String[] headers) constructor. Users can edit the table, and I want to be able to load the new data back into an array (Object[][]). Note that I'd rather not just update the array bit by bit, but be able to just completely load a new array from the table. How can this be done?

答:
I take that back, on 2nd thoughts, you dont need any typecasting - TableModel is an interface that has all the 3 method calls you need. :)

Summary: Get the model for the table, check its class and typecast it to appropriate class (Abstract or Default TableModel), and use its methods to load a newly created array. Some psuedoCode:

```<code>public Object[][] getTableData (JTable table) {
    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
    Object[][] tableData = new Object[nRow][nCol];
    for (int i = 0 ; i < nRow ; i++)
        for (int j = 0 ; j < nCol ; j++)
            tableData[i][j] = dtm.getValueAt(i,j);
    return tableData;
}
</code>```

Your headers should not have changed by user-edits. Hope that helps. Regards, - M.S.

Title: How to Retrieve JTable Data as an Array

Body:
I take that back, on 2nd thoughts, you dont need any typecasting - TableModel is an interface that has all the 3 method calls you need. :)

Summary: Get the model for the table, check its class and typecast it to appropriate class (Abstract or Default TableModel), and use its methods to load a newly created array. Some psuedoCode:

public Object[][] getTableData (JTable table) {
    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
    Object[][] tableData = new Object[nRow][nCol];
    for (int i = 0 ; i < nRow ; i++)
        for (int j = 0 ; j < nCol ; j++)
            tableData[i][j] = dtm.getValueAt(i,j);
    return tableData;
}

Your headers should not have changed by user-edits. Hope that helps. Regards, - M.S.


问:
Set up email notification every time a threshold value is exceeded within a table in SQL
I have a table where I store errors calculated from a bunch of .csv files that contain prediction and measurements. What I want, is to create an automatic process that will allow me to send an email to my account whenever any row within the table of errors contains a value that exceeds a predefined threshold. I have gone through a lot of documentation online, and as far as I get it I either need to create a trigger or set up a job on the server. However, I am new therefore I have real troubles implementing what I want. Any example would thus be greatly appreciated :)

答:
Sending e-mail from a trigger is not a good idea.

Any trigger is a part of the transaction, this means your transaction will not commit until e-mail will be sent, and in case of sending error your transaction will be rolled back.

As you said you can use a job to do this.

In the job you just check for the records of interest and if any row is found, send e-mail from a job. Or you can raise an error if any row is found and make a job send you email on failure.

The job can be scheduled to execute every 5 minutes and you can check for new rows using datetime filed: new rows in the table means

```<code>datetime_field >= dateadd(minute, -5, getdate())
</code>```

Body:
Sending e-mail from a trigger is not a good idea.

Any trigger is a part of the transaction, this means your transaction will not commit until e-mail will be sent, and in case of sending error your transaction will be rolled back.

As you said you can use a job to do this.

In the job you just check for the records of interest and if any row is found, send e-mail from a job. Or you can raise an error if any row is found and make a job send you email on failure.

The job can be scheduled to execute every 5 minutes and you can check for new rows using datetime filed: new rows in the table means

datetime_field >= dateadd(minute, -5, getdate())


问:
Context in MVVM in android
I have started working on MVVM architecture for android application.I have a doubt that is it right to pass the context to view model ? If not then how can my view model can access the context if needed.

I am doing the following things:

Feed data using some EditText.

Send this data to View model.

View model send this data to repository

Repository storing this data to shared preferences of the device.

As shared preferences required context to instantiate the object.

I am new to this architecture any guidance would be helpful for me, thanks in advance.

答:
A very good question, and it is not as simple as it seems!
You can see an example from Google team here.

They solved the problem with the help of the factory.
There it is pass (of course) the Application context (not Activity context !).

A small problem - and so much boilerplate code!

My decision:

```<code>public class MainApplication extends Application {
public void onCreate() {
AppSharedPref sharedPref = AppSharedPref.getInstance(PreferenceManager.getDefaultSharedPreferences(this));
AppRepository.getInstance(sharedPref);
</code>```

Repository is  singltone (a lot of code is skipped for brevity):

```<code>public class AppRepository implements AppDataSource {
public static AppRepository getInstance(@NonNull AppSharedPref sharedPref) {
if (INSTANCE == null) {
   INSTANCE = new AppRepository(sharedPref);
}
return INSTANCE;
}
</code>```

In ViewModel call:

```<code>public class MyViewModel extends AndroidViewModel {

// constructor
public MyViewModel(@NonNull Application application) {
   repository = AppRepository.getInstance(.....);
}
</code>```

Title: Context in MVVM in android

Body:
A very good question, and it is not as simple as it seems!
You can see an example from Google team here.

They solved the problem with the help of the factory.
There it is pass (of course) the Application context (not Activity context !).

A small problem - and so much boilerplate code!

My decision:

public class MainApplication extends Application {
public void onCreate() {
AppSharedPref sharedPref = AppSharedPref.getInstance(PreferenceManager.getDefaultSharedPreferences(this));
AppRepository.getInstance(sharedPref);

Repository is  singltone (a lot of code is skipped for brevity):

public class AppRepository implements AppDataSource {
public static AppRepository getInstance(@NonNull AppSharedPref sharedPref) {
if (INSTANCE == null) {
   INSTANCE = new AppRepository(sharedPref);
}
return INSTANCE;
}

In ViewModel call:

public class MyViewModel extends AndroidViewModel {

// constructor
public MyViewModel(@NonNull Application application) {
   repository = AppRepository.getInstance(.....);
}


问:
How to check if value is greater than another using javascript
I'm using javascript to check if the value entered by the user is greater than the value there. But when I click update it just redirect to another page without giving the error message.

Javascript

```<code><script type="text/javascript">

$(function onUpdateClick () {
    var initVal = $('#quantity').val();

    $('#quantity').change(function () {
        if ($('#quantityI').val() > initVal)
            console.log('Quantity issued should be less than quantity requested');
        else {

            location.href = '@Url.Action("Index","Issue")';
        }
    });
</code>```

View

```<code>   <div class="form-group">
                        @Html.LabelFor(model => model.item.quantity, htmlAttributes: new { @class = "control-label col-md-2" })
                        @Html.EditorFor(model => model.item.quantity, new { htmlAttributes = new { @class = "form-control" , @readonly="readonly", @id=quantity} })
                        @Html.ValidationMessageFor(model => model.item.quantity, "", new { @class = "text-danger" })
                    </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.item.quantityI, htmlAttributes: new { @class = "control-label col-md-2" })
                    @Html.EditorFor(model => model.item.quantityI, new { htmlAttributes = new { @class = "form-control", @id=quantityI } })
                    @Html.ValidationMessageFor(model => model.item.quantityI, "", new { @class = "text-danger" })
                </div>
</code>```

Model
    [Required]

```<code>    [Range(0.5,double.MaxValue, ErrorMessage = "You must enter an amount greater than Zero")]
    [Display(Name ="Quantity Requested")]
    public double quantity { get; set; }

    [Required]
    [Range(0.5, double.MaxValue, ErrorMessage = "You must enter an amount greater than Zero")]
    [Display(Name = "Quantity Issued")]
    public double quantityI { get; set; }
</code>```

答:
Your descriptions is missing some steps. Anyway I will try to give some points, hope it will help.
The initial value of the controls is an empty string (as far as I can tell) so comparing them will give a string compare of two empty strings.
Take note that in some versions of FireFox the final control's value is set  after it looses focus, so sometimes the value that you get is the old one at onchage event...</p>


问:
How do you add up an output given from a log file using Python

I need to output the ammount of attacks, per hour, per IP from a log file using Python script. I have managed to get it all done but can not work out how to add amount of attacks into a final total. I am lacking the knowledge needed to understand how the total function works outside of simple calculations. Thank you in advance for any help.

```<code>import re
from itertools import groupby
total = 0

with open(log_file) as Authlog:
    Authlog = (line for line in Authlog if "Failed password for" in line)

    for key, group in groupby(Authlog, key = lambda x: x[:9] + re.search('from(.+?) port', x).group(1)):
        hour, month, day = key[0:3], key[4:6], key[7:9]
        print ("Within the hour of %s:00 on %s-%s There was %d attacks"%(day, month, hour, len(list(group))))
        Total = total +1

print("Total amount of attacks: %s" % total)
</code>```

What I expect the result to be:

```<code>Within the hour of 08:00 on  3-Feb There was 172 attacks
Within the hour of 13:00 on  3-Feb There was 4 attacks
Within the hour of 21:00 on  3-Feb There was 1 attacks
Within the hour of 08:00 on  4-Feb There was 15 attacks
Within the hour of 10:00 on  4-Feb There was 58 attacks
Within the hour of 10:00 on  4-Feb There was 2 attacks
Within the hour of 16:00 on  4-Feb There was 4 attacks
Within the hour of 07:00 on  5-Feb There was 24 attacks
Within the hour of 08:00 on  5-Feb There was 86 attacks
Total amount of attacks: 366
</code>```

What I actually get:

```<code>Within the hour of 08:00 on  3-Feb There was 172 attacks
Within the hour of 13:00 on  3-Feb There was 4 attacks
Within the hour of 21:00 on  3-Feb There was 1 attacks
Within the hour of 08:00 on  4-Feb There was 15 attacks
Within the hour of 10:00 on  4-Feb There was 58 attacks
Within the hour of 10:00 on  4-Feb There was 2 attacks
Within the hour of 16:00 on  4-Feb There was 4 attacks
Within the hour of 07:00 on  5-Feb There was 24 attacks
Within the hour of 08:00 on  5-Feb There was 86 attacks
Total amount of attacks: 9
</code>```

答:
Variable name case does matter. Just change the line:

```<code>Total = total +1
</code>```

to

```<code>total = total + len(list(group))
</code>```

because inside a loop your totals counter is incorrect: instead it counts just iteration count. And the value set to a new variable Total created inside each loop step is loosing.

Body:
I need to output the ammount of attacks, per hour, per IP from a log file using Python script. I have managed to get it all done but can not work out how to add amount of attacks into a final total. I am lacking the knowledge needed to understand how the total function works outside of simple calculations. Thank you in advance for any help.

import re
from itertools import groupby
total = 0

with open(log_file) as Authlog:
    Authlog = (line for line in Authlog if "Failed password for" in line)

    for key, group in groupby(Authlog, key = lambda x: x[:9] + re.search('from(.+?) port', x).group(1)):
        hour, month, day = key[0:3], key[4:6], key[7:9]
        print ("Within the hour of %s:00 on %s-%s There was %d attacks"%(day, month, hour, len(list(group))))
        Total = total +1

print("Total amount of attacks: %s" % total)

What I expect the result to be:

Within the hour of 08:00 on  3-Feb There was 172 attacks
Within the hour of 13:00 on  3-Feb There was 4 attacks
Within the hour of 21:00 on  3-Feb There was 1 attacks
Within the hour of 08:00 on  4-Feb There was 15 attacks
Within the hour of 10:00 on  4-Feb There was 58 attacks
Within the hour of 10:00 on  4-Feb There was 2 attacks
Within the hour of 16:00 on  4-Feb There was 4 attacks
Within the hour of 07:00 on  5-Feb There was 24 attacks
Within the hour of 08:00 on  5-Feb There was 86 attacks
Total amount of attacks: 366

What I actually get:

Within the hour of 08:00 on  3-Feb There was 172 attacks
Within the hour of 13:00 on  3-Feb There was 4 attacks
Within the hour of 21:00 on  3-Feb There was 1 attacks
Within the hour of 08:00 on  4-Feb There was 15 attacks
Within the hour of 10:00 on  4-Feb There was 58 attacks
Within the hour of 10:00 on  4-Feb There was 2 attacks
Within the hour of 16:00 on  4-Feb There was 4 attacks
Within the hour of 07:00 on  5-Feb There was 24 attacks
Within the hour of 08:00 on  5-Feb There was 86 attacks
Total amount of attacks: 9

Body:
Variable name case does matter. Just change the line:

Total = total +1

to

total = total + len(list(group))

because inside a loop your totals counter is incorrect: instead it counts just iteration count. And the value set to a new variable Total created inside each loop step is loosing.


问:
Question regarding C loops
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

```<code>for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}
</code>```

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

```<code>#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}
</code>```

Thanks!
Amit

答:
```<code>for (i=0; i<nrow; i++) {
    dat[k]=1.0;
    k++;
}
</code>```

That should work.

Title: Question regarding C loops

Body:
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}

Thanks!
Amit

Body:
for (i=0; i<nrow; i++) {
    dat[k]=1.0;
    k++;
}

That should work.

OwnerDisplayName: Anonymous


问:
Not able to retrieve values of the collapsable tree using jQuery plugin in the polymer 2.0

I'm a beginner in Javascript and jQuery and I am trying to create a custom element of collapsable tree using the jQuery plugin ztree in the Polymer 2.0. For the parent and the nodes of the tree, I gave the values in the array as shown in the tree-element.html below.

```<code><!doctype html>
<html lang="en">
<link rel="import" href="./bower_components/polymer/polymer-element.html">
<script type="text/javascript" src="./js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="./js/jquery.ztree.core.js"></script>

<dom-module id="tree-element">
  <template>
      <link rel="stylesheet" href="./css/zTreeStyle/zTreeStyle.css" type="text/css">
          <div>
              <ul id="treeDemo" class="ztree" style="overflow-y: auto;">[[data]]</ul>
          </div>
  </template>

  <script>
    /**
     * `tree-element`
     * tree element
     *
     * @customElement
     * @polymer
     * @demo demo/index.html
     */
    class TreeElement extends Polymer.Element {

      static get is() { return 'tree-element'; }
      static get properties() {
        return {
          settings: {
                    type: Object,
                    value: {}
                },
          data:
          {
            type: Array,
            value: [
   {name:"test1", open:true, children:[
      {name:"test1_1"}, {name:"test1_2"}]},
   {name:"test2", open:true, children:[
      {name:"test2_1"}, {name:"test2_2"}]}
   ]
          }
        };
      }

      ready()
      {
          super.ready();
          $.fn.zTree.init($("#treeDemo"), this.settings, this.data);
      }
    }
    window.customElements.define(TreeElement.is, TreeElement);
  </script>
</dom-module>
</html>
</code>```

Along with that, this is my index.html file code.

```<code><!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">

    <title>tree-element demo</title>
    <script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="../js/jquery.ztree.core.js"></script>
    <script src="../bower_components/webcomponentsjs/webcomponents-lite.js"></script>

    <link rel="import" href="../../iron-demo-helpers/demo-pages-shared-styles.html">
    <link rel="import" href="../../iron-demo-helpers/demo-snippet.html">
    <link rel="import" href="../tree-element.html">

    <custom-style>
        <link rel="stylesheet" href="./css/zTreeStyle/zTreeStyle.css" type="text/css">
      <style is="custom-style" include="demo-pages-shared-styles">
      </style>
    </custom-style>
  </head>
  <body>
      <demo-snippet>
        <template>
          <tree-element></tree-element>
        </template>
      </demo-snippet>
  </body>
</html>
</code>```

I was hoping to get the tree structure as the output but, the output I am getting by running the command polymer serve --open from the project directory is shown in the below image.

Please suggest how to fix this issue as I'm feeling extremely clueless right now because of my lack of knowledge and experience in this field.

答:
Here below a simple tree element that you may develop: tree-element.html</p>

```<code><link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/iron-icons/iron-icons.html">
<link rel="import" href="bower_components/iron-icon/iron-icon.html">
<link rel="import" href="bower_components/paper-icon-button/paper-icon-button.html">

<dom-module id="tree-element">
  <template>
    <style>
      :host {
        display: block;
        position: relative;
        padding-top: 50px;
        padding-bottom: 64px;
        min-height: 100vh
      }
    paper-icon-button.menuList{
          padding-left: 50px;
    }
    </style>

  <paper-icon-button icon="menu" on-tap="extractList">Test</paper-icon-button> <span>Test2</span>
  <template is="dom-if" if="{{show}}">
    <template is= "dom-repeat" items="{{menuList}}">
      <br/>
      <paper-icon-button class="menuList" icon ="{{item.icon}}"></paper-icon-button><span>{{item.text}} </span>
    </template>
  </template>
  </template>

  <script>
    class TreeElemen extends Polymer.Element {
      static get is() { return 'tree-element'; }
      static get properties() {
        return {
          show: {
            type: Boolean,
            value: false
          },
          menuList: {
            type:Array,
            value() {return [{"icon":"android", "text":"Android"},
  {"icon":"bug-report", "text":"Bug report"}]}
}}}
extractList() {
this.show=!this.show;
}}
window.customElements.define(TreeElemen.is, TreeElemen);
  </script>
</dom-module>
</code>```

Body:
I'm a beginner in Javascript and jQuery and I am trying to create a custom element of collapsable tree using the jQuery plugin ztree in the Polymer 2.0. For the parent and the nodes of the tree, I gave the values in the array as shown in the tree-element.html below.

<!doctype html>

<link rel="import" href="./bower_components/polymer/polymer-element.html">

<dom-module id="tree-element">
  <template>
      <link rel="stylesheet" href="./css/zTreeStyle/zTreeStyle.css" type="text/css">

[[data]]

  </template>

</dom-module>

Along with that, this is my index.html file code.

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">

    <title>tree-element demo</title>

    <link rel="import" href="../../iron-demo-helpers/demo-pages-shared-styles.html">
    <link rel="import" href="../../iron-demo-helpers/demo-snippet.html">
    <link rel="import" href="../tree-element.html">

    <custom-style>
        <link rel="stylesheet" href="./css/zTreeStyle/zTreeStyle.css" type="text/css">

    </custom-style>

      <demo-snippet>
        <template>
          <tree-element></tree-element>
        </template>
      </demo-snippet>

I was hoping to get the tree structure as the output but, the output I am getting by running the command polymer serve --open from the project directory is shown in the below image.

Please suggest how to fix this issue as I'm feeling extremely clueless right now because of my lack of knowledge and experience in this field.

Body:
Here below a simple tree element that you may develop: tree-element.html

<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/iron-icons/iron-icons.html">
<link rel="import" href="bower_components/iron-icon/iron-icon.html">
<link rel="import" href="bower_components/paper-icon-button/paper-icon-button.html">

<dom-module id="tree-element">
  <template>
    <style>
      :host {
        display: block;
        position: relative;
        padding-top: 50px;
        padding-bottom: 64px;
        min-height: 100vh
      }
    paper-icon-button.menuList{
          padding-left: 50px;
    }
    </style>

  <paper-icon-button icon="menu" on-tap="extractList">Test</paper-icon-button> <span>Test2</span>
  <template is="dom-if" if="{{show}}">
    <template is= "dom-repeat" items="{{menuList}}">
      <br/>
      <paper-icon-button class="menuList" icon ="{{item.icon}}"></paper-icon-button><span>{{item.text}} </span>
    </template>
  </template>
  </template>

  <script>
    class TreeElemen extends Polymer.Element {
      static get is() { return 'tree-element'; }
      static get properties() {
        return {
          show: {
            type: Boolean,
            value: false
          },
          menuList: {
            type:Array,
            value() {return [{"icon":"android", "text":"Android"},
  {"icon":"bug-report", "text":"Bug report"}]}
}}}
extractList() {
this.show=!this.show;
}}
window.customElements.define(TreeElemen.is, TreeElemen);
  </script>
</dom-module>


问:
ArcGIS Convert IGeometryCollection to IEnumGeometry
I have a group of polylines mistakenly created with a geometry for each vertex pair. Typically they have thousands of geometries.
I would like to merge the geometries (note: NOT merge features) in each feature into one geometry. To do this I am using ITopologicalOperator5.ConstructUnion. ConstructUnion takes an IEnumGeometry parameter and I have an IGeometryCollection of geometries. I can create an IEnumGeometry using a GeometryBag but ConstructUnion does not accept GeometryBags.
If I use IEnumGeometry pEnum = (IEnumGeometry)pGeomCollection it throws an exception.
If I use IEnumGeometry pEnum = pGeomCollection as IEnumGeometry then pEnum is null.
In VB.NET Ctype(pGeomCollection, IEnumGeometry) works fine.
Can anyone tell me how to convert a (C#) Geometry Collection into an IEnumGeometry?

Thanks,

John

答:
Have you tried

```<code>IEnumGeometry enumGeom = (IEnumGeometry)((IGeometryBag)geometryCollection);
</code>```

IGeometryBag implements IGeometryCollection, and IGeometryBag implements IEnumGeometry.

But GeometryCollection doesn't implement IEnumGeometry directly, so you'll have to cast it to GeometryBag first, and afterwards to IEnumGeometry.

Body:
Have you tried

IEnumGeometry enumGeom = (IEnumGeometry)((IGeometryBag)geometryCollection);

IGeometryBag implements IGeometryCollection, and IGeometryBag implements IEnumGeometry.

But GeometryCollection doesn't implement IEnumGeometry directly, so you'll have to cast it to GeometryBag first, and afterwards to IEnumGeometry.


问:
Where to call Crop Image Before Setting to ImageView
Where to call Crop Image Before Setting to Image view as I'm not getting it as my Image not getting cropped for this activity. As I want to crop the Image and post the Cropped Image to the server as well

```<code>@Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);
                imgNavHeaderPic.setImageBitmap(bitmap);
                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                createBitmapAndAssign(Uri.fromFile(file));
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {
            Uri selectedImage = data.getData();
            createBitmapAndAssign(data.getData());
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            imgNavHeaderPic.setImageBitmap(thumbnail);
            Drawable bitmap = imgNavHeaderPic.getDrawable();

        }
    }
}
</code>```

As I'm also compressing my Image well...

答:
try this one</p>

```<code>try{
    Bitmap bm = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
    bm = Bitmap.createBitmap(bm, 0, 0, 400, 400);
    your_imageview.setImageBitmap(bm);
}catch(Exception e){
      e.printStackTrace();
}
</code>```

Body:
Where to call Crop Image Before Setting to Image view as I'm not getting it as my Image not getting cropped for this activity. As I want to crop the Image and post the Cropped Image to the server as well

@Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);
                imgNavHeaderPic.setImageBitmap(bitmap);
                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                createBitmapAndAssign(Uri.fromFile(file));
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {
            Uri selectedImage = data.getData();
            createBitmapAndAssign(data.getData());
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            imgNavHeaderPic.setImageBitmap(thumbnail);
            Drawable bitmap = imgNavHeaderPic.getDrawable();

        }
    }
}

As I'm also compressing my Image well...

Body:
try this one

try{
    Bitmap bm = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
    bm = Bitmap.createBitmap(bm, 0, 0, 400, 400);
    your_imageview.setImageBitmap(bm);
}catch(Exception e){
      e.printStackTrace();
}


问:
jQuery add or remove class based on menu item clicked
I tried this, searched on StackOverflow.

```<code>$(".sub>li>a").click(function(e) {
    if( $(this).hasClass("open") ) {
        $(this).removeClass("open").addClass("closed");
    } else {
        // if other menus are open remove open class and add closed
        $(this).siblings().removeClass("open").addClass("closed");
        $(this).removeClass("closed").addClass("open");
    }
});
</code>```

But it does not work.

Here is my fiddle. https://jsfiddle.net/v2oLfcnf/

答:
Your fiddle didn't work because it didn't include a link to jQuery anywhere. I have since updated your fiddle and it seems to work now.
See "External Resources" to the left in the fiddle window. Add a link to jQuery there, i.E.: https://code.jquery.com/jquery-1.7.2.min.js

Body:
I tried this, searched on StackOverflow.

$(".sub>li>a").click(function(e) {
    if( $(this).hasClass("open") ) {
        $(this).removeClass("open").addClass("closed");
    } else {
        // if other menus are open remove open class and add closed
        $(this).siblings().removeClass("open").addClass("closed");
        $(this).removeClass("closed").addClass("open");
    }
});

But it does not work.

Here is my fiddle. https://jsfiddle.net/v2oLfcnf/


问:
What is a good way to find gaps in a set of datespans?
What is a way to find gaps in a set of date spans?

For example, I have these date spans:

```<code>1/ 1/11 - 1/10/11
1/13/11 - 1/15/11
1/20/11 - 1/30/11
</code>```

Then I have a start and end date of 1/7/11 and 1/14/11.

I want to be able to tell that between 1/10/11 and 1/13/11 there is a gap so the start and end date is not possible.  Or I want to return only the datespans up to the first gap encountered.

If this can be done in SQL server that would be good.

I was thinking to go through each date to find out if it lands in a datespan... if it does not then there's a gap on that day.

答:
Assuming MySQL, something like this would work:

```<code>select @olddate := null;

select start_date, end_date, datediff(end_date, @olddate) as diff, @olddate:=enddate
from table
order by start_date asc, end_date asc
having diff > 1;
</code>```

Basically: cache the previous row's end_date in the @olddate variable, and then do a diff on that "old" value with the currel enddate. THe having clause will return only the records where the difference between two rows is greater than a day.

disclaimer: Haven't tested this, but the basic query construct should work.

Body:
What is a way to find gaps in a set of date spans?

For example, I have these date spans:

1/ 1/11 - 1/10/11
1/13/11 - 1/15/11
1/20/11 - 1/30/11

Then I have a start and end date of 1/7/11 and 1/14/11.

I want to be able to tell that between 1/10/11 and 1/13/11 there is a gap so the start and end date is not possible.  Or I want to return only the datespans up to the first gap encountered.

If this can be done in SQL server that would be good.

I was thinking to go through each date to find out if it lands in a datespan... if it does not then there's a gap on that day.

Body:
Assuming MySQL, something like this would work:

select @olddate := null;

select start_date, end_date, datediff(end_date, @olddate) as diff, @olddate:=enddate
from table
order by start_date asc, end_date asc
having diff > 1;

Basically: cache the previous row's end_date in the @olddate variable, and then do a diff on that "old" value with the currel enddate. THe having clause will return only the records where the difference between two rows is greater than a day.

disclaimer: Haven't tested this, but the basic query construct should work.


问:
Jquery only alpha-numeric characters not fixed sized
I am using  Jquery Mask Plugin

I need to change the patern below, to one that accepts only alpha-numeric characters .

I need to eliminate any other kind of character, white spaces, quotes or double-quotes.

I will not have a fixed length size, it can vary from 6 until 10

```<code>$('.carPlates').mask('AAA0000', {'translation': {
        A: {pattern: /[a-zA-Z]/},
        0: {pattern: /[0-9*]/}
      }
});
</code>```

I find this regex pattern that accepts only alpha-numeric characters :

```<code>/[\W_]+/u
</code>```

How can i use this pattern and allow from 6 until 10 characters ?

Body:
I am using  Jquery Mask Plugin

I need to change the patern below, to one that accepts only alpha-numeric characters .

I need to eliminate any other kind of character, white spaces, quotes or double-quotes.

I will not have a fixed length size, it can vary from 6 until 10

$('.carPlates').mask('AAA0000', {'translation': {
        A: {pattern: /[a-zA-Z]/},
        0: {pattern: /[0-9*]/}
      }
});

I find this regex pattern that accepts only alpha-numeric characters :

/[\W_]+/u

How can i use this pattern and allow from 6 until 10 characters ?

Body:
Try like this,

$('.carPlates').mask('0000000000', {'translation': {
        0: {pattern: /^[a-zA-Z0-9]*$/}
   }
 });


问:
Switching from Java 1.6 to 1.7 causes JAXB Exception
I recently ran into a problem with one of our legacy applications that depends on the UPS Tracking API. UPS changed their communication protocols to require TLSv1.2 . Unfortunately, the most recent public version of jdk 1.6 does not seem to support this protocol, so my options were to pay for an oracle support contract or upgrade to jdk 1.7. I went with the upgrade to 1.7

I changed the dependencies for my project and everything looked fine. When I tried to actually deploy to the application server it failed with the error:

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1
  counts of IllegalAnnotationExceptions java.lang.StackTraceElement does
  not have a no-arg default constructor

I did some research and apparently the issue is caused by jaxb @WebMethod annotated methods that throw an exception with throwable. The solution to that (I thought) was to add a @WebFault annotation to the exception class. I followed the instructions here: http://java.globinch.com/enterprise-java/web-services/jax-ws/jax-ws-exceptions-faults-annotation-exception-and-fault-handling-examples/
and re-deployed.

The result was the same error. The only difference is that my stacktrace is indicating that it is using my custom fault bean rather than trying to generate a wrapper. I also looked at the solutions given here: map exceptions to faults and as far as I can tell, my classes meet the specification but the problem persists.

This issue is preventing me from being able to fix the UPS problems and causing major headache for my users. Any help would be much appreciated.

My Error Log

Caused by: org.jboss.ws.WSException: Failed to create JAXBContext     at
  jaxb.hibernate.XMLAcccesorAvailableContextFactory.createContext(XMLAcccesorAvailableContextFactory.java:41)
    at
  org.jboss.ws.metadata.builder.jaxws.JAXWSMetaDataBuilder.createJAXBContext(JAXWSMetaDataBuilder.java:940)
    ... 82 more Caused by:
  com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of
  IllegalAnnotationExceptions java.lang.StackTraceElement does not have
  a no-arg default constructor.     this problem is related to the
  following location:       at java.lang.StackTraceElement      at public
  java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()         at
  java.lang.Throwable       at private java.lang.Throwable[]
  com.tura.common.server.service.addressvalidation.AddressServiceFault.suppressed
        at
  com.tura.common.server.service.addressvalidation.AddressServiceFault

at
  com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:106)

The Exception Class

```<code>@WebFault(faultBean = "com.tura.common.server.service.addressvalidation.AddressServiceFault")
public class AddressValidationServiceException extends Exception {

    private AddressServiceFault faultInfo;

    public AddressValidationServiceException() {
        super();
    }
    public AddressValidationServiceException(AddressServiceFault fault) {
        super(fault.getFaultString());
        this.faultInfo = fault;
    }

    public AddressValidationServiceException(String message, AddressServiceFault fault) {
        super(message);
        this.faultInfo = fault;
    }

    public AddressValidationServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    public AddressValidationServiceException(String message, AddressServiceFault fault, Throwable cause) {
        super(message, cause);
        this.faultInfo = fault;
    }

    protected AddressServiceFault getFaultInfo() {
        return faultInfo;
    }
}
</code>```

The Fault Bean class

```<code>public class AddressServiceFault {

    private String faultCode;

    private String faultString;

    protected String getFaultCode() {
        return faultCode;
    }

    protected void setFaultCode(String faultCode) {
        this.faultCode = faultCode;
    }

    protected String getFaultString() {
        return faultString;
    }

    protected void setFaultString(String faultString) {
        this.faultString = faultString;
    }
}
</code>```

My WebService Class

```<code>@WebMethod
    public @WebResult(name = "validatedAddresses") String parseAddressStringByLocation(
            @WebParam(name = "sLocation") String sLocation) throws AddressValidationServiceException {
        StringBuffer sbUrl = new StringBuffer();
        StringBuffer sbQueryString = new StringBuffer();

        sbUrl.append("http://test.foo.com");

        try {
            sbQueryString.append("&location=");
            sbQueryString.append(URLEncoder.encode(sLocation, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            AddressServiceFault serviceFault = new AddressServiceFault();
            serviceFault.setMessage("Validation Failed");
            throw new AddressValidationServiceException("Address Validation Error: parseQueryStringByLocation.",
                    serviceFault, e);
        }

        sbUrl.append(sbQueryString);

        return sbUrl.toString();
    }
</code>```

答:
Looks like no one has come up with a solution in time, so I will go ahead and post how I fixed this. JAX-WS uses reflection to determine If an exception class should be wrapped or not. As a result it is VERY picky about the constructors and methods included in the exception. If you look close at the AddressValidationServiceException class, you will notice that it has this method:

```<code>protected AddressServiceFault getFaultInfo() {
        return faultInfo;
    }
</code>```

The problem is in the visibility of that method. getFaultInfo() MUST be a public method, otherwise jax-ws will not correctly recognize and wrap the exception class. As soon as I changed that method to public everything started working. In fact, I was able to remove the @WebFault annotation entirely. As long as the exception class and the fault are formatted correctly, the explicit annotation is not needed.

One other 'gotcha' to be aware of. Java constructors are not inherited. If you have additional classes that extend your exception, each class in the hierarchy must explicitly define the

```<code>public MyClass(String message, MyServiceFault fault)
</code>```

and

```<code>public MyClass(String message, MyServiceFault fault, Throwable cause)
</code>```

constructors.

Body:
I recently ran into a problem with one of our legacy applications that depends on the UPS Tracking API. UPS changed their communication protocols to require TLSv1.2 . Unfortunately, the most recent public version of jdk 1.6 does not seem to support this protocol, so my options were to pay for an oracle support contract or upgrade to jdk 1.7. I went with the upgrade to 1.7

I changed the dependencies for my project and everything looked fine. When I tried to actually deploy to the application server it failed with the error:

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1
  counts of IllegalAnnotationExceptions java.lang.StackTraceElement does
  not have a no-arg default constructor

I did some research and apparently the issue is caused by jaxb @WebMethod annotated methods that throw an exception with throwable. The solution to that (I thought) was to add a @WebFault annotation to the exception class. I followed the instructions here: http://java.globinch.com/enterprise-java/web-services/jax-ws/jax-ws-exceptions-faults-annotation-exception-and-fault-handling-examples/
and re-deployed.

The result was the same error. The only difference is that my stacktrace is indicating that it is using my custom fault bean rather than trying to generate a wrapper. I also looked at the solutions given here: map exceptions to faults and as far as I can tell, my classes meet the specification but the problem persists.

This issue is preventing me from being able to fix the UPS problems and causing major headache for my users. Any help would be much appreciated.

My Error Log

Caused by: org.jboss.ws.WSException: Failed to create JAXBContext     at
  jaxb.hibernate.XMLAcccesorAvailableContextFactory.createContext(XMLAcccesorAvailableContextFactory.java:41)
    at
  org.jboss.ws.metadata.builder.jaxws.JAXWSMetaDataBuilder.createJAXBContext(JAXWSMetaDataBuilder.java:940)
    ... 82 more Caused by:
  com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of
  IllegalAnnotationExceptions java.lang.StackTraceElement does not have
  a no-arg default constructor.     this problem is related to the
  following location:       at java.lang.StackTraceElement      at public
  java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace()         at
  java.lang.Throwable       at private java.lang.Throwable[]
  com.tura.common.server.service.addressvalidation.AddressServiceFault.suppressed
        at
  com.tura.common.server.service.addressvalidation.AddressServiceFault

at
  com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:106)

The Exception Class

@WebFault(faultBean = "com.tura.common.server.service.addressvalidation.AddressServiceFault")
public class AddressValidationServiceException extends Exception {

    private AddressServiceFault faultInfo;

    public AddressValidationServiceException() {
        super();
    }
    public AddressValidationServiceException(AddressServiceFault fault) {
        super(fault.getFaultString());
        this.faultInfo = fault;
    }

    public AddressValidationServiceException(String message, AddressServiceFault fault) {
        super(message);
        this.faultInfo = fault;
    }

    public AddressValidationServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    public AddressValidationServiceException(String message, AddressServiceFault fault, Throwable cause) {
        super(message, cause);
        this.faultInfo = fault;
    }

    protected AddressServiceFault getFaultInfo() {
        return faultInfo;
    }
}

The Fault Bean class

public class AddressServiceFault {

    private String faultCode;

    private String faultString;

    protected String getFaultCode() {
        return faultCode;
    }

    protected void setFaultCode(String faultCode) {
        this.faultCode = faultCode;
    }

    protected String getFaultString() {
        return faultString;
    }

    protected void setFaultString(String faultString) {
        this.faultString = faultString;
    }
}

My WebService Class

@WebMethod
    public @WebResult(name = "validatedAddresses") String parseAddressStringByLocation(
            @WebParam(name = "sLocation") String sLocation) throws AddressValidationServiceException {
        StringBuffer sbUrl = new StringBuffer();
        StringBuffer sbQueryString = new StringBuffer();

        sbUrl.append("http://test.foo.com");

        try {
            sbQueryString.append("&location=");
            sbQueryString.append(URLEncoder.encode(sLocation, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            AddressServiceFault serviceFault = new AddressServiceFault();
            serviceFault.setMessage("Validation Failed");
            throw new AddressValidationServiceException("Address Validation Error: parseQueryStringByLocation.",
                    serviceFault, e);
        }

        sbUrl.append(sbQueryString);

        return sbUrl.toString();
    }

Body:
Looks like no one has come up with a solution in time, so I will go ahead and post how I fixed this. JAX-WS uses reflection to determine If an exception class should be wrapped or not. As a result it is VERY picky about the constructors and methods included in the exception. If you look close at the AddressValidationServiceException class, you will notice that it has this method:

protected AddressServiceFault getFaultInfo() {
        return faultInfo;
    }

The problem is in the visibility of that method. getFaultInfo() MUST be a public method, otherwise jax-ws will not correctly recognize and wrap the exception class. As soon as I changed that method to public everything started working. In fact, I was able to remove the @WebFault annotation entirely. As long as the exception class and the fault are formatted correctly, the explicit annotation is not needed.

One other 'gotcha' to be aware of. Java constructors are not inherited. If you have additional classes that extend your exception, each class in the hierarchy must explicitly define the

public MyClass(String message, MyServiceFault fault)

and

public MyClass(String message, MyServiceFault fault, Throwable cause)

constructors.


问:
Open a form from modal form that opened from parent form
I create a form which makes lightbox effect.And after creating this lightbox form, i create another form.

```<code>//Execute from parent form
Form f = new Form();
f.ShowInTaskbar = false;
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = FormStartPosition.CenterParent;
f.Opacity = 0.6;
f.ShowDialog(); // Open Modal window
notificationSize nds = new notificationSize();
nds.Show(); // Open another form on Modal Dialog
</code>```

After creating lightbox form, it doesn't show another form nds. Just showind the lightbox modal dialog.

how can i show the form on the modal form ?

答:
Display your "child" form by setting TopLevel to false:

```<code>Form f = new Form();
f.ShowInTaskbar = false;
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = FormStartPosition.CenterParent;
f.Opacity = 0.6;

notificationSize nds = new notificationSize();
nds.TopLevel = false;
nds.FormBorderStyle = ... // you may want to set this to none
nds.Dock = ... // you may want to set this to fill
f.Controls.Add(nds);
nds.Show(); // Open another form on Modal Dialog

f.ShowDialog(); // Open Modal window
</code>```

Body:
I create a form which makes lightbox effect.And after creating this lightbox form, i create another form.

//Execute from parent form
Form f = new Form();
f.ShowInTaskbar = false;
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = FormStartPosition.CenterParent;
f.Opacity = 0.6;
f.ShowDialog(); // Open Modal window
notificationSize nds = new notificationSize();
nds.Show(); // Open another form on Modal Dialog

After creating lightbox form, it doesn't show another form nds. Just showind the lightbox modal dialog.

how can i show the form on the modal form ?

Body:
Display your "child" form by setting TopLevel to false:

Form f = new Form();
f.ShowInTaskbar = false;
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = FormStartPosition.CenterParent;
f.Opacity = 0.6;

notificationSize nds = new notificationSize();
nds.TopLevel = false;
nds.FormBorderStyle = ... // you may want to set this to none
nds.Dock = ... // you may want to set this to fill
f.Controls.Add(nds);
nds.Show(); // Open another form on Modal Dialog

f.ShowDialog(); // Open Modal window