问:
Are IFrames (HTML) obsolete?
Getting contradictory messages about that, hope they're not.
I cannot imagine support for it would stop, since a gazillion sites use them.

Some additional questions about that:

Why should they phase out this tag?

Any alternative for it?

答:
Horses for courses... s are like anything else... for the right purpose they're the right tool; for the wrong purpose they're an ugly hack, or worse.

In Ajax,
s are often the more appropriate container.  In some places the activity of passing-off external content as part of your own site, as supported by s, is inappropriate.

My team used an  the other day as an ideal way to give users access to their HTML e-mail history - the e-mails were complete  pages which we wanted to insert easily into our web template.  s were absolutely perfect for presenting that data]'.

On the other hand, s should almost always be removed or disabled in any user-submitted content which is output back onto the site, because in that context they are a major security issue.

Title: Are IFrames (HTML) obsolete?

Body:
Horses for courses... <iframe>s are like anything else... for the right purpose they're the right tool; for the wrong purpose they're an ugly hack, or worse.

In Ajax, <div>s are often the more appropriate container.  In some places the activity of passing-off external content as part of your own site, as supported by <iframe>s, is inappropriate.

My team used an <iframe> the other day as an ideal way to give users access to their HTML e-mail history - the e-mails were complete <html> pages which we wanted to insert easily into our web template.  <iframe>s were absolutely perfect for presenting that data]'.

On the other hand, <iframe>s should almost always be removed or disabled in any user-submitted content which is output back onto the site, because in that context they are a major security issue.


来源: stackexchange

问:
iOS 10.3: NSStrikethroughStyleAttributeName is not rendered if applied to a sub range of NSMutableAttributedString
A strikethrough (single, double, ...) added as attribute to an instance of NSMutableAttributedString is not rendered if the apply range is not the whole string range.

This happens using addAttribute(_ name: String, value: Any, range: NSRange),  insert(_ attrString: NSAttributedString, at loc: Int), append(_ attrString: NSAttributedString), ...

Broken by Apple in early iOS 10.3 betas, and not fixed in 10.3 final.

Credit:
https://openradar.appspot.com/31034683

答: Adding a NSBaselineOffsetAttributeName, as explained here, to the attributed string brings back the strikethrough line. Overriding drawText:in: can be slow especially on Collection View or Table View Cells.

ContentLicense: CC BY-SA 3.0


问:
grep to match filename in full path
I want to "extract" the file name in a full path string using grep.

For example:

In /etc/network/interfaces I want to match "interfaces".

In /home/user/Documents/report.pdf I want to match "report.pdf".

Basically I want the opposite of:

```<code>$ ls /etc/network/interfaces | grep "^.*/"
</code>```

I tried:

```<code>$ ls -p /etc/network/interfaces | grep "/.*$"
</code>```

But it won't be the last slash (/), all chars (.*), until the end ($). Since slashes are chars as well, it matches all the path.

