Rectangle 27 95

Bugs found in all the custom javascript "natural string sort order" im...

I was really annoyed about this string natural sorting order so I took quite some time to investigate this issue. I hope this helps.

localeCompare() character support is badass, just use it. As pointed out by Shog9, the answer to your question is:

There are quite a bunch of custom implementations out there, trying to do string comparison more precisely called "natural string sort order"

When "playing" with these implementations, I always noticed some strange "natural sorting order" choice, or rather mistakes (or omissions in the best cases).

Typically, special characters (space, dash, ampersand, brackets, and so on) are not processed correctly.

You will then find them appearing mixed up in different places, typically that could be:

  • some will be between the uppercase 'Z' and the lowercase 'a'

When one would have expected special characters to all be "grouped" together in one place, except for the space special character maybe (which would always be the first character). That is, either all before numbers, or all between numbers and letters (lowercase & uppercase being "together" one after another), or all after letters.

My conclusion is that they all fail to provide a consistent order when I start adding barely unusual characters (ie. characters with diacritics or charcters such as dash, exclamation mark and so on).

Research on the custom implementations:

Natural Compare Lite
Natural Sort
Javascript Natural Sort
Alphanum
localeCompare()

Research on the browser-native implementations:

  • http://jsbin.com/beboroyifomu/2/edit?js,console - basic latin characters in string comparison : consistency check in string vs when a character is alone

So considering the current level of support provided by the javascript custom implementations I came across, we will probably never see anything getting any close to supporting all this characters & scripts (languages). Hence I would rather use the browsers' native localeCompare() method. Yes, it does have the downside of beeing non-consistent across browsers but basic testing shows it covers a much wider range of characters, allowing solid & meaningful sort orders.

Shog9
return item1.attr.localeCompare(item2.attr);

Thanks to Shog9's nice answer, which put me in the "right" direction I believe

How to sort strings in JavaScript - Stack Overflow

javascript string
Rectangle 27 129

Set up your service as a custom AngularJS Provider

Despite what the Accepted answer says, you actually CAN do what you were intending to do, but you need to set it up as a configurable provider, so that it's available as a service during the configuration phase.. First, change your Service to a provider as shown below. The key difference here is that after setting the value of defer, you set the defer.promise property to the promise object returned by $http.get:

app.provider('dbService', function dbServiceProvider() {

  //the provider recipe for services require you specify a $get function
  this.$get= ['dbhost',function dbServiceFactory(dbhost){
     // return the factory as a provider
     // that is available during the configuration phase
     return new DbService(dbhost);  
  }]

});

function DbService(dbhost){
    var status;

    this.setUrl = function(url){
        dbhost = url;
    }

    this.getData = function($http) {
        return $http.get(dbhost+'db.php/score/getData')
            .success(function(data){
                 // handle any special stuff here, I would suggest the following:
                 status = 'ok';
                 status.data = data;
             })
             .error(function(message){
                 status = 'error';
                 status.message = message;
             })
             .then(function(){
                 // now we return an object with data or information about error 
                 // for special handling inside your application configuration
                 return status;
             })
    }    
}

Now, you have a configurable custom Provider, you just need to inject it. Key difference here being the missing "Provider on your injectable".

app.config(function ($routeProvider) { 
    $routeProvider
        .when('/', {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
            resolve: {
                dbData: function(DbService, $http) {
                     /*
                     *dbServiceProvider returns a dbService instance to your app whenever
                     * needed, and this instance is setup internally with a promise, 
                     * so you don't need to worry about $q and all that
                     */
                    return DbService('http://dbhost.com').getData();
                }
            }
        })
});
appCtrl
app.controller('appCtrl',function(dbData, DbService){
     $scope.dbData = dbData;

     // You can also create and use another instance of the dbService here...
     // to do whatever you programmed it to do, by adding functions inside the 
     // constructor DbService(), the following assumes you added 
     // a rmUser(userObj) function in the factory
     $scope.removeDbUser = function(user){
         DbService.rmUser(user);
     }

})

The following alternative is a similar approach, but allows definition to occur within the .config, encapsulating the service to within the specific module in the context of your app. Choose the method that right for you. Also see below for notes on a 3rd alternative and helpful links to help you get the hang of all these things

app.config(function($routeProvider, $provide) {
    $provide.service('dbService',function(){})
    //set up your service inside the module's config.

    $routeProvider
        .when('/', {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
            resolve: {
                data: 
            }
        })
});
  • John Lindquist has an excellent 5 minute explanation and demonstration of this at egghead.io, and it's one of the free lessons! I basically modified his demonstration by making it $http specific in the context of this request
  • View the AngularJS Developer guide on Providers
factory
service
provider

The provider gives you a bit more configuration over the .service method, which makes it better as an application level provider, but you could also encapsulate this within the config object itself by injecting $provide into config like so:

It would really be useful if your codepen samples worked. For instance, $provide.service('dbService',function(){ doesn't have $http injected but uses it in its body. As it stands, I could not get your technique 2 to work. It's very frustrating that it is so hard to load config data from a remove file in an Angular program at startup.

@Alkaline I have learned a thing or two since this post. The answer is correct in theory but has 1 or 2 things (1 you pointed out) that should be fixed. Thanks for the comment. I'll review and update the answer. Deleted the codepen for the moment... never had a chance to finish it.

I think the information you provided here is incorrect. You can use a provider but during config phase you're not working with the result of the $get call. Instead you want to add methods on the provider instance and just return this when you call $get. In fact in your example you could just use a service... In a provider you also can't inject services like $http. And btw this //return the factory as a provider, that is available during the configuration phase is misleading/incorrect information

angularjs - Inject service in app.config - Stack Overflow

angularjs
Rectangle 27 188

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

I've tried your example of HandleUnauthorizedRequest but when I specify the RouteValueDictionary, it just redirects to me a route that doesn't exist. It appends the route I want to redirect the user to to the route that the user wanted to access... si I get something like: localhost:9999/admin/Home when I wanted localhost:9999/Home

@GabrielBB, I wish you would explain more. Does your comment mean I shouldn't follow this solution and that there's something you would change about it? What would you write in place of the if/else? Thank you.

@Emil I would just simply return the boolean that the String.Contains method gave me. But this is irrelevant, i didn't downvote, i just didn't upvote hehe.

authorization - ASP.NET MVC 4 Custom Authorize Attribute with Permissi...

asp.net-mvc-4 authorization custom-attributes
Rectangle 27 141

How to draw a Bzier path in a custom view

It wasn't long ago that I didn't even know how to pronounce Bzier, let alone know how to use Bzier paths to make a custom shape. The following is what I have learned. It turns out that they aren't as scary as they seem at first.

These are the main steps:

  • Design the outline of the shape you want.
  • Divide the outline path into segments of lines, arcs, and curves.
  • Build that path programmatically.
  • Draw the path either in drawRect or using a CAShapeLayer.

You could do anything, but as an example I have chosen the shape below. It could be a popup key on a keyboard.

Look back at your shape design and break it down into simpler elements of lines (for straight lines), arcs (for circles and round corners), and curves (for anything else).

Here is what our example design would look like:

  • Orange dots are the control points for the curves
  • Green dots are the points between path segments
  • Dotted lines show the bounding rectangle
  • Dark blue numbers are the segments in the order that they will be added programmatically

We'll arbitrarily start in the bottom left corner and work clockwise. I'll use the grid in the image to get the x and y values for the points. I'll hardcode everything here, but of course you wouldn't do that in a real project.

The basic process is:

UIBezierPath
  • Choose a starting point on the path with moveToPoint
addLineToPoint
addArcWithCenter
addCurveToPoint
  • Close the path with closePath

Here is the code to make the path in the image above.

func createBezierPath() -> UIBezierPath {

    // create a new path
    let path = UIBezierPath()

    // starting point for the path (bottom left)
    path.move(to: CGPoint(x: 2, y: 26))

    // *********************
    // ***** Left side *****
    // *********************

    // segment 1: line
    path.addLine(to: CGPoint(x: 2, y: 15))

    // segment 2: curve
    path.addCurve(to: CGPoint(x: 0, y: 12), // ending point
        controlPoint1: CGPoint(x: 2, y: 14),
        controlPoint2: CGPoint(x: 0, y: 14))

    // segment 3: line
    path.addLine(to: CGPoint(x: 0, y: 2))

    // *********************
    // ****** Top side *****
    // *********************

    // segment 4: arc
    path.addArc(withCenter: CGPoint(x: 2, y: 2), // center point of circle
        radius: 2, // this will make it meet our path line
        startAngle: CGFloat(M_PI), //  radians = 180 degrees = straight left
        endAngle: CGFloat(3*M_PI_2), // 3/2 radians = 270 degrees = straight up
        clockwise: true) // startAngle to endAngle goes in a clockwise direction

    // segment 5: line
    path.addLine(to: CGPoint(x: 8, y: 0))

    // segment 6: arc
    path.addArc(withCenter: CGPoint(x: 8, y: 2),
                          radius: 2,
                          startAngle: CGFloat(3*M_PI_2), // straight up
        endAngle: CGFloat(0), // 0 radians = straight right
        clockwise: true)

    // *********************
    // ***** Right side ****
    // *********************

    // segment 7: line
    path.addLine(to: CGPoint(x: 10, y: 12))

    // segment 8: curve
    path.addCurve(to: CGPoint(x: 8, y: 15), // ending point
        controlPoint1: CGPoint(x: 10, y: 14),
        controlPoint2: CGPoint(x: 8, y: 14))

    // segment 9: line
    path.addLine(to: CGPoint(x: 8, y: 26))

    // *********************
    // **** Bottom side ****
    // *********************

    // segment 10: line
    path.close() // draws the final line to close the path

    return path
}

Note: Some of the above code can be reduced by adding a line and an arc in a single command (since the arc has an implied starting point). See here for more details.

We can draw the path either in a layer or in drawRect.

Method 1: Draw path in a layer

Our custom class looks like this. We add our Bezier path to a new CAShapeLayer when the view is initialized.

import UIKit
class MyCustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {

        // Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()

        // The Bezier path that we made needs to be converted to 
        // a CGPath before it can be used on a layer.
        shapeLayer.path = createBezierPath().cgPath

        // apply other properties related to the path
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.lineWidth = 1.0
        shapeLayer.position = CGPoint(x: 10, y: 10)

        // add the new layer to our custom view
        self.layer.addSublayer(shapeLayer)
    }

    func createBezierPath() -> UIBezierPath {

        // see previous code for creating the Bezier path
    }
}

And creating our view in the View Controller like this

override func viewDidLoad() {
    super.viewDidLoad()

    // create a new UIView and add it to the view controller
    let myView = MyCustomView()
    myView.frame = CGRect(x: 100, y: 100, width: 50, height: 50)
    myView.backgroundColor = UIColor.yellow
    view.addSubview(myView)

}

Hmm, that's a little small because I hardcoded all the numbers in. I can scale the path size up, though, like this:

let path = createBezierPath()
let scale = CGAffineTransform(scaleX: 2, y: 2)
path.apply(scale)
shapeLayer.path = path.cgPath

Method 2: Draw path in draw

Using draw is slower than drawing to the layer, so this is not the recommended method if you don't need it.

Here is the revised code for our custom view:

import UIKit
class MyCustomView: UIView {

    override func draw(_ rect: CGRect) {

        // create path (see previous code)
        let path = createBezierPath()

        // fill
        let fillColor = UIColor.white
        fillColor.setFill()

        // stroke
        path.lineWidth = 1.0
        let strokeColor = UIColor.blue
        strokeColor.setStroke()

        // Move the path to a new location
        path.apply(CGAffineTransform(translationX: 10, y: 10))

        // fill and stroke the path (always do these last)
        path.fill()
        path.stroke()

    }

    func createBezierPath() -> UIBezierPath {

        // see previous code for creating the Bezier path
    }
}

which gives us the same result...

  • Thinking like a Bzier path (Everything I've ever read from this author is good and the inspiration for my example above came from here.)
  • Bezier Curves (how they are used in graphics applications)
  • Bezier Curves (good description of how the mathematical formulas are derived)

What if frame of the view changes? How can we resize the shape when an orientation change occurs?

@ozgur, There are at least two options. One would be to do a scale (and possibly translate) transform as I showed in my example above. Another option would be to recalculate the Bezier path based on the new frame. In the example above I hard coded all of the numbers into the Bezier path. However, when I have used Bezier paths in actual projects, I determine the Bezier values based on the frame size. When the frame (or more likely, bounds) changes I recalculate the Bezier path.

I chose the latter before. I recalculated the bezier path and updated the layer in question in layoutSubviews method but I am not sure if that is the right place to do it. Where would you update the path when the view's frame has changed?

@ozgur, layoutSubviews definitely sounds like the right place to do it. I would say if that is working then keep it there. Here is an example of where I used a Bezier path. (Scroll to the bottom.) For some reason I didn't put it in layoutSubviews but I don't remember why now. I should probably submit this to code review. I'm no expert. I just made the answer above to learn how to do Bezier paths myself.

@BohdanSavych, the draw method already belongs to the view, so you don't need to add it. It is a standard method defined by UIView for the purpose of drawing. We are just overriding it here so that we can do our own drawing on the view.

ios - Drawing UIBezierPath on code generated UIView - Stack Overflow

ios iphone objective-c uiview uibezierpath
Rectangle 27 141

How to draw a Bzier path in a custom view

It wasn't long ago that I didn't even know how to pronounce Bzier, let alone know how to use Bzier paths to make a custom shape. The following is what I have learned. It turns out that they aren't as scary as they seem at first.

These are the main steps:

  • Design the outline of the shape you want.
  • Divide the outline path into segments of lines, arcs, and curves.
  • Build that path programmatically.
  • Draw the path either in drawRect or using a CAShapeLayer.

You could do anything, but as an example I have chosen the shape below. It could be a popup key on a keyboard.

Look back at your shape design and break it down into simpler elements of lines (for straight lines), arcs (for circles and round corners), and curves (for anything else).

Here is what our example design would look like:

  • Orange dots are the control points for the curves
  • Green dots are the points between path segments
  • Dotted lines show the bounding rectangle
  • Dark blue numbers are the segments in the order that they will be added programmatically

We'll arbitrarily start in the bottom left corner and work clockwise. I'll use the grid in the image to get the x and y values for the points. I'll hardcode everything here, but of course you wouldn't do that in a real project.

The basic process is:

UIBezierPath
  • Choose a starting point on the path with moveToPoint
addLineToPoint
addArcWithCenter
addCurveToPoint
  • Close the path with closePath

Here is the code to make the path in the image above.

func createBezierPath() -> UIBezierPath {

    // create a new path
    let path = UIBezierPath()

    // starting point for the path (bottom left)
    path.move(to: CGPoint(x: 2, y: 26))

    // *********************
    // ***** Left side *****
    // *********************

    // segment 1: line
    path.addLine(to: CGPoint(x: 2, y: 15))

    // segment 2: curve
    path.addCurve(to: CGPoint(x: 0, y: 12), // ending point
        controlPoint1: CGPoint(x: 2, y: 14),
        controlPoint2: CGPoint(x: 0, y: 14))

    // segment 3: line
    path.addLine(to: CGPoint(x: 0, y: 2))

    // *********************
    // ****** Top side *****
    // *********************

    // segment 4: arc
    path.addArc(withCenter: CGPoint(x: 2, y: 2), // center point of circle
        radius: 2, // this will make it meet our path line
        startAngle: CGFloat(M_PI), //  radians = 180 degrees = straight left
        endAngle: CGFloat(3*M_PI_2), // 3/2 radians = 270 degrees = straight up
        clockwise: true) // startAngle to endAngle goes in a clockwise direction

    // segment 5: line
    path.addLine(to: CGPoint(x: 8, y: 0))

    // segment 6: arc
    path.addArc(withCenter: CGPoint(x: 8, y: 2),
                          radius: 2,
                          startAngle: CGFloat(3*M_PI_2), // straight up
        endAngle: CGFloat(0), // 0 radians = straight right
        clockwise: true)

    // *********************
    // ***** Right side ****
    // *********************

    // segment 7: line
    path.addLine(to: CGPoint(x: 10, y: 12))

    // segment 8: curve
    path.addCurve(to: CGPoint(x: 8, y: 15), // ending point
        controlPoint1: CGPoint(x: 10, y: 14),
        controlPoint2: CGPoint(x: 8, y: 14))

    // segment 9: line
    path.addLine(to: CGPoint(x: 8, y: 26))

    // *********************
    // **** Bottom side ****
    // *********************

    // segment 10: line
    path.close() // draws the final line to close the path

    return path
}

Note: Some of the above code can be reduced by adding a line and an arc in a single command (since the arc has an implied starting point). See here for more details.

We can draw the path either in a layer or in drawRect.

Method 1: Draw path in a layer

Our custom class looks like this. We add our Bezier path to a new CAShapeLayer when the view is initialized.

import UIKit
class MyCustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {

        // Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()

        // The Bezier path that we made needs to be converted to 
        // a CGPath before it can be used on a layer.
        shapeLayer.path = createBezierPath().cgPath

        // apply other properties related to the path
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.lineWidth = 1.0
        shapeLayer.position = CGPoint(x: 10, y: 10)

        // add the new layer to our custom view
        self.layer.addSublayer(shapeLayer)
    }

    func createBezierPath() -> UIBezierPath {

        // see previous code for creating the Bezier path
    }
}

And creating our view in the View Controller like this

override func viewDidLoad() {
    super.viewDidLoad()

    // create a new UIView and add it to the view controller
    let myView = MyCustomView()
    myView.frame = CGRect(x: 100, y: 100, width: 50, height: 50)
    myView.backgroundColor = UIColor.yellow
    view.addSubview(myView)

}

Hmm, that's a little small because I hardcoded all the numbers in. I can scale the path size up, though, like this:

let path = createBezierPath()
let scale = CGAffineTransform(scaleX: 2, y: 2)
path.apply(scale)
shapeLayer.path = path.cgPath

Method 2: Draw path in draw

Using draw is slower than drawing to the layer, so this is not the recommended method if you don't need it.

Here is the revised code for our custom view:

import UIKit
class MyCustomView: UIView {

    override func draw(_ rect: CGRect) {

        // create path (see previous code)
        let path = createBezierPath()

        // fill
        let fillColor = UIColor.white
        fillColor.setFill()

        // stroke
        path.lineWidth = 1.0
        let strokeColor = UIColor.blue
        strokeColor.setStroke()

        // Move the path to a new location
        path.apply(CGAffineTransform(translationX: 10, y: 10))

        // fill and stroke the path (always do these last)
        path.fill()
        path.stroke()

    }

    func createBezierPath() -> UIBezierPath {

        // see previous code for creating the Bezier path
    }
}

which gives us the same result...

  • Thinking like a Bzier path (Everything I've ever read from this author is good and the inspiration for my example above came from here.)
  • Bezier Curves (how they are used in graphics applications)
  • Bezier Curves (good description of how the mathematical formulas are derived)

What if frame of the view changes? How can we resize the shape when an orientation change occurs?

@ozgur, There are at least two options. One would be to do a scale (and possibly translate) transform as I showed in my example above. Another option would be to recalculate the Bezier path based on the new frame. In the example above I hard coded all of the numbers into the Bezier path. However, when I have used Bezier paths in actual projects, I determine the Bezier values based on the frame size. When the frame (or more likely, bounds) changes I recalculate the Bezier path.

I chose the latter before. I recalculated the bezier path and updated the layer in question in layoutSubviews method but I am not sure if that is the right place to do it. Where would you update the path when the view's frame has changed?

@ozgur, layoutSubviews definitely sounds like the right place to do it. I would say if that is working then keep it there. Here is an example of where I used a Bezier path. (Scroll to the bottom.) For some reason I didn't put it in layoutSubviews but I don't remember why now. I should probably submit this to code review. I'm no expert. I just made the answer above to learn how to do Bezier paths myself.

@BohdanSavych, the draw method already belongs to the view, so you don't need to add it. It is a standard method defined by UIView for the purpose of drawing. We are just overriding it here so that we can do our own drawing on the view.

ios - Drawing UIBezierPath on code generated UIView - Stack Overflow

ios iphone objective-c uiview uibezierpath
Rectangle 27 15

You could do this with a custom action:

import argparse

def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength

parser=argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', nargs='+', action=required_length(2,3))

args=parser.parse_args('-f 1 2 3'.split())
print(args.f)
# ['1', '2', '3']

try:
    args=parser.parse_args('-f 1 2 3 4'.split())
    print(args)
except argparse.ArgumentTypeError as err:
    print(err)
# argument "f" requires between 2 and 3 arguments

Time traveler here. Great answer! However, you're subclassing argparse.Action here... what happens if I want my action to be append? How can I modify this code so that I can append multiple instances of this argument, and also get that specified range effect?

Ah, actually, merging your code with this answer did what I was looking for. Never mind me - unless you were thinking the same thing, in which case, check that answer out.

There is a proposed patch bugs.python.org/issue11354 to add a range nargs option, e.g. nargs=(2,3) or nargs='{2,3}' (re style notation). That approach is more powerful when other positionals have variable nargs values. Otherwise this custom action approach works fine.

Python argparse: Is there a way to specify a range in nargs? - Stack O...

python argparse
Rectangle 27 14

You could do this with a custom action:

import argparse

def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength

parser=argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', nargs='+', action=required_length(2,3))

args=parser.parse_args('-f 1 2 3'.split())
print(args.f)
# ['1', '2', '3']

try:
    args=parser.parse_args('-f 1 2 3 4'.split())
    print(args)
except argparse.ArgumentTypeError as err:
    print(err)
# argument "f" requires between 2 and 3 arguments

Time traveler here. Great answer! However, you're subclassing argparse.Action here... what happens if I want my action to be append? How can I modify this code so that I can append multiple instances of this argument, and also get that specified range effect?

Ah, actually, merging your code with this answer did what I was looking for. Never mind me - unless you were thinking the same thing, in which case, check that answer out.

There is a proposed patch bugs.python.org/issue11354 to add a range nargs option, e.g. nargs=(2,3) or nargs='{2,3}' (re style notation). That approach is more powerful when other positionals have variable nargs values. Otherwise this custom action approach works fine.

Python argparse: Is there a way to specify a range in nargs? - Stack O...

python argparse
Rectangle 27 24

You could do this with a custom ConfigurableNavigationHandler. Here's a kickoff example:

package com.example;

import java.util.Map;
import java.util.Set;

import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.NavigationCase;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

public class RedirectNavigationHandler extends ConfigurableNavigationHandler {

    private NavigationHandler parent;

    public RedirectNavigationHandler(NavigationHandler parent) {
        this.parent = parent;
    }

    @Override
    public void handleNavigation(FacesContext context, String from, String outcome) {
        if (!outcome.endsWith("?faces-redirect=true")) {
            outcome += "?faces-redirect=true";
        }

        parent.handleNavigation(context, from, outcome);        
    }

    @Override
    public NavigationCase getNavigationCase(FacesContext context, String fromAction, String outcome) {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCase(context, fromAction, outcome);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Set<NavigationCase>> getNavigationCases() {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCases();
        } else {
            return null;
        }
    }

}

Register it as follows in faces-config.xml:

<application>
    <navigation-handler>com.example.RedirectNavigationHandler</navigation-handler>
</application>

Is possible to make this handler work when action method return void (stay on the same page) <h:commandButton action="#{bean.voidMethod}"/> ?

Hi, Albert. You can add code to handler and check if the request is an AJAX request getting a PartialViewContext from FaceContext and then invoking PartialViewContext.isAJAXRequest download.oracle.com/javaee/6/api/javax/faces/context/.

extends ConfigurableNavigationHandler
extends NavigationHandler
ConfigurableNavigationHandler
NavigationHandler

jsf 2 - JSF 2 and Post/Redirect/Get? - Stack Overflow

jsf jsf-2 post-redirect-get
Rectangle 27 5

Here is an example of a custom cursor..

cursor: paw.cur;

You have to specify a URL if you want to use a custom image based cursor..

a:hover {
    cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif), auto;
}
a:hover {
    cursor: crosshair;
}

css - Cursor not working in a:hover - Stack Overflow

css hover cursor
Rectangle 27 67

The more efficient (less obtrusive) way of doing this is through custom formatting.

  • In the Number tab, choose Custom.
  • Set the Custom formatting to 000#. (zero zero zero #)

Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.

This works great if there is no need to retain the leading zeroes past the original cell but won't work if the strings need to be used anywhere else. It would make the cells display as 0004, 01032, 0284 but if you tried to combine the strings in a separate cell it would show, for example, 4-1032-284 instead of the desired 0004-01032-0284

@AshtonSheets yes, as I noted in the answer it only displays the leading zeroes, it does nothing to the actual value. However, there have been situations where I used this instead of =text() because of its convenience and lack of formula involved.

0000
000#

I use a variation of this solution to round to millions of dollars: $#,,"M" However this turns $200,000 into $.2M when I would prefer $0.2M. Then I use $0#,,"M" and it gives me my $0.2M format but also changes numbers larger than 1,000,000 into $01.0M format! I seem to be going in circles - is there a solution for getting a 0 before the . ?

For those with my issue above, the answer was to swap out # (hash) for 0 (zero). The # gives you no character when there's no value but the 0 gives you a zero when there's no value! Makes sense and works great: $0.0,,"M"

padding - Add leading zeroes/0's to existing Excel values to certain l...

excel padding
Rectangle 27 13

so this is a custom Drawable you can use:

class LineDrawable extends Drawable {
    private Paint mPaint;

    public LineDrawable() {
        mPaint = new Paint();
        mPaint.setStrokeWidth(3);
    }

    @Override
    public void draw(Canvas canvas) {
        int lvl = getLevel();
        Rect b = getBounds();
        float x = b.width() * lvl / 10000.0f;
        float y = (b.height() - mPaint.getStrokeWidth()) / 2;
        mPaint.setColor(0xffff0000);
        canvas.drawLine(0, y, x, y, mPaint);
        mPaint.setColor(0xff00ff00);
        canvas.drawLine(x, y, b.width(), y, mPaint);
    }

    @Override
    protected boolean onLevelChange(int level) {
        invalidateSelf();
        return true;
    }

    @Override
    public void setAlpha(int alpha) {
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }
}
View v = new View(this);
final LineDrawable d = new LineDrawable();
d.setLevel(4000);
v.setBackgroundDrawable(d);
setContentView(v);
OnTouchListener l = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int lvl = (int) (10000 * event.getX() / v.getWidth());
        d.setLevel(lvl);
        return true;
    }
};
v.setOnTouchListener(l);