Does anyone know a way to match only the last part? Something like (from last slash until the end.

Thank you,

答:
awk, getting the / separated last field:

```<code>% awk -F/ '{print $NF}' <<<'/etc/network/interfaces'
interfaces

% awk -F/ '{print $NF}' <<<'/home/user/Documents/report.pdf'
report.pdf
</code>```

grep, getting the portion after last /:

```<code>% grep -o '[^/]\+$' <<<'/etc/network/interfaces'
interfaces

% grep -o '[^/]\+$' <<<'/home/user/Documents/report.pdf'
report.pdf
</code>```

sed, replacing everything upto the last / with null:

```<code>% sed 's_.*/__' <<<'/etc/network/interfaces'
interfaces

% sed 's_.*/__' <<<'/home/user/Documents/report.pdf'
report.pdf
</code>```

Title: grep to match filename in full path

Body:
I want to "extract" the file name in a full path string using grep.

For example:

In /etc/network/interfaces I want to match "interfaces".

In /home/user/Documents/report.pdf I want to match "report.pdf".

Basically I want the opposite of:

$ ls /etc/network/interfaces | grep "^.*/"

I tried:

$ ls -p /etc/network/interfaces | grep "/.*$"

But it won't be the last slash (/), all chars (.*), until the end ($). Since slashes are chars as well, it matches all the path.

Does anyone know a way to match only the last part? Something like (from last slash until the end.

Thank you,

Body:
awk, getting the / separated last field:

% awk -F/ '{print $NF}' <<<'/etc/network/interfaces'
interfaces

% awk -F/ '{print $NF}' <<<'/home/user/Documents/report.pdf'
report.pdf

grep, getting the portion after last /:

% grep -o '[^/]\+$' <<<'/etc/network/interfaces'
interfaces

% grep -o '[^/]\+$' <<<'/home/user/Documents/report.pdf'
report.pdf

sed, replacing everything upto the last / with null:

% sed 's_.*/__' <<<'/etc/network/interfaces'
interfaces

% sed 's_.*/__' <<<'/home/user/Documents/report.pdf'
report.pdf


问:
How do numpy block matrices work?
The outcome of this code doesn't make any sense to me:

```<code>a = np.zeros((2, 2))
b = np.bmat([[a, a], [a, a]])
print(b.shape, b.dot(np.zeros(4)).shape)
</code>```

How can a matrix with shape (4, 4) when doing a sum-product over its final axis return a matrix of shape (1, 4)?

答:
bmat returns a numpy.matrix instance, as in those things you should never use because they cause all kinds of weird incompatibilities. numpy.matrix always tries to preserve at least two dimensions, so b.dot(np.zeros(4)) is 2D instead of 1D.

Make a numpy.array:

```<code>b = np.bmat([[a, a], [a, a]]).A
#                             ^
</code>```

Or as of NumPy 1.13,

```<code>b = np.block([[a, a], [a, a]])
</code>```

Title: How do numpy block matrices work?

Body:
The outcome of this code doesn't make any sense to me:

a = np.zeros((2, 2))
b = np.bmat([[a, a], [a, a]])
print(b.shape, b.dot(np.zeros(4)).shape)

How can a matrix with shape (4, 4) when doing a sum-product over its final axis return a matrix of shape (1, 4)?

Body:
bmat returns a numpy.matrix instance, as in those things you should never use because they cause all kinds of weird incompatibilities. numpy.matrix always tries to preserve at least two dimensions, so b.dot(np.zeros(4)) is 2D instead of 1D.

Make a numpy.array:

b = np.bmat([[a, a], [a, a]]).A
#                             ^

Or as of NumPy 1.13,

b = np.block([[a, a], [a, a]])


问:
Convert vb.net static method call on object
I am having more problems with my converting of vb.net to c#.net.

I have some files in vb.net that have "Option Strict Off" to allow for bad programming.  When I convert to c# I use "dynamic" until I come back and fix problems, and this works in all cases

But now I have this code:

```<code>Public Class ContractResults
   'Big class definition
   Public Shared Sub CleanCache()
       'Code here
   End Sub
End Class
</code>```

And in a file with Option Strict Off:

```<code>Public Sub VerifyResults(result as Object)
   'Here, result is normally ContractResults
   'first it check for that then call this:
   result.CleanCache()
End Sub
</code>```

In c# I use "dynamic", but a runtime error pops up when I call "static" method with dynamic reference.  In vb.net, I can called "shared" sub from instance, but in c# this is not allowed

Exception:
   "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"
   "Member 'ContractTypes.ContractResults.CleanCache()' cannot be accessed with an instance reference; qualify it with a type name instead"

It seems I must convert code to use actual type, but then this means much rewriting of more parts.  Is anyone able to show another way?

I want to make sure you do not think I can use

```<code>(result as ContractResults).CleanCache();
</code>```

Because all types that may be passed in have "CleanCache()" method, but do not inherits from anything the same other than "Object".  There are many types (30!) that have this "static" method and so that is why it uses Option Strict Off

答:
I'm sorry to say this, but the original decision to turn Option Strict Off was a bad one.  Somehow I doubt that the code that was originally written does what you think it's doing anyway.

It's time to just go ahead and fix that problem.

ContentLicense: CC BY-SA 2.5

Body:
I am having more problems with my converting of vb.net to c#.net.

I have some files in vb.net that have "Option Strict Off" to allow for bad programming.  When I convert to c# I use "dynamic" until I come back and fix problems, and this works in all cases

But now I have this code:

Public Class ContractResults
   'Big class definition
   Public Shared Sub CleanCache()
       'Code here
   End Sub
End Class

And in a file with Option Strict Off:

Public Sub VerifyResults(result as Object)
   'Here, result is normally ContractResults
   'first it check for that then call this:
   result.CleanCache()
End Sub

In c# I use "dynamic", but a runtime error pops up when I call "static" method with dynamic reference.  In vb.net, I can called "shared" sub from instance, but in c# this is not allowed

Exception:
   "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"
   "Member 'ContractTypes.ContractResults.CleanCache()' cannot be accessed with an instance reference; qualify it with a type name instead"

It seems I must convert code to use actual type, but then this means much rewriting of more parts.  Is anyone able to show another way?

I want to make sure you do not think I can use

(result as ContractResults).CleanCache();

Because all types that may be passed in have "CleanCache()" method, but do not inherits from anything the same other than "Object".  There are many types (30!) that have this "static" method and so that is why it uses Option Strict Off


问:
Square-Connect TransactionId Length
I am not finding how wide the transaction_Id string is when returned. I need to store that in a database and need to know how wide to set the column. I am not finding it in their documentation.

https://docs.connect.squareup.com/api/connect/v2/#endpoint-charge

https://docs.connect.squareup.com/api/connect/v2/#type-tendercashdetails

答: Currently most transaction_ids are 26 characters long, but there is no guarantee about how long, or what format an id would be. Some of Square's ids are 36 character GUIDs and that is probably a reasonable upper limit. My advice is to make your column at least 36 characters wide, and include logic in your app to check if a longer id is received that would be truncated in your table.

Title: Square-Connect TransactionId Length


问:
CAGradientLayer diagonal gradient

I use the following CAGradientLayer:

```<code>let layer = CAGradientLayer()
layer.colors = [
    UIColor.redColor().CGColor,
    UIColor.greenColor().CGColor,
    UIColor.blueColor().CGColor
]
layer.startPoint = CGPointMake(0, 1)
layer.endPoint = CGPointMake(1, 0)
layer.locations = [0.0, 0.6, 1.0]
</code>```

But when I set bounds property for the layer, it just stretches a square gradient. I need a result like in Sketch 3 app image (see above).

How can I achieve this?

答:
Update: Use context.drawLinearGradient() instead of CAGradientLayer in a manner similar to the following. It will draw gradients that are consistent with Sketch/Photoshop.

If you absolutely must use CAGradientLayer, then here is the math you'll need to use...

It took some time to figure out, but from careful observation, I found out that Apple's implementation of gradients in CAGradientLayer is pretty odd:

First it converts the view to a square.

Then it applies the gradient using start/end points.

The middle gradient will indeed form a 90 degree angle in this resolution.

Finally, it squishes the view down to the original size.

This means that the middle gradient will no longer form a 90 degree angle in the new size. This contradicts the behavior of virtually every other paint application: Sketch, Photoshop, etc.

If you want to implement start/end points as it works in Sketch, you'll need to translate the start/end points to account for the fact that Apple is going to squish the view.

Steps to perform (Diagrams)

Code

```<code>import UIKit

/// Last updated 4/3/17.
/// See https://stackoverflow.com/a/43176174 for more information.
public enum LinearGradientFixer {
  public static func fixPoints(start: CGPoint, end: CGPoint, bounds: CGSize) -> (CGPoint, CGPoint) {
    // Naming convention:
    // - a: point a
    // - ab: line segment from a to b
    // - abLine: line that passes through a and b
    // - lineAB: line that passes through A and B
    // - lineSegmentAB: line segment that passes from A to B

    if start.x == end.x || start.y == end.y {
      // Apple's implementation of horizontal and vertical gradients works just fine
      return (start, end)
    }

    // 1. Convert to absolute coordinates
    let startEnd = LineSegment(start, end)
    let ab = startEnd.multiplied(multipliers: (x: bounds.width, y: bounds.height))
    let a = ab.p1
    let b = ab.p2

    // 2. Calculate perpendicular bisector
    let cd = ab.perpendicularBisector

    // 3. Scale to square coordinates
    let multipliers = calculateMultipliers(bounds: bounds)
    let lineSegmentCD = cd.multiplied(multipliers: multipliers)

    // 4. Create scaled perpendicular bisector
    let lineSegmentEF = lineSegmentCD.perpendicularBisector

    // 5. Unscale back to rectangle
    let ef = lineSegmentEF.divided(divisors: multipliers)

    // 6. Extend line
    let efLine = ef.line

    // 7. Extend two lines from a and b parallel to cd
    let aParallelLine = Line(m: cd.slope, p: a)
    let bParallelLine = Line(m: cd.slope, p: b)

    // 8. Find the intersection of these lines
    let g = efLine.intersection(with: aParallelLine)
    let h = efLine.intersection(with: bParallelLine)

    if let g = g, let h = h {
      // 9. Convert to relative coordinates
      let gh = LineSegment(g, h)
      let result = gh.divided(divisors: (x: bounds.width, y: bounds.height))
      return (result.p1, result.p2)
    }
    return (start, end)
  }

  private static func unitTest() {
    let w = 320.0
    let h = 60.0
    let bounds = CGSize(width: w, height: h)
    let a = CGPoint(x: 138.5, y: 11.5)
    let b = CGPoint(x: 151.5, y: 53.5)
    let ab = LineSegment(a, b)
    let startEnd = ab.divided(divisors: (x: bounds.width, y: bounds.height))
    let start = startEnd.p1
    let end = startEnd.p2

    let points = fixPoints(start: start, end: end, bounds: bounds)

    let pointsSegment = LineSegment(points.0, points.1)
    let result = pointsSegment.multiplied(multipliers: (x: bounds.width, y: bounds.height))

    print(result.p1) // expected: (90.6119039567129, 26.3225059181603)
    print(result.p2) // expected: (199.388096043287, 38.6774940818397)
  }
}

private func calculateMultipliers(bounds: CGSize) -> (x: CGFloat, y: CGFloat) {
  if bounds.height <= bounds.width {
    return (x: 1, y: bounds.width/bounds.height)
  } else {
    return (x: bounds.height/bounds.width, y: 1)
  }
}

private struct LineSegment {
  let p1: CGPoint
  let p2: CGPoint

  init(_ p1: CGPoint, _ p2: CGPoint) {
    self.p1 = p1
    self.p2 = p2
  }

  init(p1: CGPoint, m: CGFloat, distance: CGFloat) {
    self.p1 = p1

    let line = Line(m: m, p: p1)
    let measuringPoint = line.point(x: p1.x + 1)
    let measuringDeltaH = LineSegment(p1, measuringPoint).distance

    let deltaX = distance/measuringDeltaH
    self.p2 = line.point(x: p1.x + deltaX)
  }

  var length: CGFloat {
    let dx = p2.x - p1.x
    let dy = p2.y - p1.y
    return sqrt(dx * dx + dy * dy)
  }
  var distance: CGFloat {
    return p1.x <= p2.x ? length : -length
  }
  var midpoint: CGPoint {
    return CGPoint(x: (p1.x + p2.x)/2, y: (p1.y + p2.y)/2)
  }
  var slope: CGFloat {
    return (p2.y-p1.y)/(p2.x-p1.x)
  }
  var perpendicularSlope: CGFloat {
    return -1/slope
  }
  var line: Line {
    return Line(p1, p2)
  }
  var perpendicularBisector: LineSegment {
    let p1 = LineSegment(p1: midpoint, m: perpendicularSlope, distance: -distance/2).p2
    let p2 = LineSegment(p1: midpoint, m: perpendicularSlope, distance: distance/2).p2
    return LineSegment(p1, p2)
  }

  func multiplied(multipliers: (x: CGFloat, y: CGFloat)) -> LineSegment {
    return LineSegment(
      CGPoint(x: p1.x * multipliers.x, y: p1.y * multipliers.y),
      CGPoint(x: p2.x * multipliers.x, y: p2.y * multipliers.y))
  }
  func divided(divisors: (x: CGFloat, y: CGFloat)) -> LineSegment {
    return multiplied(multipliers: (x: 1/divisors.x, y: 1/divisors.y))
  }
}

private struct Line {
  let m: CGFloat
  let b: CGFloat

  /// y = mx+b
  init(m: CGFloat, b: CGFloat) {
    self.m = m
    self.b = b
  }

  /// y-y1 = m(x-x1)
  init(m: CGFloat, p: CGPoint) {
    // y = m(x-x1) + y1
    // y = mx-mx1 + y1
    // y = mx + (y1 - mx1)
    // b = y1 - mx1
    self.m = m
    self.b = p.y - m*p.x
  }

  init(_ p1: CGPoint, _ p2: CGPoint) {
    self.init(m: LineSegment(p1, p2).slope, p: p1)
  }

  func y(x: CGFloat) -> CGFloat {
    return m*x + b
  }

  func point(x: CGFloat) -> CGPoint {
    return CGPoint(x: x, y: y(x: x))
  }

  func intersection(with line: Line) -> CGPoint? {
    // Line 1: y = mx + b
    // Line 2: y = nx + c
    // mx+b = nx+c
    // mx-nx = c-b
    // x(m-n) = c-b
    // x = (c-b)/(m-n)
    let n = line.m
    let c = line.b
    if m-n == 0 {
      // lines are parallel
      return nil
    }
    let x = (c-b)/(m-n)
    return point(x: x)
  }
}
</code>```

Proof it works regardless of rectangle size

I tried this with a view size=320x60, gradient=[red@0,green@0.5,blue@1], startPoint = (0,1), and endPoint = (1,0).

Sketch 3:

Actual generated iOS screenshot using the code above:

Note that the angle of the green line looks 100% accurate. The difference lies in how the red and blue are blended. I can't tell if that's because I'm calculating the start/end points incorrectly, or if it's just a difference in how Apple blends gradients vs. how Sketch blends gradients.

Title: CAGradientLayer diagonal gradient

Body:
I use the following CAGradientLayer:

let layer = CAGradientLayer()
layer.colors = [
    UIColor.redColor().CGColor,
    UIColor.greenColor().CGColor,
    UIColor.blueColor().CGColor
]
layer.startPoint = CGPointMake(0, 1)
layer.endPoint = CGPointMake(1, 0)
layer.locations = [0.0, 0.6, 1.0]

But when I set bounds property for the layer, it just stretches a square gradient. I need a result like in Sketch 3 app image (see above).

How can I achieve this?

Body:
Update: Use context.drawLinearGradient() instead of CAGradientLayer in a manner similar to the following. It will draw gradients that are consistent with Sketch/Photoshop.

If you absolutely must use CAGradientLayer, then here is the math you'll need to use...

It took some time to figure out, but from careful observation, I found out that Apple's implementation of gradients in CAGradientLayer is pretty odd:

First it converts the view to a square.

Then it applies the gradient using start/end points.

The middle gradient will indeed form a 90 degree angle in this resolution.

Finally, it squishes the view down to the original size.

This means that the middle gradient will no longer form a 90 degree angle in the new size. This contradicts the behavior of virtually every other paint application: Sketch, Photoshop, etc.

If you want to implement start/end points as it works in Sketch, you'll need to translate the start/end points to account for the fact that Apple is going to squish the view.

Steps to perform (Diagrams)

Code

import UIKit

/// Last updated 4/3/17.
/// See https://stackoverflow.com/a/43176174 for more information.
public enum LinearGradientFixer {
  public static func fixPoints(start: CGPoint, end: CGPoint, bounds: CGSize) -> (CGPoint, CGPoint) {
    // Naming convention:
    // - a: point a
    // - ab: line segment from a to b
    // - abLine: line that passes through a and b
    // - lineAB: line that passes through A and B
    // - lineSegmentAB: line segment that passes from A to B

    if start.x == end.x || start.y == end.y {
      // Apple's implementation of horizontal and vertical gradients works just fine
      return (start, end)
    }

    // 1. Convert to absolute coordinates
    let startEnd = LineSegment(start, end)
    let ab = startEnd.multiplied(multipliers: (x: bounds.width, y: bounds.height))
    let a = ab.p1
    let b = ab.p2

    // 2. Calculate perpendicular bisector
    let cd = ab.perpendicularBisector

    // 3. Scale to square coordinates
    let multipliers = calculateMultipliers(bounds: bounds)
    let lineSegmentCD = cd.multiplied(multipliers: multipliers)

    // 4. Create scaled perpendicular bisector
    let lineSegmentEF = lineSegmentCD.perpendicularBisector

    // 5. Unscale back to rectangle
    let ef = lineSegmentEF.divided(divisors: multipliers)

    // 6. Extend line
    let efLine = ef.line

    // 7. Extend two lines from a and b parallel to cd
    let aParallelLine = Line(m: cd.slope, p: a)
    let bParallelLine = Line(m: cd.slope, p: b)

    // 8. Find the intersection of these lines
    let g = efLine.intersection(with: aParallelLine)
    let h = efLine.intersection(with: bParallelLine)

    if let g = g, let h = h {
      // 9. Convert to relative coordinates
      let gh = LineSegment(g, h)
      let result = gh.divided(divisors: (x: bounds.width, y: bounds.height))
      return (result.p1, result.p2)
    }
    return (start, end)
  }

  private static func unitTest() {
    let w = 320.0
    let h = 60.0
    let bounds = CGSize(width: w, height: h)
    let a = CGPoint(x: 138.5, y: 11.5)
    let b = CGPoint(x: 151.5, y: 53.5)
    let ab = LineSegment(a, b)
    let startEnd = ab.divided(divisors: (x: bounds.width, y: bounds.height))
    let start = startEnd.p1
    let end = startEnd.p2

    let points = fixPoints(start: start, end: end, bounds: bounds)

    let pointsSegment = LineSegment(points.0, points.1)
    let result = pointsSegment.multiplied(multipliers: (x: bounds.width, y: bounds.height))

    print(result.p1) // expected: (90.6119039567129, 26.3225059181603)
    print(result.p2) // expected: (199.388096043287, 38.6774940818397)
  }
}

private func calculateMultipliers(bounds: CGSize) -> (x: CGFloat, y: CGFloat) {
  if bounds.height <= bounds.width {
    return (x: 1, y: bounds.width/bounds.height)
  } else {
    return (x: bounds.height/bounds.width, y: 1)
  }
}

private struct LineSegment {
  let p1: CGPoint
  let p2: CGPoint

  init(_ p1: CGPoint, _ p2: CGPoint) {
    self.p1 = p1
    self.p2 = p2
  }

  init(p1: CGPoint, m: CGFloat, distance: CGFloat) {
    self.p1 = p1

    let line = Line(m: m, p: p1)
    let measuringPoint = line.point(x: p1.x + 1)
    let measuringDeltaH = LineSegment(p1, measuringPoint).distance

    let deltaX = distance/measuringDeltaH
    self.p2 = line.point(x: p1.x + deltaX)
  }

  var length: CGFloat {
    let dx = p2.x - p1.x
    let dy = p2.y - p1.y
    return sqrt(dx * dx + dy * dy)
  }
  var distance: CGFloat {
    return p1.x <= p2.x ? length : -length
  }
  var midpoint: CGPoint {
    return CGPoint(x: (p1.x + p2.x)/2, y: (p1.y + p2.y)/2)
  }
  var slope: CGFloat {
    return (p2.y-p1.y)/(p2.x-p1.x)
  }
  var perpendicularSlope: CGFloat {
    return -1/slope
  }
  var line: Line {
    return Line(p1, p2)
  }
  var perpendicularBisector: LineSegment {
    let p1 = LineSegment(p1: midpoint, m: perpendicularSlope, distance: -distance/2).p2
    let p2 = LineSegment(p1: midpoint, m: perpendicularSlope, distance: distance/2).p2
    return LineSegment(p1, p2)
  }

  func multiplied(multipliers: (x: CGFloat, y: CGFloat)) -> LineSegment {
    return LineSegment(
      CGPoint(x: p1.x * multipliers.x, y: p1.y * multipliers.y),
      CGPoint(x: p2.x * multipliers.x, y: p2.y * multipliers.y))
  }
  func divided(divisors: (x: CGFloat, y: CGFloat)) -> LineSegment {
    return multiplied(multipliers: (x: 1/divisors.x, y: 1/divisors.y))
  }
}

private struct Line {
  let m: CGFloat
  let b: CGFloat

  /// y = mx+b
  init(m: CGFloat, b: CGFloat) {
    self.m = m
    self.b = b
  }

  /// y-y1 = m(x-x1)
  init(m: CGFloat, p: CGPoint) {
    // y = m(x-x1) + y1
    // y = mx-mx1 + y1
    // y = mx + (y1 - mx1)
    // b = y1 - mx1
    self.m = m
    self.b = p.y - m*p.x
  }

  init(_ p1: CGPoint, _ p2: CGPoint) {
    self.init(m: LineSegment(p1, p2).slope, p: p1)
  }

  func y(x: CGFloat) -> CGFloat {
    return m*x + b
  }

  func point(x: CGFloat) -> CGPoint {
    return CGPoint(x: x, y: y(x: x))
  }

  func intersection(with line: Line) -> CGPoint? {
    // Line 1: y = mx + b
    // Line 2: y = nx + c
    // mx+b = nx+c
    // mx-nx = c-b
    // x(m-n) = c-b
    // x = (c-b)/(m-n)
    let n = line.m
    let c = line.b
    if m-n == 0 {
      // lines are parallel
      return nil
    }
    let x = (c-b)/(m-n)
    return point(x: x)
  }
}

Proof it works regardless of rectangle size

I tried this with a view size=320x60, gradient=[red@0,green@0.5,blue@1], startPoint = (0,1), and endPoint = (1,0).

Sketch 3:

Actual generated iOS screenshot using the code above:

Note that the angle of the green line looks 100% accurate. The difference lies in how the red and blue are blended. I can't tell if that's because I'm calculating the start/end points incorrectly, or if it's just a difference in how Apple blends gradients vs. how Sketch blends gradients.


问:
Custom list class in Python 3 with __get__ and __set__ attributes
I would like to write a custom list class in Python 3 like in this question How would I create a custom list class in python?, but unlike that question I would like to implement __get__ and __set__ methods. Although my class is similar to the list, but there are some magic operations hidden behind these methods. And so I would like to work with this variable like with list, like in main of my program (see below). I would like to know, how to move __get__ and __set__ methods (fget and fset respectively) from Foo class to MyList class to have only one class.

My current solution (also, I added output for each operation for clarity):

```<code>class MyList:

    def __init__(self, data=[]):
        print('MyList.__init__')
        self._mylist = data

    def __getitem__(self, key):
        print('MyList.__getitem__')
        return self._mylist[key]

    def __setitem__(self, key, item):
        print('MyList.__setitem__')
        self._mylist[key] = item

    def __str__(self):
        print('MyList.__str__')
        return str(self._mylist)

class Foo:

    def __init__(self, mylist=[]):
        self._mylist = MyList(mylist)

    def fget(self):
        print('Foo.fget')
        return self._mylist

    def fset(self, data):
        print('Foo.fset')
        self._mylist = MyList(data)

    mylist = property(fget, fset, None, 'MyList property')

if __name__ == '__main__':
    foo = Foo([1, 2, 3])
    # >>> MyList.__init__
    print(foo.mylist)
    # >>> Foo.fget
    # >>> MyList.__str__
    # >>> [1, 2, 3]
    foo.mylist = [1, 2, 3, 4]
    # >>> Foo.fset
    # >>> MyList.__init__
    print(foo.mylist)
    # >>> Foo.fget
    # >>> MyList.__str__
    # >>> [1, 2, 3, 4]
    foo.mylist[0] = 0
    # >>> Foo.fget
    # >>> MyList.__setitem__
    print(foo.mylist[0])
    # >>> Foo.fget
    # >>> MyList.__getitem__
    # >>> 0
</code>```

Thank you in advance for any help.

How to move __get__ and __set__ methods (fget and fset respectively) from Foo class to MyList class to have only one class?

UPD:

Thanks a lot to @Blckknght! I tried to understand his answer and it works very well for me! It's exactly what I needed. As a result, I get the following code:

```<code>class MyList:
    def __init__(self, value=None):
        self.name = None
        if value is None:
            self.value = []
        else:
            self.value = value

    def __set_name__(self, owner, name):
        self.name = "_" + name

    def __get__(self, instance, owner):
        return getattr(instance, self.name)

    def __set__(self, instance, value):
        setattr(instance, self.name, MyList(value))

    def __getitem__(self, key):
        return self.value[key]

    def __setitem__(self, key, value):
        self.value[key] = value

    def append(self, value):
        self.value.append(value)

    def __str__(self):
        return str(self.value)

class Foo:
    my_list = MyList()

    def __init__(self):
        self.my_list = [1, 2, 3]
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list = [4, 5, 6, 7, 8]
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list[0] = 10
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list.append(7)
        print(type(self.my_list))       # <class '__main__.MyList'>
        print(self.my_list)             # [10, 5, 6, 7, 8, 7]

foo = Foo()
</code>```

I don't know, that's Pythonic way or not, but it works as I expected.

答:
While you can make your MyList class follow the descriptor protocol (which is what the __get__ and __set__ methods are for), you probably don't want to. That's because, to be useful, a descriptor must be placed as an attribute of a class, not as an attribute of an instance. The properties in your Foo class creating separate instances of MyList for each instance. That wouldn't work if the list was defined on the Foo class directly.

That's not to say that custom descriptors can't be useful. The property you're using in your Foo class is a descriptor. If you wanted to, you could write your own MyListAttr descriptor that does the same thing.

```<code>class MyListAttr(object):
    def __init__(self):
        self.name = None

    def __set_name__(self, owner, name):     # this is used in Pyton 3.6+
        self.name = "_" + name

    def find_name(self, cls):  # this is used on earlier versions that don't support set_name
        for name in dir(cls):
            if getattr(cls, name) is self:
                self.name = "_" + name
                return
        raise TypeError()

    def __get__(self, obj, owner):
        if obj is None:
           return self
        if self.name is None:
            self.find_name(owner)
        return getattr(obj, self.name)

    def __set__(self, obj, value):
        if self.name is None:
            self.find_name(type(obj))
        setattr(obj, self.name, MyList(value))

class Foo(object):
    mylist = MyListAttr() # create the descriptor as a class variable

    def __init__(self, data=None):
        if data is None:
            data = []

        self.mylist = data    # this invokes the __set__ method of the descriptor!
</code>```

The MyListAttr class is more complicated than it otherwise might be because I try to have the descriptor object find its own name. That's not easy to figure out in older versions of Python. Starting with Python 3.6, it's much easier (because the __set_name__ method will be called on the descriptor when it is assigned as a class variable). A lot of the code in the class could be removed if you only needed to support Python 3.6 and later (you wouldn't need find_name or any of the code that calls it in __get__ and __set__).

It might not seem worth writing a long descriptor class like MyListAttr to do what you were able to do with less code using a property. That's probably correct if you only have one place you want to use the descriptor. But if you may have many classes (or many attributes within a single class) where you want the same special behavior, you will benefit from packing the behavior into a descriptor rather than writing a lot of very similar property getter and setter methods.

You might not have noticed, but I also made a change to the Foo class that is not directly related to the descriptor use. The change is to the default value for data. Using a mutable object like a list as a default argument is usually a very bad idea, as that same object will be shared by all calls to the function without an argument (so all Foo instances not initialized with data would share the same list). It's better to use a sentinel value (like None) and replace the sentinel with what you really want (a new empty list in this case). You probably should fix this issue in your MyList.__init__ method too.

Body:
I would like to write a custom list class in Python 3 like in this question How would I create a custom list class in python?, but unlike that question I would like to implement __get__ and __set__ methods. Although my class is similar to the list, but there are some magic operations hidden behind these methods. And so I would like to work with this variable like with list, like in main of my program (see below). I would like to know, how to move __get__ and __set__ methods (fget and fset respectively) from Foo class to MyList class to have only one class.

My current solution (also, I added output for each operation for clarity):

class MyList:

    def __init__(self, data=[]):
        print('MyList.__init__')
        self._mylist = data

    def __getitem__(self, key):
        print('MyList.__getitem__')
        return self._mylist[key]

    def __setitem__(self, key, item):
        print('MyList.__setitem__')
        self._mylist[key] = item

    def __str__(self):
        print('MyList.__str__')
        return str(self._mylist)

class Foo:

    def __init__(self, mylist=[]):
        self._mylist = MyList(mylist)

    def fget(self):
        print('Foo.fget')
        return self._mylist

    def fset(self, data):
        print('Foo.fset')
        self._mylist = MyList(data)

    mylist = property(fget, fset, None, 'MyList property')

if __name__ == '__main__':
    foo = Foo([1, 2, 3])
    # >>> MyList.__init__
    print(foo.mylist)
    # >>> Foo.fget
    # >>> MyList.__str__
    # >>> [1, 2, 3]
    foo.mylist = [1, 2, 3, 4]
    # >>> Foo.fset
    # >>> MyList.__init__
    print(foo.mylist)
    # >>> Foo.fget
    # >>> MyList.__str__
    # >>> [1, 2, 3, 4]
    foo.mylist[0] = 0
    # >>> Foo.fget
    # >>> MyList.__setitem__
    print(foo.mylist[0])
    # >>> Foo.fget
    # >>> MyList.__getitem__
    # >>> 0

Thank you in advance for any help.

How to move __get__ and __set__ methods (fget and fset respectively) from Foo class to MyList class to have only one class?

UPD:

Thanks a lot to @Blckknght! I tried to understand his answer and it works very well for me! It's exactly what I needed. As a result, I get the following code:

class MyList:
    def __init__(self, value=None):
        self.name = None
        if value is None:
            self.value = []
        else:
            self.value = value

    def __set_name__(self, owner, name):
        self.name = "_" + name

    def __get__(self, instance, owner):
        return getattr(instance, self.name)

    def __set__(self, instance, value):
        setattr(instance, self.name, MyList(value))

    def __getitem__(self, key):
        return self.value[key]

    def __setitem__(self, key, value):
        self.value[key] = value

    def append(self, value):
        self.value.append(value)

    def __str__(self):
        return str(self.value)

class Foo:
    my_list = MyList()

    def __init__(self):
        self.my_list = [1, 2, 3]
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list = [4, 5, 6, 7, 8]
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list[0] = 10
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list.append(7)
        print(type(self.my_list))       # <class '__main__.MyList'>
        print(self.my_list)             # [10, 5, 6, 7, 8, 7]

foo = Foo()

I don't know, that's Pythonic way or not, but it works as I expected.

Body:
While you can make your MyList class follow the descriptor protocol (which is what the __get__ and __set__ methods are for), you probably don't want to. That's because, to be useful, a descriptor must be placed as an attribute of a class, not as an attribute of an instance. The properties in your Foo class creating separate instances of MyList for each instance. That wouldn't work if the list was defined on the Foo class directly.

That's not to say that custom descriptors can't be useful. The property you're using in your Foo class is a descriptor. If you wanted to, you could write your own MyListAttr descriptor that does the same thing.

class MyListAttr(object):
    def __init__(self):
        self.name = None

    def __set_name__(self, owner, name):     # this is used in Pyton 3.6+
        self.name = "_" + name

    def find_name(self, cls):  # this is used on earlier versions that don't support set_name
        for name in dir(cls):
            if getattr(cls, name) is self:
                self.name = "_" + name
                return
        raise TypeError()

    def __get__(self, obj, owner):
        if obj is None:
           return self
        if self.name is None:
            self.find_name(owner)
        return getattr(obj, self.name)

    def __set__(self, obj, value):
        if self.name is None:
            self.find_name(type(obj))
        setattr(obj, self.name, MyList(value))

class Foo(object):
    mylist = MyListAttr() # create the descriptor as a class variable

    def __init__(self, data=None):
        if data is None:
            data = []

        self.mylist = data    # this invokes the __set__ method of the descriptor!

The MyListAttr class is more complicated than it otherwise might be because I try to have the descriptor object find its own name. That's not easy to figure out in older versions of Python. Starting with Python 3.6, it's much easier (because the __set_name__ method will be called on the descriptor when it is assigned as a class variable). A lot of the code in the class could be removed if you only needed to support Python 3.6 and later (you wouldn't need find_name or any of the code that calls it in __get__ and __set__).

It might not seem worth writing a long descriptor class like MyListAttr to do what you were able to do with less code using a property. That's probably correct if you only have one place you want to use the descriptor. But if you may have many classes (or many attributes within a single class) where you want the same special behavior, you will benefit from packing the behavior into a descriptor rather than writing a lot of very similar property getter and setter methods.

You might not have noticed, but I also made a change to the Foo class that is not directly related to the descriptor use. The change is to the default value for data. Using a mutable object like a list as a default argument is usually a very bad idea, as that same object will be shared by all calls to the function without an argument (so all Foo instances not initialized with data would share the same list). It's better to use a sentinel value (like None) and replace the sentinel with what you really want (a new empty list in this case). You probably should fix this issue in your MyList.__init__ method too.


问:
Collect stdout logs for a shell script that runs inside another shell script
I have a shell script called load_data.sh that runs inside a shell script called shell.sh

The contents of shell.sh

```<code>xargs --max-procs 10 -n 1 sh load_data.sh < tables.txt
</code>```

This shell script runs on 10 tables at the same time in the tables.txt

Now I want to collect the Full logs of the load_data.sh So I did

```<code>xargs --max-procs 10 -n 1 sh load_data.sh < tables.txt |& tee-a logs.txt
</code>```

But I am getting a mix of all the logs. What I want is the logs should be 1st table log then 2nd table log and then 3rd table logs and so on...

Is it possible to achieve that. If so how can I achieve that?

答:
You can solve your problem by creating a separate logfile for each time your script is run.  To get the logfiles to be created in sequence you can use the 'nl' utility to number each line of input.

```<code>nl -n rz tables.txt | xargs -n 2 --max-procs 10 sh -c './load_data.sh "$1" > log-$0'
</code>```

Will produced logfiles in sequence

```<code>log-001
log-002
log-003
..
</code>```

To turn that back into one file you can just use 'cat'

```<code>cat log* > result
</code>```

Body:
I have a shell script called load_data.sh that runs inside a shell script called shell.sh

The contents of shell.sh

xargs --max-procs 10 -n 1 sh load_data.sh < tables.txt

This shell script runs on 10 tables at the same time in the tables.txt

Now I want to collect the Full logs of the load_data.sh So I did

xargs --max-procs 10 -n 1 sh load_data.sh < tables.txt |& tee-a logs.txt

But I am getting a mix of all the logs. What I want is the logs should be 1st table log then 2nd table log and then 3rd table logs and so on...

Is it possible to achieve that. If so how can I achieve that?

Body:
You can solve your problem by creating a separate logfile for each time your script is run.  To get the logfiles to be created in sequence you can use the 'nl' utility to number each line of input.

nl -n rz tables.txt | xargs -n 2 --max-procs 10 sh -c './load_data.sh "$1" > log-$0'

Will produced logfiles in sequence

log-001
log-002
log-003
..

To turn that back into one file you can just use 'cat'

cat log* > result


问:
Something Sort or Filter..iguess
can you help me because i want to display on the report viewer the dates that has no data recorded or inserted........ for example.. MARCH 2,3,5,7 has record.. i want to display on the report viewer that has no record MARCH 4,6.....something like that.
enter image description here</p>

答:
you can use this code to build up your calendar then just a matter of join the calendar to your table</p>

```<code>declare @mm varchar(2) = '02'
declare @yy varchar(4) = '2017'

select cast(@yy + '-' + @mm + '-' + cast(x.dd as varchar(2)) as date)
 from
(select number [dd] from master..spt_values
where type = 'p'
and number between 1 and 31
) x
where  isdate(cast(@yy + '-' + @mm + '-' + cast(x.dd as varchar(2)) as varchar(max))) = 1
order by x.dd
</code>```

Title: Something Sort or Filter..iguess

Body:
you can use this code to build up your calendar then just a matter of join the calendar to your table

declare @mm varchar(2) = '02'
declare @yy varchar(4) = '2017'

select cast(@yy + '-' + @mm + '-' + cast(x.dd as varchar(2)) as date)
 from
(select number [dd] from master..spt_values
where type = 'p'
and number between 1 and 31
) x
where  isdate(cast(@yy + '-' + @mm + '-' + cast(x.dd as varchar(2)) as varchar(max))) = 1
order by x.dd


问:
ImportError: No module named requests
I tried importing requests:

```<code>import requests
</code>```

But I get an error:

ImportError: No module named requests

答:
On Windows Open Command Line

```<code>pip3 install requests
</code>```

ContentLicense: CC BY-SA 4.0

Title: ImportError: No module named requests

Body:
I tried importing requests:

import requests

But I get an error:

ImportError: No module named requests

Body:
On Windows Open Command Line

pip3 install requests


问:
git --bare clone analogue for Hg (Mercurial)
I want to checkout only history of a repository.

Does there any option to clone history as like as git --bare clone <repo_url> option?

答: @vampire has your answer for a new clone.  For an existing one hg update null does the job. That checks out the null revision, which is the revision before revision 0, and contains no files.  If you check out that revision you local files go away and you've got a bare clone.


问:
Delphi: Freeing a dynamic control at runtime
Is there a failsafe way of freeing a Delphi control?

I have a TStringGrid descendent which I am "embedding" a custom control in it for an inplace editor. When the user navigates within the cells of the grid via the tab key or arrow keys, I need to create a dynamic control if the cell is editable. I have hooked the needed events and am utilizing the OnKeyDown event of my custom control to pass the navigation keys back to the parent TStringGrid.

Previously, the TStringGrid descendent would simply call FreeAndNil on the embedded control, but under some circumstances this would cause access violations inside of UpdateUIState/GetParentForm.  Looking at the call stack, it appears that sometimes after the control was free'd, a WM_KEYDOWN (TWinControl.WMKeyDown) message was still happening.

I've all ready looked at and implemented the changes discussed in How to free control inside its event handler?. This appears to have resolved the issue, but I am wondering if there are any other cavet's to this approach.

In effect, this workaround has simply delayed the destruction of the control until after all the existing messages on the queue at the time the CM_RELEASE message was posted.

Would it not be possible that after the CM_RELEASE was posted, another WM_KEY* or similar message could all ready have been posted to the message queue?

My current CM_RELEASE handler looks like:

```<code>procedure TMyCustomControl.HandleRelease(var Msg: TMessage);
begin
  Free;
end;
</code>```

So, will this be safe in all instances or should I do something to clear any other messages from the queue? ( SendMessage(Self.Handle, WM_DESTROY, 0, 0) comes to mind )

答:
In general you should not destroy a control in an event-handler of that control.

But since your function is a plain non virtual message handler which is never called from internal code in that control you should be ok. I don't like too too much from a style point of view, but I think it's ok for your use-case.

But a custom message might be cleaner.

Would it not be possible that after the CM_RELEASE was posted, another WM_KEY* or similar message could all ready have been posted to the message queue?

If messages in queue would cause big problems you could never safely destroy a control since messages can be posted from other threads and applications. Just make sure the correct functioning of your application doesn't depends on those messages being handles in every case.

Body:
Is there a failsafe way of freeing a Delphi control?

I have a TStringGrid descendent which I am "embedding" a custom control in it for an inplace editor. When the user navigates within the cells of the grid via the tab key or arrow keys, I need to create a dynamic control if the cell is editable. I have hooked the needed events and am utilizing the OnKeyDown event of my custom control to pass the navigation keys back to the parent TStringGrid.

Previously, the TStringGrid descendent would simply call FreeAndNil on the embedded control, but under some circumstances this would cause access violations inside of UpdateUIState/GetParentForm.  Looking at the call stack, it appears that sometimes after the control was free'd, a WM_KEYDOWN (TWinControl.WMKeyDown) message was still happening.

I've all ready looked at and implemented the changes discussed in How to free control inside its event handler?. This appears to have resolved the issue, but I am wondering if there are any other cavet's to this approach.

In effect, this workaround has simply delayed the destruction of the control until after all the existing messages on the queue at the time the CM_RELEASE message was posted.

Would it not be possible that after the CM_RELEASE was posted, another WM_KEY* or similar message could all ready have been posted to the message queue?

My current CM_RELEASE handler looks like:

procedure TMyCustomControl.HandleRelease(var Msg: TMessage);
begin
  Free;
end;

So, will this be safe in all instances or should I do something to clear any other messages from the queue? ( SendMessage(Self.Handle, WM_DESTROY, 0, 0) comes to mind )


答:
As said in the first comment you can directly try using awk something like:

```<code>ls -l /etc/networks | awk '{print $NF}' | awk -F "/" '{print $NF}'
</code>```

It should be possible to trim these 2 awk pipes as well

Title: grep to match filename in full path

Body:
As said in the first comment you can directly try using awk something like:

ls -l /etc/networks | awk '{print $NF}' | awk -F "/" '{print $NF}'

It should be possible to trim these 2 awk pipes as well


问:
removing index.php in hmvc
i want to removing index.php in hmvc code igniter , when i type the url without index.php it's running well but when i process to other controller the url is automatically showing index.php after my codeigniter folder.

example i type :

```<code>localhost/ci_hmvc/user/login
</code>```

and the result when i process to other controller is :

```<code>localhost/ci_hmvc/index.php/user/dashboard
</code>```

and my .htaccess

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /ci_hmvc/index.php/$1 [L]
</IfModule>
</code>```

please any one help me

答:
You can make changes in config.php which is in config folder
You can see the line

```<code>$config['index_page'] = 'index.php';
</code>```

Change this line in to

```<code>$config['index_page'] = '';
</code>```

I hope this will helps you

Title: removing index.php in hmvc

Body:
i want to removing index.php in hmvc code igniter , when i type the url without index.php it's running well but when i process to other controller the url is automatically showing index.php after my codeigniter folder.

example i type :

localhost/ci_hmvc/user/login

and the result when i process to other controller is :

localhost/ci_hmvc/index.php/user/dashboard

and my .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /ci_hmvc/index.php/$1 [L]
</IfModule>

please any one help me

Body:
You can make changes in config.php which is in config folder
You can see the line

$config['index_page'] = 'index.php';

Change this line in to

$config['index_page'] = '';

I hope this will helps you


问:
Iteration of Hash: JekyII
Hi I was trying to extract this ("Polk County", "short_name" => "Polk County")
in the 3rd row of this Hash but I can seem to get just the "Polk County"
this is my current code:

```<code>{% for county_hash in location.address_components %}
 {% for county in county_hash %}
  {{ county.long_name }}
 {% endfor %}
{% endfor %}

{
"0" => {
    "long_name" => "426", "short_name" => "426", "types" => ["street_number"]
}, "1" => {
    "long_name" => "Swanee Drive", "short_name" => "Swanee Dr", "types" => ["route"]
}, "2" => {
    "long_name" => "Livingston", "short_name" => "Livingston", "types" => ["locality", "political"]
}, "3" => {
    "long_name" => "Polk County", "short_name" => "Polk County", "types" => ["administrative_area_level_2", "political"]
}, "4" => {
    "long_name" => "Texas", "short_name" => "TX", "types" => ["administrative_area_level_1", "political"]
}, "5" => {
    "long_name" => "United States", "short_name" => "US", "types" => ["country", "political"]
}, "6" => {
    "long_name" => "77351", "short_name" => "77351", "types" => ["postal_code"]
}, "7" => {
    "long_name" => "8238", "short_name" => "8238", "types" => ["postal_code_suffix"]
}
</code>```

}

答:
Thanks for the help,
This method works for me.

```<code>{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {% if county.long_name contains 'County' %}
     {{ county.long_name }}
    {% endif %}
  {% endfor %}
{% endfor %}
</code>```

breadcrumbs

Title: Iteration of Hash: JekyII

Body:
Hi I was trying to extract this ("Polk County", "short_name" => "Polk County")
in the 3rd row of this Hash but I can seem to get just the "Polk County"
this is my current code:

{% for county_hash in location.address_components %}
 {% for county in county_hash %}
  {{ county.long_name }}
 {% endfor %}
{% endfor %}

{
"0" => {
    "long_name" => "426", "short_name" => "426", "types" => ["street_number"]
}, "1" => {
    "long_name" => "Swanee Drive", "short_name" => "Swanee Dr", "types" => ["route"]
}, "2" => {
    "long_name" => "Livingston", "short_name" => "Livingston", "types" => ["locality", "political"]
}, "3" => {
    "long_name" => "Polk County", "short_name" => "Polk County", "types" => ["administrative_area_level_2", "political"]
}, "4" => {
    "long_name" => "Texas", "short_name" => "TX", "types" => ["administrative_area_level_1", "political"]
}, "5" => {
    "long_name" => "United States", "short_name" => "US", "types" => ["country", "political"]
}, "6" => {
    "long_name" => "77351", "short_name" => "77351", "types" => ["postal_code"]
}, "7" => {
    "long_name" => "8238", "short_name" => "8238", "types" => ["postal_code_suffix"]
}

}

Body:
Thanks for the help,
This method works for me.

{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {% if county.long_name contains 'County' %}
     {{ county.long_name }}
    {% endif %}
  {% endfor %}
{% endfor %}

breadcrumbs


问:
Why is it "impossible" to implement garbage collection in C because of weak typing?
I was told by a rather smart person that you cannot implement garbage collection in C because of it's weakly typed. The basic idea seems to be that C gives you too much freedom. He mentioned casting pointers without type checking...

I don't really grok the idea. Can someone give me an explanation and possibly a code sample of why this wouldn't work.

NOTE: Obviously C is about speed and why would you want to add garbage collection? I'm just curious really.

答:
It's perfectly possible to implement whatever memory manager you can think of in C. The catch is that you then have to use its allocation/deallocation functions exclusively and restrict your 'pointer magic' to things it can keep track of. Aditionally, the memory management might be restricted to certain supported types.

For example, Objective-C's retain/release system and autorelease pools are basically memory managers implemented in C. Many libraries also implement their own, simple form of memory management like reference counting.

Then, there's the Boehm garbage collector. To use it, just replace your malloc()/realloc() calls with the Boehm versions and you never have to call free() again. Read about the possible issues with this approach.

Also, check this wikipedia page for a quick overview on how conservative garbage collectors work.

OwnerDisplayName: Tim Merrifield

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: Christoph

LastEditorDisplayName: Christoph


问:
iPad - How to move Mulitple UIViews side-by-side
How to move multiple UIViews Side-by-Side just like an twitter application working in iPad. With full of effects animation and rotations.</p>

答:
Take a look at view animations:

http://www.switchonthecode.com/tutorials/creating-basic-animations-on-iphone


问:
C Programming - Sprintf & String Arrays
I've been reading a few other questions from folks on arrays of strings.  I drew some insight and changed my code, but one problem I'm having is incorporating sprintf.

High level, the purpose of this will ultimately be a function to fopen/fread a variable number of files in a directory. But getting hung up on this string manipulation portion.

I'd like to increment my pointers within sprintf, but I'm getting segmentation issues.  Any thoughts on fixing what I have or perhaps a different route? MAX = 20, FILES = 4.

```<code>char fName_A[MAX];
char fName_B[MAX];
char * ptr_A[FILES];
char * ptr_B[FILES];
int i;

for(i=0; i<FILES; i++){
    sprintf(fName_A, "waveA00%d.bin", i);
    sprintf(fName_B, "waveB00%d.bin", i);

    ptr_A[i] = fName_A;
    ptr_B[i] = fName_B;

    printf("Ch1 File Number %d is named %s\n", i, *(ptr_A+i));
    printf("Ch2 File Number %d is named %s\n", i, *(ptr_B+i));
}

printf("fName_A[0] = %s\n", *ptr_A);
printf("fName_A[1] = %s\n", *(ptr_A + 1));
printf("fName_A[2] = %s\n", *(ptr_A + 2));
printf("fName_A[3] = %s\n", *(ptr_A + 3));

return 0;
</code>```

答:
You are not allocating any memory for strings associated with Ptr_A and Ptr_B, just setting the pointers to point to the buffers fName_A and fName_B, so when you check at the end, they all point to the last string stored in these buffers.

Fix it by allocating store for each filename in A and B as an array of chars, instead of using pointers. Here's an example:

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

#define MAX   100
#define FILES 4

int main(int argc, char** argv)
{
 char fName_A[MAX];
 char fName_B[MAX];
 char A[FILES][MAX];
 char B[FILES][MAX];
 int i;

 for(i=0; i<FILES; i++){
    sprintf(fName_A, "waveA00%d.bin", i);
    sprintf(fName_B, "waveB00%d.bin", i);

    strcpy(A[i], fName_A);
    strcpy(B[i], fName_B);

    printf("Ch1 File Number %d is named %s\n", i, A[i]);
    printf("Ch2 File Number %d is named %s\n", i, B[i]);
 }

 for(i=0; i<FILES; i++) {
    printf("A[%d] = %s\n", i, A[i]);
    printf("B[%d] = %s\n", i, B[i]);
 }
}
</code>```

This will output the following:

```<code>Ch1 File Number 0 is named waveA000.bin
Ch2 File Number 0 is named waveB000.bin
Ch1 File Number 1 is named waveA001.bin
Ch2 File Number 1 is named waveB001.bin
Ch1 File Number 2 is named waveA002.bin
Ch2 File Number 2 is named waveB002.bin
Ch1 File Number 3 is named waveA003.bin
Ch2 File Number 3 is named waveB003.bin
A[0] = waveA000.bin
B[0] = waveB000.bin
A[1] = waveA001.bin
B[1] = waveB001.bin
A[2] = waveA002.bin
B[2] = waveB002.bin
A[3] = waveA003.bin
B[3] = waveB003.bin
</code>```

Title: C Programming - Sprintf & String Arrays

Body:
I've been reading a few other questions from folks on arrays of strings.  I drew some insight and changed my code, but one problem I'm having is incorporating sprintf.

High level, the purpose of this will ultimately be a function to fopen/fread a variable number of files in a directory. But getting hung up on this string manipulation portion.

I'd like to increment my pointers within sprintf, but I'm getting segmentation issues.  Any thoughts on fixing what I have or perhaps a different route? MAX = 20, FILES = 4.

char fName_A[MAX];
char fName_B[MAX];
char * ptr_A[FILES];
char * ptr_B[FILES];
int i;

for(i=0; i<FILES; i++){
    sprintf(fName_A, "waveA00%d.bin", i);
    sprintf(fName_B, "waveB00%d.bin", i);

    ptr_A[i] = fName_A;
    ptr_B[i] = fName_B;

    printf("Ch1 File Number %d is named %s\n", i, *(ptr_A+i));
    printf("Ch2 File Number %d is named %s\n", i, *(ptr_B+i));
}

printf("fName_A[0] = %s\n", *ptr_A);
printf("fName_A[1] = %s\n", *(ptr_A + 1));
printf("fName_A[2] = %s\n", *(ptr_A + 2));
printf("fName_A[3] = %s\n", *(ptr_A + 3));

return 0;

Body:
You are not allocating any memory for strings associated with Ptr_A and Ptr_B, just setting the pointers to point to the buffers fName_A and fName_B, so when you check at the end, they all point to the last string stored in these buffers.

Fix it by allocating store for each filename in A and B as an array of chars, instead of using pointers. Here's an example:

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

#define MAX   100
#define FILES 4

int main(int argc, char** argv)
{
 char fName_A[MAX];
 char fName_B[MAX];
 char A[FILES][MAX];
 char B[FILES][MAX];
 int i;

 for(i=0; i<FILES; i++){
    sprintf(fName_A, "waveA00%d.bin", i);
    sprintf(fName_B, "waveB00%d.bin", i);

    strcpy(A[i], fName_A);
    strcpy(B[i], fName_B);

    printf("Ch1 File Number %d is named %s\n", i, A[i]);
    printf("Ch2 File Number %d is named %s\n", i, B[i]);
 }

 for(i=0; i<FILES; i++) {
    printf("A[%d] = %s\n", i, A[i]);
    printf("B[%d] = %s\n", i, B[i]);
 }
}

This will output the following:

Ch1 File Number 0 is named waveA000.bin
Ch2 File Number 0 is named waveB000.bin
Ch1 File Number 1 is named waveA001.bin
Ch2 File Number 1 is named waveB001.bin
Ch1 File Number 2 is named waveA002.bin
Ch2 File Number 2 is named waveB002.bin
Ch1 File Number 3 is named waveA003.bin
Ch2 File Number 3 is named waveB003.bin
A[0] = waveA000.bin
B[0] = waveB000.bin
A[1] = waveA001.bin
B[1] = waveB001.bin
A[2] = waveA002.bin
B[2] = waveB002.bin
A[3] = waveA003.bin
B[3] = waveB003.bin


问:
Check if timestamp older than 30 seconds
I am trying to determine if a timestamp is older than 30 seconds, but for some reason it is coming back as older than 30 seconds when it hasn't even been a couple seconds. </p>

<p>Example: https://ideone.com/KLIIBz </p>

```<code>public static Boolean cooldown(int id) {

    Calendar now = Calendar.getInstance();
    now.add(Calendar.SECOND, -secondsAgo);
    long timeAgo = now.getTimeInMillis();
    if ( cooldown.containsKey(id) ) {

        System.out.println(cooldown.get(id) + " | " + timeAgo);

        // Stored timestamp always older than timeAgo
        if ( cooldown.get(id) < timeAgo ) {

            cooldown.remove(id);

        } else {

            // This code should be executed, as I am running the function one after another from same UUID not even a second or two apart.
            return false;

        }

    }

    now = Calendar.getInstance();
    cooldown.put(id, now.getTimeInMillis());

    return true;

}
</code>```

答:
currentTimeMillis returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Can you explain why you use it.

Body:
I am trying to determine if a timestamp is older than 30 seconds, but for some reason it is coming back as older than 30 seconds when it hasn't even been a couple seconds.

Example: https://ideone.com/KLIIBz

public static Boolean cooldown(int id) {

    Calendar now = Calendar.getInstance();
    now.add(Calendar.SECOND, -secondsAgo);
    long timeAgo = now.getTimeInMillis();
    if ( cooldown.containsKey(id) ) {

        System.out.println(cooldown.get(id) + " | " + timeAgo);

        // Stored timestamp always older than timeAgo
        if ( cooldown.get(id) < timeAgo ) {

            cooldown.remove(id);

        } else {

            // This code should be executed, as I am running the function one after another from same UUID not even a second or two apart.
            return false;

        }

    }

    now = Calendar.getInstance();
    cooldown.put(id, now.getTimeInMillis());

    return true;

}


问:
How to substitute variable contents in a Windows batch file
I'm writing a simple script to substitute text in an environment variable with other text. The trouble I get is with the substituted or substituted text being pulled from other variables

```<code>SET a=The fat cat
ECHO %a%
REM Results in 'The fat cat'
ECHO %a:fat=thin%
REM Results in 'The thin cat'
</code>```

Works fine (output is 'The fat cat' and 'The thin cat'

However, if 'fat' or 'thin' are in variables, it doesn't work

```<code>SET b=fat
ECHO %a:%c%=thin%
REM _Should_ give 'The thin cat'.
REM _Actually_ gives '%a:fat=thin%' (the %c% is evaluated, but no further).

REM using delayed evaluation doesn't make any difference either
ECHO !a:%c%=thin!
REM Actual output is now '!a:fat=thin!'
</code>```

I know this can be done as I've seen it in blogs before, but I never saved the link to the blogs.

Anyone have any ideas?

PS. I'm running the scripts on Windows 7

PPS. I know this is easier in Perl/Python/other script language of choice, but I just want to know why something that should be easy is not immediately obvious.

PPPS. I've also tried the scripts with delayed expansion explicitly turned on

```<code>SETLOCAL enabledelayedexpansion
</code>```

This makes no difference.

答:
:: Use perl on %var% =~ s/$old/$new/

```<code>set var=The fat cat
set old=fat
set new=thin

ECHO before=%var%

for /f "delims=" %%m in ('echo %var% ^|perl -pe "s/%old%/%new%/" ') do set var=%%m

ECHO after=%var%
</code>```

Output:

```<code>before=The fat cat
after=The thin cat
</code>```

Body:
I'm writing a simple script to substitute text in an environment variable with other text. The trouble I get is with the substituted or substituted text being pulled from other variables

SET a=The fat cat
ECHO %a%
REM Results in 'The fat cat'
ECHO %a:fat=thin%
REM Results in 'The thin cat'

Works fine (output is 'The fat cat' and 'The thin cat'

However, if 'fat' or 'thin' are in variables, it doesn't work

SET b=fat
ECHO %a:%c%=thin%
REM _Should_ give 'The thin cat'.
REM _Actually_ gives '%a:fat=thin%' (the %c% is evaluated, but no further).

REM using delayed evaluation doesn't make any difference either
ECHO !a:%c%=thin!
REM Actual output is now '!a:fat=thin!'

I know this can be done as I've seen it in blogs before, but I never saved the link to the blogs.

Anyone have any ideas?

PS. I'm running the scripts on Windows 7

PPS. I know this is easier in Perl/Python/other script language of choice, but I just want to know why something that should be easy is not immediately obvious.

PPPS. I've also tried the scripts with delayed expansion explicitly turned on

SETLOCAL enabledelayedexpansion

This makes no difference.

Body:
:: Use perl on %var% =~ s/$old/$new/

set var=The fat cat
set old=fat
set new=thin

ECHO before=%var%

for /f "delims=" %%m in ('echo %var% ^|perl -pe "s/%old%/%new%/" ') do set var=%%m

ECHO after=%var%

Output:

before=The fat cat
after=The thin cat


问:
Mysql subquery not working properly with comma-separated value in column
I have a MySQL table Mapdetail that has resultTypeIds column storing a comma separated list of ids:

MapDetails

```<code>=============================
mapheaderid     |    resultTypeIds
=============================
54              |    1,4,-9999
</code>```

Now, when I try it as a subquery, it does not return me the correct result while if I hard-code (1,4,-9999) it works fine

WRONG - RETURNING 1 ROW ONLY

```<code>select * from resulttypes rt where rt.resulttypeid in
        (select md1.resulttypeids from mapdetail md1
            where md1.mapheaderid = 54)
</code>```

CORRECT - RETURNING 2 ROWS

```<code>select * from resulttypes rt where rt.resulttypeid in (1,4,-9999)
</code>```

答:
If you can't re-structure your DB (as mentioned in Comments). Try using FIND_IN_SET instead of IN

Try something like:

```<code>select * from resulttypes rt where FIND_IN_SET (rt.resulttypeid,
            (select md1.resulttypeids from mapdetail md1
            where md1.mapheaderid = 54))
</code>```

Body:
I have a MySQL table Mapdetail that has resultTypeIds column storing a comma separated list of ids:

MapDetails

=============================
mapheaderid     |    resultTypeIds
=============================
54              |    1,4,-9999

Now, when I try it as a subquery, it does not return me the correct result while if I hard-code (1,4,-9999) it works fine

WRONG - RETURNING 1 ROW ONLY

select * from resulttypes rt where rt.resulttypeid in
        (select md1.resulttypeids from mapdetail md1
            where md1.mapheaderid = 54)

CORRECT - RETURNING 2 ROWS

select * from resulttypes rt where rt.resulttypeid in (1,4,-9999)

Body:
If you can't re-structure your DB (as mentioned in Comments). Try using FIND_IN_SET instead of IN

Try something like:

select * from resulttypes rt where FIND_IN_SET (rt.resulttypeid,
            (select md1.resulttypeids from mapdetail md1
            where md1.mapheaderid = 54))


问:
crystal report & sub report
am developing a payroll project in vb.net with SQL server, in this am using SEAGATE crystal report for taking reports, if i use more than 10 sub reports in single report weather it affect my project efficiency or it will take more time </p>

答:
Actually it is hard to say, how your subreports affect performance. I've designed reports, where using subreports makes entire report run faster - sometimes it is not so easy to build underlying query to be more efficient than many simpler queries for subreports.

One example is A-B-A-C type reports, where there are many one-to-many relations from master table/query (A) to subtables/queries (B,C) AND users want to see all BC type data at once (not on-demand). For single query it would be A*B*C rows to process (and implement nasty logic to show-hide sections), using subreports you can deal with A*(B+C) total rows to process and display.

But when you use subreport to display only some total value, then often it is more efficient to aggregate it already in master view - takes less time both in server and while transmitting data. Crystal Reports formatting time is usually negligible compared to query execution time.

Like always, optimum strategy depends on particular report needs.

Title: crystal report & sub report


问:
Why is it valid to get string[0] even when it has not been initialized?
Consider this code

```<code>string str;
cout << str[0] << str.size();
</code>```

And what I get is not a run time error, but " 0", a 0 following a space. Why is this possible?

答:
str is not uninitialized, it's default initalized as an empty std::string; i.e. its size() is 0. And since C++11, the standard requires std::basic_string::operator[] to return a reference to the null character for this case.

If pos == size(), a reference to the character with value CharT() (the null character) is returned.

It's worth noting that before C++11, for the non-const version of operator[] this is undefined behavior, for the const version a reference to null character will be returned; and since C++11 for the non-const version, any modification to other character on the returned reference is undefined behavior.

BTW: Undefined behavior means anything is possible; it has not to be a runtime error.

Body:
Consider this code

string str;
cout << str[0] << str.size();

And what I get is not a run time error, but " 0", a 0 following a space. Why is this possible?


问:
Can we inherit singleton class?
Can we inherit singleton class?</p>

答:
Here's a possible way to handle a derived Singleton:</p>

```<code>public abstract class Singleton<T> where T : Singleton<T>, new() {

    private static readonly T s_instance = new T();

    protected Singleton() {
        if (s_instance != null) {
            string s = string.Format(
                "An instance of {0} already exists at {0}.instance. " +
                "That's what \"Singleton\" means. You can't create another.",
                typeof(T));
            throw new System.Exception(s);
        }
    }

    public static T instance { get { return s_instance; } }
}

public class MyClass : Singleton<MyClass> {

}
</code>```

Title: Can we inherit singleton class?

Body: Can we inherit singleton class?

Body:
Here's a possible way to handle a derived Singleton:

public abstract class Singleton<T> where T : Singleton<T>, new() {

    private static readonly T s_instance = new T();

    protected Singleton() {
        if (s_instance != null) {
            string s = string.Format(
                "An instance of {0} already exists at {0}.instance. " +
                "That's what \"Singleton\" means. You can't create another.",
                typeof(T));
            throw new System.Exception(s);
        }
    }

    public static T instance { get { return s_instance; } }
}

public class MyClass : Singleton<MyClass> {

}


问:
django rest framework changing id to url
Suppose, I have a model Collection and one-to-many relationship to CollectionImage

```<code>class Collection(models.Model):
    name = models.CharField(max_length=500)
    description = models.TextField(max_length=5000)
    publish = models.DateTimeField(auto_now=False, auto_now_add=True)
    author = models.CharField(max_length=500)

    def __str__(self):
        return self.name

class CollectionImage(models.Model):
    collection = models.ForeignKey('Collection', related_name='images')
    image = models.ImageField(height_field='height_field', width_field='width_field')
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)

    def __str__(self):
        return self.collection.name
</code>```

I created a Serializer class for my model

```<code>class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]
</code>```

and a API View

```<code>class CollectionList(ListAPIView):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer
</code>```

The problem that i have, is that the field images gives an array of ids, where i would like it to be an array of Image urls, is it possible to do ?

答:
Can set depth=1 to unfold all related models one level deep:

```<code>class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]
        depth = 1
</code>```

Body:
Suppose, I have a model Collection and one-to-many relationship to CollectionImage

class Collection(models.Model):
    name = models.CharField(max_length=500)
    description = models.TextField(max_length=5000)
    publish = models.DateTimeField(auto_now=False, auto_now_add=True)
    author = models.CharField(max_length=500)

    def __str__(self):
        return self.name

class CollectionImage(models.Model):
    collection = models.ForeignKey('Collection', related_name='images')
    image = models.ImageField(height_field='height_field', width_field='width_field')
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)

    def __str__(self):
        return self.collection.name

I created a Serializer class for my model

class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]

and a API View

class CollectionList(ListAPIView):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer

The problem that i have, is that the field images gives an array of ids, where i would like it to be an array of Image urls, is it possible to do ?

Body:
Can set depth=1 to unfold all related models one level deep:

class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]
        depth = 1


问:
void pointer in function call in C++ vs C
I have this piece of code that works in C but not C++, is that any way to make it work on both C and C++ ?

```<code>void foo(void* b)
{
   int *c = b;
   printf("%d\n",*c);

}

int main ()
{
 int a = 1000;

 foo(&a);
 return 0;
}
</code>```

output:

C++:

```<code>1 In function 'void foo(void*)':
2 Line 3: error: invalid conversion from 'void*' to 'int*'
3 compilation terminated due to -Wfatal-errors.
</code>```

C:

```<code>1000
</code>```

Please help

答:
Considering all the casting issues with both the languages, the correct way would be -

```<code>#ifdef __cplusplus
#define cast_to_intp(x) static_cast<int*>(x)
#else
#define cast_to_intp(x) (x)
#endif
</code>```

And then use

```<code>int *c = cast_to_intp(b);
</code>```

Body:
I have this piece of code that works in C but not C++, is that any way to make it work on both C and C++ ?

void foo(void* b)
{
   int *c = b;
   printf("%d\n",*c);

}

int main ()
{
 int a = 1000;

 foo(&a);
 return 0;
}

output:

C++:

1 In function 'void foo(void*)':
2 Line 3: error: invalid conversion from 'void*' to 'int*'
3 compilation terminated due to -Wfatal-errors.

C:

1000

Please help

Body:
Considering all the casting issues with both the languages, the correct way would be -

#ifdef __cplusplus
#define cast_to_intp(x) static_cast<int*>(x)
#else
#define cast_to_intp(x) (x)
#endif

And then use

int *c = cast_to_intp(b);


问:
Don't understand excel formula embedded in VBA
Can someone please explain this Excel formula inside the VBA code.

```<code>Range("U8").FormulaR1C1 = _
=IF(ISNA(VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE)=""True""),""No Title Found"",VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE))"
</code>```

I get that the IF is checking for the #N/A value. What I don't understand is what either of the VLOOKUPfunctions is doing exactly. What cell are being reference by the R1C1 notation? Why doesn't the column need to be specified? Then I don't get the 'C:\temp\MasterRecords.xls'!C2:C15 arguments. Thanks.

答:
In the formula

1) RC[-1] refers to the one cell left to the formula cell.

2) The Vlookup formula is referring to an external workbook C:\temp\MasterRecords.xls.

3) table_array C2:C15 used in Vlookup formula refers to $B:$O

4) Col_index_num 14 refers to the column O considering the table_array

The formula is written in R1C1 style and I suppose you are getting confused with C2:C15 because R is missing that only means here that whole columns are used in the formula i.e. $B:$O

Body:
Can someone please explain this Excel formula inside the VBA code.

Range("U8").FormulaR1C1 = _
=IF(ISNA(VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE)=""True""),""No Title Found"",VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE))"

I get that the IF is checking for the #N/A value. What I don't understand is what either of the VLOOKUPfunctions is doing exactly. What cell are being reference by the R1C1 notation? Why doesn't the column need to be specified? Then I don't get the 'C:\temp\MasterRecords.xls'!C2:C15 arguments. Thanks.


问:
How to make htaccess redirect on direct image access while allowing embedding
The scenario looks like this, say that I have a website that contains some images. I want to allow people to embed them on their site, but I also want to redirect when anybody tries to access the image directly.

One option is this

```<code>RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?imgzzz.com/.*$ [NC]
RewriteRule i/image_(\d+)\.(jpg|gif) - [F]
</code>```

which would deny any access from anywhere else than the site, but that doesn't allow embedding the image.

The second option is to ommit the second RewriteCond leaving only

```<code>RewriteCond %{HTTP_REFERER} !^$
RewriteRule i/image_(\d+)\.(jpg|gif) - [F]
</code>```

Which allows embedding, but the user can still access the image if he's comming from anywhere else than a bookmark.

Is there any way to make embedding available and at the same time doing redirect on direct access to the image?

答:
No. It's just a request to a URI, whether it's part of a page or being accessed directly, the server can see absolutely no difference.

We-e-ell, okay, I guess you could theoretically, perhaps, do some crazy hackery with php & javascript, but I can't see it being worth the hassle, and it wouldn't be reliable either. Then again, it's just a request, and you have no way of discerning how it originated. It'd also disrupt the way how some people browse, i.e. people who like to open images in new windows &c. I guess I know what you'd like to achieve (instead of an image, you'd like to serve a page with some data along with the image to give the content and your site more visibility), and I tend to agree it's a valid idea, but image search engines already do these things.