Thank you a lot! Do you have any idea on what is the most efficient way: this, or my solution with ImageViews?

android - How to programmatically create or alter a drawable made of l...

android line drawable shape
Rectangle 27 12

You can do this with an custom argparse.Action:

import argparse
import sys

class AddressAction(argparse.Action):
    def __call__(self, parser, args, values, option = None):
        args.address=values
        if args.query_type=='odam' and not args.address:
            args.address=[
                'master1.odamex.net:15000',
                'master2.odamex.net:15000',
                ]        
        if not args.address:
            parser.error("If you are making a server query, you must pass an address.")

p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
        const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
        const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*', action=AddressAction)
args = p.parse_args()
% test.py --odas
If you are making a server query, you must pass an address.
% test.py --odam
Namespace(address=['master1.odamex.net:15000', 'master2.odamex.net:15000'], query_type='odam')
% test.py --odam 1 2 3
Namespace(address=['1', '2', '3'], query_type='odam')

Precisely what I was looking for!

sys.exit()

One downside of using a custom action is that the action is called when the argument is parsed, and arguments after the one in question have not yet been added to the values array. This makes optional arguments sensitive to order. To avoid this, dont add a custom action, just check the dependency after the main call to parse_args, and call p.error('explanation message') if the dependecy fails. This prints out the help text and exits.