If I had to choose, I'd go with second option, it's permissive enough to allow normal browsing, and would disallow external links to the images.

Body:
The scenario looks like this, say that I have a website that contains some images. I want to allow people to embed them on their site, but I also want to redirect when anybody tries to access the image directly.

One option is this

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?imgzzz.com/.*$ [NC]
RewriteRule i/image_(\d+)\.(jpg|gif) - [F]

which would deny any access from anywhere else than the site, but that doesn't allow embedding the image.

The second option is to ommit the second RewriteCond leaving only

RewriteCond %{HTTP_REFERER} !^$
RewriteRule i/image_(\d+)\.(jpg|gif) - [F]

Which allows embedding, but the user can still access the image if he's comming from anywhere else than a bookmark.

Is there any way to make embedding available and at the same time doing redirect on direct access to the image?


问:
Convert an indexed pandas matrix to a flat dataframe
Given the dataframe:

```<code>df = pd.DataFrame([['foo', 123, 4, 5, 0, 1], ['foo', 123, 4, 0, 9, 1], ['bar', 33, 0, 0, 3, 5]], columns=list('ABCDEF'))
</code>```

[out]:

```<code>    A   B   C   D   E   F
0   foo 123 4   5   0   1
1   foo 123 4   0   9   1
2   bar 33  0   0   3   5
</code>```

The goal is to sum certain columns ('C', 'D', 'E', F') using other columns ('A' and 'B') as keys to achieve:

```<code>    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5
</code>```

I've tried:

```<code>df.groupby(['A', 'B']).sum()
</code>```

[out]:

```<code>        C   D   E   F
A   B
bar 33  0   0   3   5
foo 123 8   5   9   2
</code>```

How do I change it back to the non-indexed matrix? i.e.

```<code>    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5
</code>```

答:
You need to add .reset_index().

```<code>df.groupby(['A','B']).sum().reset_index()

    A   B   C   D   E   F
0   bar 33  0   0   3   5
1   foo 123 8   5   9   2
</code>```

or

```<code>df.set_index(['A','B']).sum(level=[0,1]).reset_index()

    A   B   C   D   E   F
0   bar 33  0   0   3   5
1   foo 123 8   5   9   2
</code>```

Body:
Given the dataframe:

df = pd.DataFrame([['foo', 123, 4, 5, 0, 1], ['foo', 123, 4, 0, 9, 1], ['bar', 33, 0, 0, 3, 5]], columns=list('ABCDEF'))

[out]:

    A   B   C   D   E   F
0   foo 123 4   5   0   1
1   foo 123 4   0   9   1
2   bar 33  0   0   3   5

The goal is to sum certain columns ('C', 'D', 'E', F') using other columns ('A' and 'B') as keys to achieve:

    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5

I've tried:

df.groupby(['A', 'B']).sum()

[out]:

        C   D   E   F
A   B
bar 33  0   0   3   5
foo 123 8   5   9   2

How do I change it back to the non-indexed matrix? i.e.

    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5

Body:
You need to add .reset_index().

df.groupby(['A','B']).sum().reset_index()

    A   B   C   D   E   F
0   bar 33  0   0   3   5
1   foo 123 8   5   9   2

or

df.set_index(['A','B']).sum(level=[0,1]).reset_index()

    A   B   C   D   E   F
0   bar 33  0   0   3   5
1   foo 123 8   5   9   2


问:
Open modal on gridview row click
I have a user control that has a GridView and when a user clicks on a row in this GridView the function OnSelectedIndexChanged is called, I'd like a modal to pop up after this occurs. I used the ScriptManager to invoke the script $('#seasonInfoModal').modal() which works in opening modals. The problem is it doesn't work when opening a modal which is defined within the same user control. The modal opens when it is inside the page.aspx , but doesn't open when inside the control .ascx. I have everything hooked up properly and have omitted some details. Here's what the overall code looks like

main page.aspx

```<code><%@ Page Title="" Language="C#" ... %>
<%@ Register Src="~/Controls/MyControl.ascx" TagPrefix="ACT" TagName="GeneralADM" %>

<ACT:GeneralADM runat="server"" />
</code>```

MyControl.ascx

```<code><%@ Language="C#" AutoWireUP="true" Codebehind="" Inherits="" %>

<div runat="server">

     <!-- Seasonal Info-->
     <div runat="server" id="seasonInfoModal" class="modal fade" role="dialog" draggable="true">
     </div>
     <!-- End seasonal info-->

     <!-- Start of Season Edit Modal -->
     <div id="seasonEditInfo" class="modal fade" role="dialog" draggable="false">
     </div>
     <!-- End of Season Edit Modal -->

      <asp:GridView>
      </asp:GridView>

</div>
</code>```

In the code behind I try to open the modal like this

MyControl.ascx.cs

```<code>protected void OnSelectedIndexChanged(object sender, GridViewEventArgs e){
    ScriptManager.RegisterStartupScript(this,
      this.GetType(),
      "seasonInfoModal",
      "$('#seasonInfoModal').modal();",
      true);
}
</code>```

issue

#seasonInfoModal doesn't popup instead a new modal is made with nothing inside it and the screen fades to dark on click. When I pull the #seasonInfoModal out of the control into the page where I am inserting the control itself, the modal actually pops up.

question

How can I open the modal #seasonInfoModal when it is inside the control from that control's codebehind specifically from inside OnSelectedIndexChanged function?

答:
The problem may be caused by the ID mangling performed by ASP.NET. Since the modal div is a server control (as specified by runat="server"), its ID in the rendered HTML is not seasonInfoModal but something like MyControl1_seasonInfoModal. As a result, the Javascript selector $('#seasonInfoModal') cannot find it.

You can change the startup script code, and pass the value of seasonInfoModal.ClientID to the jQuery selector, to account for the ID mangling:

```<code>protected void OnSelectedIndexChanged(object sender, GridViewEventArgs e){
    ScriptManager.RegisterStartupScript(this,
      this.GetType(),
      "seasonInfoModal",
      string.Format("$('#{0}').modal();", seasonInfoModal.ClientID),
      true);
}
</code>```

Other alternatives to avoid ID mangling would be:

To remove the runat="server" attribute if you don't need to access the div control in code-behind

To add clientidmode="static" to the div.

To use a class name (with the corresponding jQuery class selector) instead of an ID for the modal div.

These 3 solutions, however, would not behave correctly if several instances of the user control are present in the form. The modal of the first instance would always be used, and in cases 1 and 2, several controls of the form would have the same ID.

Title: Open modal on gridview row click

Body:
I have a user control that has a GridView and when a user clicks on a row in this GridView the function OnSelectedIndexChanged is called, I'd like a modal to pop up after this occurs. I used the ScriptManager to invoke the script $('#seasonInfoModal').modal() which works in opening modals. The problem is it doesn't work when opening a modal which is defined within the same user control. The modal opens when it is inside the page.aspx , but doesn't open when inside the control .ascx. I have everything hooked up properly and have omitted some details. Here's what the overall code looks like

main page.aspx

<%@ Page Title="" Language="C#" ... %>
<%@ Register Src="~/Controls/MyControl.ascx" TagPrefix="ACT" TagName="GeneralADM" %>

<ACT:GeneralADM runat="server"" />

MyControl.ascx

<%@ Language="C#" AutoWireUP="true" Codebehind="" Inherits="" %>

      <asp:GridView>
      </asp:GridView>

In the code behind I try to open the modal like this

MyControl.ascx.cs

protected void OnSelectedIndexChanged(object sender, GridViewEventArgs e){
    ScriptManager.RegisterStartupScript(this,
      this.GetType(),
      "seasonInfoModal",
      "$('#seasonInfoModal').modal();",
      true);
}

issue

#seasonInfoModal doesn't popup instead a new modal is made with nothing inside it and the screen fades to dark on click. When I pull the #seasonInfoModal out of the control into the page where I am inserting the control itself, the modal actually pops up.

question

How can I open the modal #seasonInfoModal when it is inside the control from that control's codebehind specifically from inside OnSelectedIndexChanged function?

Body:
The problem may be caused by the ID mangling performed by ASP.NET. Since the modal div is a server control (as specified by runat="server"), its ID in the rendered HTML is not seasonInfoModal but something like MyControl1_seasonInfoModal. As a result, the Javascript selector $('#seasonInfoModal') cannot find it.

You can change the startup script code, and pass the value of seasonInfoModal.ClientID to the jQuery selector, to account for the ID mangling:

protected void OnSelectedIndexChanged(object sender, GridViewEventArgs e){
    ScriptManager.RegisterStartupScript(this,
      this.GetType(),
      "seasonInfoModal",
      string.Format("$('#{0}').modal();", seasonInfoModal.ClientID),
      true);
}

Other alternatives to avoid ID mangling would be:

To remove the runat="server" attribute if you don't need to access the div control in code-behind

To add clientidmode="static" to the div.

To use a class name (with the corresponding jQuery class selector) instead of an ID for the modal div.

These 3 solutions, however, would not behave correctly if several instances of the user control are present in the form. The modal of the first instance would always be used, and in cases 1 and 2, several controls of the form would have the same ID.


问:
take values between spaces and dot
i have these kind of strings,

```<code>1. "Drs. H. Ahmad Malik S.Kom S.E S.pd"
2. "H. Ahmad Abdul Malik S.Kom S.E S.pd"
</code>```

Expected output :

```<code>1. Ahmad Malik
2. Ahmad Abdul Malik
</code>```

can anyone help me to solve it, i've try with substring, patindex but always did not get the expected output

答:
Just about any parse/split function would do the trick.

Option 1 With a Parse/Split Function

```<code>Declare @YourTable table (ID int,Name varchar(100))
Insert Into @YourTable values
(1,'Drs. H. Ahmad Malik S.Kom S.E S.pd'),
(2,'H. Ahmad Abdul Malik S.Kom S.E S.pd')

Select A.*
      ,B.*
 From  @YourTable A
 Cross Apply (
              Select NewString = Stuff((Select  ' ' +RetVal
                From [dbo].[udf-Str-Parse](A.Name,' ')
                Where RetVal Not Like '%.%'
             Order by RetSeq
             For XML Path ('')),1,1,'')
  ) B
</code>```

Option 2 Without a Parse/Split Function

```<code>Select A.*
      ,B.*
 From  @YourTable A
 Cross Apply (
              Select NewString = Stuff((Select  ' ' +RetVal
                From (
                        Select RetSeq = Row_Number() over (Order By (Select null))
                              ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                        From  (Select x = Cast('<x>' + replace((Select replace(A.Name,' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
                        Cross Apply x.nodes('x') AS B(i)
                     ) B1
                Where RetVal Not Like '%.%'
             Order by RetSeq
             For XML Path ('')),1,1,'')
  ) B
</code>```

Both Return

```<code>ID  Name                                  NewString
1   Drs. H. Ahmad Malik S.Kom S.E S.pd    Ahmad Malik
2   H. Ahmad Abdul Malik S.Kom S.E S.pd   Ahmad Abdul Malik
</code>```

The UDF if Interested

```<code>CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Much faster than str-Parse, but limited to 8K
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')
</code>```

Title: take values between spaces and dot

Body:
i have these kind of strings,

1. "Drs. H. Ahmad Malik S.Kom S.E S.pd"
2. "H. Ahmad Abdul Malik S.Kom S.E S.pd"

Expected output :

1. Ahmad Malik
2. Ahmad Abdul Malik

can anyone help me to solve it, i've try with substring, patindex but always did not get the expected output

Body:
Just about any parse/split function would do the trick.

Option 1 With a Parse/Split Function

Declare @YourTable table (ID int,Name varchar(100))
Insert Into @YourTable values
(1,'Drs. H. Ahmad Malik S.Kom S.E S.pd'),
(2,'H. Ahmad Abdul Malik S.Kom S.E S.pd')

Select A.*
      ,B.*
 From  @YourTable A
 Cross Apply (
              Select NewString = Stuff((Select  ' ' +RetVal
                From [dbo].[udf-Str-Parse](A.Name,' ')
                Where RetVal Not Like '%.%'
             Order by RetSeq
             For XML Path ('')),1,1,'')
  ) B

Option 2 Without a Parse/Split Function

Select A.*
      ,B.*
 From  @YourTable A
 Cross Apply (
              Select NewString = Stuff((Select  ' ' +RetVal
                From (
                        Select RetSeq = Row_Number() over (Order By (Select null))
                              ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                        From  (Select x = Cast('<x>' + replace((Select replace(A.Name,' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
                        Cross Apply x.nodes('x') AS B(i)
                     ) B1
                Where RetVal Not Like '%.%'
             Order by RetSeq
             For XML Path ('')),1,1,'')
  ) B

Both Return

ID  Name                                  NewString
1   Drs. H. Ahmad Malik S.Kom S.E S.pd    Ahmad Malik
2   H. Ahmad Abdul Malik S.Kom S.E S.pd   Ahmad Abdul Malik

The UDF if Interested

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Much faster than str-Parse, but limited to 8K
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')


问:
What is the recommended way to filter Objects with Unique property in the array in JS?
How to filter objects in array based on unique property
here i have an array where KEY is the key value in the objects.
How to filter the objects where key value is unique. Key value is repeated in the objects but should only the first one should be filtered out.

```<code>var array = [];
array = [
  {
    "KEY": "00001",
    "ID": "1234",
    "ID_DESC": "1234",
    "NOT_UNIQUE_VALUE": "119.0",
    "NOT_UNIQUE_TYPE": "this is not unique"
  },
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"11019.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  }]
</code>```

Result:

```<code>uniquearray = [
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"119.0",
    "NO T_UNIQUE_TYPE":"this is not unique"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  }]
</code>```

答:
```<code>var uniqueArray = []
for (var i = 0; i < array.length; i++) {
    var uniquevalue = array[i];
    unique[array.KEY] = uniquevalue;
}
for (var name in unique) {
    var uniqueObject = unique[name];
    uniqueArray.push(uniqueObject);
}
</code>```

Body:
How to filter objects in array based on unique property
here i have an array where KEY is the key value in the objects.
How to filter the objects where key value is unique. Key value is repeated in the objects but should only the first one should be filtered out.

var array = [];
array = [
  {
    "KEY": "00001",
    "ID": "1234",
    "ID_DESC": "1234",
    "NOT_UNIQUE_VALUE": "119.0",
    "NOT_UNIQUE_TYPE": "this is not unique"
  },
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"11019.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type",
  }]

Result:

uniquearray = [
  {
    "KEY":"00001",
    "ID":"1234",
    "ID_DESC":"1234",
    "NOT_UNIQUE_VALUE":"119.0",
    "NO T_UNIQUE_TYPE":"this is not unique"
  },
  {
    "KEY":"00002",
    "ID":"2468",
    "ID_DESC":"2468",
    "NOT_UNIQUE_VALUE":"195.0",
    "NOT_UNIQUE_TYPE":"not unique type"
  }]