Python argparse: nargs + or * depending on prior argument - Stack Over...

python argparse
Rectangle 27 8

You can do this with a custom filter:

$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
    if (isTrue)
    {
        return Json(new { Foo = "Bar" });
    }
    throw new HttpException(404, "Oh noes...");
}

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        var statusCode = new HttpException(null, exception).GetHttpCode();

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
            Data = new
            {
                error = true,
                message = filterContext.Exception.Message
            }
        };

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = statusCode;  
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

ASP.NET MVC Ajax Error returning view instead of ajax - Stack Overflow

ajax asp.net-mvc jquery error-handling
Rectangle 27 8

You can do this with a custom filter:

$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
    if (isTrue)
    {
        return Json(new { Foo = "Bar" });
    }
    throw new HttpException(404, "Oh noes...");
}

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        var statusCode = new HttpException(null, exception).GetHttpCode();

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
            Data = new
            {
                error = true,
                message = filterContext.Exception.Message
            }
        };

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = statusCode;  
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

ASP.NET MVC Ajax Error returning view instead of ajax - Stack Overflow

ajax asp.net-mvc jquery error-handling
Rectangle 27 3

Example to create an array of a custom class

Below is the class definition.

public class DummyUser
{
    public string email { get; set; }
    public string language { get; set; }
}

This is how you can initialize the array:

private DummyUser[] arrDummyUser = new DummyUser[]
{
    new DummyUser{
       email = "abc.xyz@email.com",
       language = "English"
    },
    new DummyUser{
       email = "def@email.com",
       language = "Spanish"
    }
};

All possible C# array initialization syntaxes - Stack Overflow

c# arrays syntax array-initialization
Rectangle 27 21

I was able to do this with a custom deserializer (cut and pasted from here)

package etc;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

/**
 * Keeps json value as json, does not try to deserialize it
 * @author roytruelove
 *
 */
public class KeepAsJsonDeserialzier extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        TreeNode tree = jp.getCodec().readTree(jp);
        return tree.toString();
    }
}

Amazing how simple. IMO this should be the official answer. I tried with a very complex structure containing arrays, subobjects, etc. Maybe you edit your answer and add that the String member to be deserialized should be annotated by @JsonDeserialize( using = KeepAsJsonDeserialzier.class ). (and correct the typo in your class name ;-)

this works for Deserializion. How about for Serialization of raw json into a pojo? How would that be accomplished

@JsonRawValue

This works like a charm. Thank you Roy and @Heri ..combination of this post together with Heri's comment is imho the best answer.

java - How can I include raw JSON in an object using Jackson? - Stack ...

java json inner-classes jackson
Rectangle 27 20

I was able to do this with a custom deserializer (cut and pasted from here)

package etc;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

/**
 * Keeps json value as json, does not try to deserialize it
 * @author roytruelove
 *
 */
public class KeepAsJsonDeserialzier extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        TreeNode tree = jp.getCodec().readTree(jp);
        return tree.toString();
    }
}

Amazing how simple. IMO this should be the official answer. I tried with a very complex structure containing arrays, subobjects, etc. Maybe you edit your answer and add that the String member to be deserialized should be annotated by @JsonDeserialize( using = KeepAsJsonDeserialzier.class ). (and correct the typo in your class name ;-)

this works for Deserializion. How about for Serialization of raw json into a pojo? How would that be accomplished

@JsonRawValue

This works like a charm. Thank you Roy and @Heri ..combination of this post together with Heri's comment is imho the best answer.

java - How can I include raw JSON in an object using Jackson? - Stack ...

java json inner-classes jackson
Rectangle 27 17

You could use a global action filter. Let's suppose that you have a custom principal:

public class MyPrincipal : GenericPrincipal
{
    public MyPrincipal(IIdentity identity, string[] roles): base(identity, roles)
    {
    }

    ... some custom properties and stuff
}

then you could write a global authorization action filter (but which doesn't derive from the base AuthorizeAttribute to avoid global authentication, it just implements the IAuthorizationFilter interface to ensure that it runs before any other filters):

public class GlobalIdentityInjector : ActionFilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var identity = filterContext.HttpContext.User.Identity;

        // do some stuff here and assign a custom principal:
        var principal = new MyPrincipal(identity, null);
        // here you can assign some custom property that every user 
        // (even the non-authenticated have)

        // set the custom principal
        filterContext.HttpContext.User = principal;
    }
}

The global filter will be registered in ~/App_Start/FilterConfig.cs so that it is guaranteed that it will apply to all actions:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new GlobalIdentityInjector());
    }
}

And now you could have a custom authorization attribute which will be applied only to certain controller actions that require authentication:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            return false;
        }

        // we know that at this stage we have our custom
        // principal injected by the global action filter
        var myPrincipal = (MyPrincipal)httpContext.User;

        // do some additional work here to enrich this custom principal
        // by setting some other properties that apply only to
        // authenticated users

        return true;

    }
}

and then you could have 2 types of actions:

public ActionResult Foo()
{
    var user = (MyPrincipal)User;

    // work with the custom properties that apply only
    // to anonymous users

    ...
}

[MyAuthorize]
public ActionResult Bar()
{
    var user = (MyPrincipal)User;

    // here you can work with all the properties
    // because we know that the custom authorization
    // attribute set them and the global filter set the other properties

    ...
}

Excellent, detailed answer Darin. If only to glean more MVC architecture information from you, could you speak to why you would choose a global action filter vs the other choices?

The first of your suggestions is out of question because it involves using sessions. Personally I never use sessions. Application_AuthenticateRequest is not MVCish. The third and fourth I don't like because of the base controller. And the last one - IHttpModule I don't like because not MVCish. So I choose a global action filter - it doesn't require implementing a base controller (which developers might forget to derive from) and it is universally applied to ALL requests and it is quite common way to implement such functionality in ASP.NET MVC applications.

Almost a year later and this saved me immensely. Thanks a lot Darin.

asp.net - How to create a CustomPrincipal globally (with and without A...

asp.net asp.net-mvc forms-authentication iprincipal
Rectangle 27 10

How to use the pre_get_posts hook to display list of posts on a page, ...

I've been playing with the pre_get_posts hook and here's one idea

Ceate a page called for example Show with the slug:

example.com/show

Create a custom page template:

tpl_show.php

located in the current theme directory.

We construct the following pre_get_posts action callback:

function b2e_pre_get_posts( $query )
{
    $target_page = 'show';                             // EDIT to your needs

    if (    ! is_admin()                               // front-end only
         && $query->is_main_query()                    // main query only
         && $target_page === $query->get( 'pagename' ) // matching pagename only
    ) {
        // modify query_vars:
        $query->set( 'post_type',      'post'                 );  // override 'post_type'
        $query->set( 'pagename',       null                   );  // override 'pagename'
        $query->set( 'posts_per_page', 10                     );
        $query->set( 'meta_key',       'wpb_post_views_count' );
        $query->set( 'orderby',        'meta_value_num'       );
        $query->set( 'order',          'DESC'                 );

        // Support for paging
        $query->is_singular = 0;

        // custom page template
        add_filter( 'template_include', 'b2e_template_include', 99 );
    }
}

add_action( 'pre_get_posts', 'b2e_pre_get_posts' );
function b2e_template_include( $template )
{
    $target_tpl = 'tpl_show.php'; // EDIT to your needs

    remove_filter( 'template_include', 'b2e_template_include', 99 );

    $new_template = locate_template( array( $target_tpl ) );

    if ( ! empty( $new_template ) )
        $template = $new_template; ;

    return $template;
}
example.com/show/page/2
example.com/show/page/3

I updated the answer and removed the query-object part modification, based on the suggestion from @PieterGoosen, since it could e.g. break the breadcrumbs on his setup.

Also removed the is_page() check within the pre_get_posts hook, since it might still give some irregularities in some cases. The reason is that the query-object is not always available. This is being worked on, see e.g. #27015. There are workarounds possible if we want to use the is_page() or is_front_page().

I constructed the following table, just to get a better overview of some of the properties and query varaiables of the main WP_Query object, for a given slug:

It's interesting to note that the pagination in WP_Query depends on the nopaging not being set and the current page not being singular (from the 4.4 source):

// Paging
if ( empty($q['nopaging']) && !$this->is_singular ) {
    $page = absint($q['paged']);
    if ( !$page )
        $page = 1;

    // If 'offset' is provided, it takes precedence over 'paged'.
    if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
        $q['offset'] = absint( $q['offset'] );
        $pgstrt = $q['offset'] . ', ';
    } else {
        $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
    }
    $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
}

where we can see that the LIMIT part of the generated SQL query is within the conditional check. This explains why we modify the is_singular property above.

We could have used other filter/hooks, but here we used pre_get_posts as mentioned by the OP.

Thanks @andy, it was an interesting puzzle ;-)

Will award the bounty to you as soon as I can, unfortunately I cannot award the bounty within 24 hours of starting one. Enjoy ;

No problem. Enjoy the rest of your Sunday. Last day to "relax" before everything goes back to normal tommorrow

Thanks for the update @PieterGoosen and generous bounty. I just updated the answer. I guess I was trying to remove the page identity when I originally posted it, but I've now skipped that part, thanks to your suggestion.

php - WordPress - pre_get_posts in place of query_posts on pages - Sta...

php wordpress
Rectangle 27 10

How to use the pre_get_posts hook to display list of posts on a page, ...

I've been playing with the pre_get_posts hook and here's one idea

Ceate a page called for example Show with the slug:

example.com/show

Create a custom page template:

tpl_show.php

located in the current theme directory.

We construct the following pre_get_posts action callback:

function b2e_pre_get_posts( $query )
{
    $target_page = 'show';                             // EDIT to your needs

    if (    ! is_admin()                               // front-end only
         && $query->is_main_query()                    // main query only
         && $target_page === $query->get( 'pagename' ) // matching pagename only
    ) {
        // modify query_vars:
        $query->set( 'post_type',      'post'                 );  // override 'post_type'
        $query->set( 'pagename',       null                   );  // override 'pagename'
        $query->set( 'posts_per_page', 10                     );
        $query->set( 'meta_key',       'wpb_post_views_count' );
        $query->set( 'orderby',        'meta_value_num'       );
        $query->set( 'order',          'DESC'                 );

        // Support for paging
        $query->is_singular = 0;

        // custom page template
        add_filter( 'template_include', 'b2e_template_include', 99 );
    }
}

add_action( 'pre_get_posts', 'b2e_pre_get_posts' );
function b2e_template_include( $template )
{
    $target_tpl = 'tpl_show.php'; // EDIT to your needs

    remove_filter( 'template_include', 'b2e_template_include', 99 );

    $new_template = locate_template( array( $target_tpl ) );

    if ( ! empty( $new_template ) )
        $template = $new_template; ;

    return $template;
}
example.com/show/page/2
example.com/show/page/3

I updated the answer and removed the query-object part modification, based on the suggestion from @PieterGoosen, since it could e.g. break the breadcrumbs on his setup.

Also removed the is_page() check within the pre_get_posts hook, since it might still give some irregularities in some cases. The reason is that the query-object is not always available. This is being worked on, see e.g. #27015. There are workarounds possible if we want to use the is_page() or is_front_page().

I constructed the following table, just to get a better overview of some of the properties and query varaiables of the main WP_Query object, for a given slug:

It's interesting to note that the pagination in WP_Query depends on the nopaging not being set and the current page not being singular (from the 4.4 source):

// Paging
if ( empty($q['nopaging']) && !$this->is_singular ) {
    $page = absint($q['paged']);
    if ( !$page )
        $page = 1;

    // If 'offset' is provided, it takes precedence over 'paged'.
    if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
        $q['offset'] = absint( $q['offset'] );
        $pgstrt = $q['offset'] . ', ';
    } else {
        $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
    }
    $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
}

where we can see that the LIMIT part of the generated SQL query is within the conditional check. This explains why we modify the is_singular property above.

We could have used other filter/hooks, but here we used pre_get_posts as mentioned by the OP.

Thanks @andy, it was an interesting puzzle ;-)

Will award the bounty to you as soon as I can, unfortunately I cannot award the bounty within 24 hours of starting one. Enjoy ;

No problem. Enjoy the rest of your Sunday. Last day to "relax" before everything goes back to normal tommorrow

Thanks for the update @PieterGoosen and generous bounty. I just updated the answer. I guess I was trying to remove the page identity when I originally posted it, but I've now skipped that part, thanks to your suggestion.

php - WordPress - pre_get_posts in place of query_posts on pages - Sta...

php wordpress