Rectangle 27 138

You can do this using the filter() function:

$(".a").filter(".b")

What is the difference between this answer and the accepted one?

@Rice: This one will be a little bit slower, because it will build a list of objects with class "a" first, then remove all but those that have class "b", whereas mine does this in one step. But otherwise, no difference.

This worked for me in an instance where I was searching for a class defined as a variable, which didn't work with the syntax in the first example. eg: $('.foo').filter(variable). Thanks

@pac: $('.foo' + variable) should have done the trick, but I can see where this method would be clearer in that case.

This is also more efficient if you have already found .a's and need to filter multiple times based different arbitrary classes that also belong to the original .a set.

How can I select an element with multiple classes in jQuery? - Stack O...

jquery jquery-selectors
Rectangle 27 136

You can do this using the filter() function:

$(".a").filter(".b")

What is the difference between this answer and the accepted one?

@Rice: This one will be a little bit slower, because it will build a list of objects with class "a" first, then remove all but those that have class "b", whereas mine does this in one step. But otherwise, no difference.

This worked for me in an instance where I was searching for a class defined as a variable, which didn't work with the syntax in the first example. eg: $('.foo').filter(variable). Thanks

@pac: $('.foo' + variable) should have done the trick, but I can see where this method would be clearer in that case.

This is also more efficient if you have already found .a's and need to filter multiple times based different arbitrary classes that also belong to the original .a set.

How can I select an element with multiple classes in jQuery? - Stack O...

jquery jquery-selectors
Rectangle 27 136

You can do this using the filter() function:

$(".a").filter(".b")

What is the difference between this answer and the accepted one?

@Rice: This one will be a little bit slower, because it will build a list of objects with class "a" first, then remove all but those that have class "b", whereas mine does this in one step. But otherwise, no difference.

This worked for me in an instance where I was searching for a class defined as a variable, which didn't work with the syntax in the first example. eg: $('.foo').filter(variable). Thanks

@pac: $('.foo' + variable) should have done the trick, but I can see where this method would be clearer in that case.

This is also more efficient if you have already found .a's and need to filter multiple times based different arbitrary classes that also belong to the original .a set.

How can I select an element with multiple classes in jQuery? - Stack O...

jquery jquery-selectors
Rectangle 27 36

Using these articles as reference:

Using the filter as a ServiceFilter

Because the filter will be used as a ServiceType, it needs to be registered with the framework IoC. If the action filters were used directly, this would not be required.

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc();

    services.AddScoped<ISessionService, SessionService>();
    services.AddScoped<EnsureUserLoggedIn>();

    ...
}

Custom filters are added to the MVC controller method and the controller class using the ServiceFilter attribute like so:

[ServiceFilter(typeof(EnsureUserLoggedIn))]
[Route("api/issues")]
public class IssueController : Controller {
    // GET: api/issues
    [HttpGet]
    [ServiceFilter(typeof(EnsureUserLoggedIn))]
    public IEnumerable<string> Get(){...}
}

There were other examples of

Take a look, give them a try and see if that resolves your issue.

Yup, this worked. I was unfamiliar with the ServiceFilter attribute before. That was the piece missing in my code. Thank you.

You shouldn't do authorization policy checks this way, it's not the way in was intended to. You are supposed to use i.e. Cookie Authorization or some other authorization type (jwt for example) and then use AuthorizeAttribute with policies you set up on application startup. Check my comment above

Interestingly a global filter does not seem to a allow for DI, see: github.com/damienbod/AspNet5Filters/blob/ - the author of the blogs actually hard-wires dependencies himself there.

Found a blog that actually covers Global filters + dependency injection: weblogs.asp.net/ricardoperes/

How does this work if you need to specify properties on the attribute?

c# - Inject service into Action Filter - Stack Overflow

c# dependency-injection asp.net-core
Rectangle 27 4

Using a filter to intercept the request

This kind of authentication could be achieved with a ContainerRequestFilter, intercepting the requests to your resource methods.

The filter will be used to extract the API key from the request and validate it. If the API key is not valid, the request will be refused. Otherwise, the request will proceed to the resource methods.

Have a look at the following piece of code. The ContainerRequestContext API can be used to extract information from the HTTP request:

@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Extract and validate the API key from the request
        String apiKey = requestContext.getHeaderString("API-Key");
        ...
    }
}

Also have a look at this answer I wrote a while ago about authentication with tokens in JAX-RS. There you will find plenty of details that can be useful to address the situation you described in your question.

During the authentication process, you must be able to identify the user who is performing the request. To propagate this information to your resource classes/methods you could:

  • Override the SecurityContext and inject it into your resource classes/methods.
  • Use a CDI Event and a producer method to create an object that contains the user identifier that can be injected in your resource classes/methods.

By default, the filters are global (it means they are executed for all the resource methods of your application). To bind the filter to a subset of resource methods or classes, you could use name binding annotations.

X-
API-Key

@Michael-O Thanks. It was just an example on how to use the ContainerRequestContext API to extract a header from the HTTP request. Actually, custom headers should be avoided at all. The best approach would be using the standard Authorization header. Unfortunately I don't know much about the OP requirements, but I assumed the API key is being sent in a custom header.

java - Authenticating with an API key in JAX-RS - Stack Overflow

java web-services security rest jax-rs
Rectangle 27 4

Using a filter to intercept the request

This kind of authentication could be achieved with a ContainerRequestFilter, intercepting the requests to your resource methods.

The filter will be used to extract the API key from the request and validate it. If the API key is not valid, the request will be refused. Otherwise, the request will proceed to the resource methods.

Have a look at the following piece of code. The ContainerRequestContext API can be used to extract information from the HTTP request:

@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Extract and validate the API key from the request
        String apiKey = requestContext.getHeaderString("API-Key");
        ...
    }
}

Also have a look at this answer I wrote a while ago about authentication with tokens in JAX-RS. There you will find plenty of details that can be useful to address the situation you described in your question.

During the authentication process, you must be able to identify the user who is performing the request. To propagate this information to your resource classes/methods you could:

  • Override the SecurityContext and inject it into your resource classes/methods.
  • Use a CDI Event and a producer method to create an object that contains the user identifier that can be injected in your resource classes/methods.

By default, the filters are global (it means they are executed for all the resource methods of your application). To bind the filter to a subset of resource methods or classes, you could use name binding annotations.

X-
API-Key

@Michael-O Thanks. It was just an example on how to use the ContainerRequestContext API to extract a header from the HTTP request. Actually, custom headers should be avoided at all. The best approach would be using the standard Authorization header. Unfortunately I don't know much about the OP requirements, but I assumed the API key is being sent in a custom header.

java - Authenticating with an API key in JAX-RS - Stack Overflow

java web-services security rest jax-rs
Rectangle 27 76

From what I understand you can't pass an arguments to a filter function (when using the 'filter' filter). What you would have to do is to write a custom filter, sth like this:

.filter('weDontLike', function(){

return function(items, name){

    var arrayToReturn = [];        
    for (var i=0; i<items.length; i++){
        if (items[i].name != name) {
            arrayToReturn.push(items[i]);
        }
    }

    return arrayToReturn;
};

The other simple alternative, without writing custom filters is to store a name to filter out in a scope and then write:

$scope.weDontLike = function(item) {
  return item.name != $scope.name;
};

Thats prefect thanks! Storing the name in the scope won't work so well as I have three lists from the same data on the same page im filtering with different states (or names).

Is it possible to reorder the parameters of a filter? For example pass the item to the second parameter of a filter?

It is worth noting that in this example the markup is {{ items | weDontLike:'thenameyoudontlike' }} ... right now you have to go to the fiddle to get that. Also worth noting that you can pass multiple params to your custom filter {{ items | weDontLike:'thename':['I am', 'an array']:'and so on' }} you would just add more arguments to your custom filter to have access to them.

javascript - Passing arguments to angularjs filters - Stack Overflow

javascript angularjs angular-filters
Rectangle 27 17

You can get the channel ID with the username (in your case "klauskkpm") using the filter "forUsername", like this:

https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername=klauskkpm&part=id

How can I get a channel ID from YouTube? - Stack Overflow

youtube youtube-api
Rectangle 27 95

As per the JSON docs at Mozilla, JSON.Stringify has a second parameter censor which can be used to filter/ignore children items while parsing the tree. However, perhaps you can avoid the circular references.

In Node.js we cannot. So we can do something like this:

function censor(censor) {
  var i = 0;

  return function(key, value) {
    if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value) 
      return '[Circular]'; 

    if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
      return '[Unknown]';

    ++i; // so we know we aren't using the original object anymore

    return value;  
  }
}

var b = {foo: {bar: null}};

b.foo.bar = b;

console.log("Censoring: ", b);

console.log("Result: ", JSON.stringify(b, censor(b)));
Censoring:  { foo: { bar: [Circular] } }
Result: {"foo":{"bar":"[Circular]"}}

Unfortunately there seems to be a maximum of 30 iterations before it automatically assumes it's circular. Otherwise, this should work. I even used areEquivalent from here, but JSON.Stringify still throws the exception after 30 iterations. Still, it's good enough to get a decent representation of the object at a top level, if you really need it. Perhaps somebody can improve upon this though? In Node.js for an HTTP request object, I'm getting:

{
"limit": null,
"size": 0,
"chunks": [],
"writable": true,
"readable": false,
"_events": {
    "pipe": [null, null],
    "error": [null]
},
"before": [null],
"after": [],
"response": {
    "output": [],
    "outputEncodings": [],
    "writable": true,
    "_last": false,
    "chunkedEncoding": false,
    "shouldKeepAlive": true,
    "useChunkedEncodingByDefault": true,
    "_hasBody": true,
    "_trailer": "",
    "finished": false,
    "socket": {
        "_handle": {
            "writeQueueSize": 0,
            "socket": "[Unknown]",
            "onread": "[Unknown]"
        },
        "_pendingWriteReqs": "[Unknown]",
        "_flags": "[Unknown]",
        "_connectQueueSize": "[Unknown]",
        "destroyed": "[Unknown]",
        "bytesRead": "[Unknown]",
        "bytesWritten": "[Unknown]",
        "allowHalfOpen": "[Unknown]",
        "writable": "[Unknown]",
        "readable": "[Unknown]",
        "server": "[Unknown]",
        "ondrain": "[Unknown]",
        "_idleTimeout": "[Unknown]",
        "_idleNext": "[Unknown]",
        "_idlePrev": "[Unknown]",
        "_idleStart": "[Unknown]",
        "_events": "[Unknown]",
        "ondata": "[Unknown]",
        "onend": "[Unknown]",
        "_httpMessage": "[Unknown]"
    },
    "connection": "[Unknown]",
    "_events": "[Unknown]",
    "_headers": "[Unknown]",
    "_headerNames": "[Unknown]",
    "_pipeCount": "[Unknown]"
},
"headers": "[Unknown]",
"target": "[Unknown]",
"_pipeCount": "[Unknown]",
"method": "[Unknown]",
"url": "[Unknown]",
"query": "[Unknown]",
"ended": "[Unknown]"
}

It's the first time I see a function being passed which returns a self-executing function which returns a regular function. I believe I understand why this was done, but I don't believe I would have found that solution myself, and I feel I could remember this technique better if I could see other examples where this setup is needed. That being said, could you point to any literature regarding this setup/technique (for lack of a better word) or similar ones?

+1 to Shawn. Please remove that IEFE, it's absolutely useless and illegible.

thx for pointing out the censor arg! it allows debugging down circular issues. in my case i had a jquery array where i thougth to have a normal array. they both look similar in debug print mode. About the IEFE, I see them frequently used in places where there is absolutely no need for them and agree with Shawn and Bergi that this is just such case.

Still no solution to the 30 iteration limit?

javascript - Chrome sendrequest error: TypeError: Converting circular ...

javascript json google-chrome google-chrome-extension
Rectangle 27 95

As per the JSON docs at Mozilla, JSON.Stringify has a second parameter censor which can be used to filter/ignore children items while parsing the tree. However, perhaps you can avoid the circular references.

In Node.js we cannot. So we can do something like this:

function censor(censor) {
  var i = 0;

  return function(key, value) {
    if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value) 
      return '[Circular]'; 

    if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
      return '[Unknown]';

    ++i; // so we know we aren't using the original object anymore

    return value;  
  }
}

var b = {foo: {bar: null}};

b.foo.bar = b;

console.log("Censoring: ", b);

console.log("Result: ", JSON.stringify(b, censor(b)));
Censoring:  { foo: { bar: [Circular] } }
Result: {"foo":{"bar":"[Circular]"}}

Unfortunately there seems to be a maximum of 30 iterations before it automatically assumes it's circular. Otherwise, this should work. I even used areEquivalent from here, but JSON.Stringify still throws the exception after 30 iterations. Still, it's good enough to get a decent representation of the object at a top level, if you really need it. Perhaps somebody can improve upon this though? In Node.js for an HTTP request object, I'm getting:

{
"limit": null,
"size": 0,
"chunks": [],
"writable": true,
"readable": false,
"_events": {
    "pipe": [null, null],
    "error": [null]
},
"before": [null],
"after": [],
"response": {
    "output": [],
    "outputEncodings": [],
    "writable": true,
    "_last": false,
    "chunkedEncoding": false,
    "shouldKeepAlive": true,
    "useChunkedEncodingByDefault": true,
    "_hasBody": true,
    "_trailer": "",
    "finished": false,
    "socket": {
        "_handle": {
            "writeQueueSize": 0,
            "socket": "[Unknown]",
            "onread": "[Unknown]"
        },
        "_pendingWriteReqs": "[Unknown]",
        "_flags": "[Unknown]",
        "_connectQueueSize": "[Unknown]",
        "destroyed": "[Unknown]",
        "bytesRead": "[Unknown]",
        "bytesWritten": "[Unknown]",
        "allowHalfOpen": "[Unknown]",
        "writable": "[Unknown]",
        "readable": "[Unknown]",
        "server": "[Unknown]",
        "ondrain": "[Unknown]",
        "_idleTimeout": "[Unknown]",
        "_idleNext": "[Unknown]",
        "_idlePrev": "[Unknown]",
        "_idleStart": "[Unknown]",
        "_events": "[Unknown]",
        "ondata": "[Unknown]",
        "onend": "[Unknown]",
        "_httpMessage": "[Unknown]"
    },
    "connection": "[Unknown]",
    "_events": "[Unknown]",
    "_headers": "[Unknown]",
    "_headerNames": "[Unknown]",
    "_pipeCount": "[Unknown]"
},
"headers": "[Unknown]",
"target": "[Unknown]",
"_pipeCount": "[Unknown]",
"method": "[Unknown]",
"url": "[Unknown]",
"query": "[Unknown]",
"ended": "[Unknown]"
}

It's the first time I see a function being passed which returns a self-executing function which returns a regular function. I believe I understand why this was done, but I don't believe I would have found that solution myself, and I feel I could remember this technique better if I could see other examples where this setup is needed. That being said, could you point to any literature regarding this setup/technique (for lack of a better word) or similar ones?

+1 to Shawn. Please remove that IEFE, it's absolutely useless and illegible.

thx for pointing out the censor arg! it allows debugging down circular issues. in my case i had a jquery array where i thougth to have a normal array. they both look similar in debug print mode. About the IEFE, I see them frequently used in places where there is absolutely no need for them and agree with Shawn and Bergi that this is just such case.

Still no solution to the 30 iteration limit?

javascript - Chrome sendrequest error: TypeError: Converting circular ...

javascript json google-chrome google-chrome-extension
Rectangle 27 18

First do a loop using a filter that will return only unique teams, and then a nested loop that returns all players per current team:

<div ng-app ng-controller="Main">
    <div ng-repeat="playerPerTeam in playersToFilter() | filter:filterTeams">
        <b>{{playerPerTeam.team}}</b>
        <li ng-repeat="player in players | filter:{team: playerPerTeam.team}">{{player.name}}</li>        
    </div>
</div>
function Main($scope) {
    $scope.players = [{name: 'Gene', team: 'team alpha'},
                    {name: 'George', team: 'team beta'},
                    {name: 'Steve', team: 'team gamma'},
                    {name: 'Paula', team: 'team beta'},
                    {name: 'Scruath of the 5th sector', team: 'team gamma'}];

    var indexedTeams = [];

    // this will reset the list of indexed teams each time the list is rendered again
    $scope.playersToFilter = function() {
        indexedTeams = [];
        return $scope.players;
    }

    $scope.filterTeams = function(player) {
        var teamIsNew = indexedTeams.indexOf(player.team) == -1;
        if (teamIsNew) {
            indexedTeams.push(player.team);
        }
        return teamIsNew;
    }
}

just brilliant . but what if i want to push a new object to $scope.players on click ? as u are looping through a function will it get added ?

javascript - How can I group data with an Angular filter? - Stack Over...

javascript filter angularjs grouping
Rectangle 27 12

a solution is using map and filter functions

d={"a":1,"b":2,"c":3}
l=("a","b","d")
list(map(d.__delitem__, filter(d.__contains__,l)))
print(d)
{'c': 3}
>>> d={"a":1,"b":2,"c":3} >>> l=("a","b","d") >>> map(d.__delitem__, filter(d.__contains__,l)) <map object at 0x10579b9e8> >>> print(d) {'a': 1, 'b': 2, 'c': 3}
list(map(d.__delitem__,filter(d.__contains__,l)))
deque(map(...), maxlen=0)
from collections import deque

python - Removing multiple keys from a dictionary safely - Stack Overf...

python dictionary
Rectangle 27 2

Exclude it from component-scan by using a filter

<component-scan base-package="your-package">
    <exclude-filter type="regex" expression="DefaultService" />
</component-scan>

Not sure if there is a way to do it with only annotations (other than removing the @Service annotation from DefaultService).

Thanks, Wilhelm, I am sure your solution would work. But then I would have to scan for my services by myself. Good idea!

javabeans - How to overwrite Spring service beans by name, using annot...

spring javabeans overwrite autowired inject
Rectangle 27 6

Using git attributes, and filters setup with git config

OK, this is a new tack on solving this problem My approach is to not use any hooks, but rather use filters and git attributes. What this allows you to do, is setup, on each machine you develop on, a set of filters that will strip extra trailing white space and extra blank lines at the end of files before committing them. Then setup a .gitattributes file that says which types of files the filter should be applied to. The filters have two phases, clean which is applied when adding files to the index, and smudge which is applied when adding them to the working directory.

git config --global core.attributesfile ~/.gitattributes_global
git config --global filter.fix-eol-eof.clean fixup-eol-eof %f
git config --global filter.fix-eol-eof.smudge cat
git config --global filter.fix-eol-eof.required true

Finally, put the fixup-eol-eof script somewhere on your path, and make it executable. The script uses sed to do some on the fly editing (remove spaces and blanks at the end of lines, and extraneous blank lines at the end of the file)

#!/bin/bash
sed -e s/[  ]*$// -e :a -e '/^\n*$/{$d;N;ba' -e '}' $1

Lastly, create or open ~/.gitattributes_global in your favorite editor and add lines like:

pattern attr1 [attr2 [attr3 []]]

So if we want to fix the whitespace issue, for all of our c source files we would add a line that looks like this:

*.c filter=fix-eol-eof

The filter has two phases, the clean phase which is applied when things are added to the index or checked in, and the smudge phase when git puts stuff into your working directory. Here, our smudge is just running the contents through the cat command which should leave them unchanged, with the exception of possibly adding a trailing newline character if there wasnt one at the end of the file. The clean command is the whitespace filtering which I cobbled together from notes at http://sed.sourceforge.net/sed1line.txt. It seems that it must be put into a shell script, I couldnt figure out how to inject the sed command, including the sanitation of the extraneous extra lines at the end of the file directly into the git-config file. (You CAN get rid of trailing blanks, however, without the need of a separate sed script, just set the filter.fix-eol-eofto something like sed 's/[ \t]*$//' %f where the \t is an actual tab, by pressing tab.)

The require = true causes an error to be raised if something goes wrong, to keep you out of trouble.

Please forgive me if my language concerning git is imprecise. I think I have a fairly good grasp of the concepts but am still learning the terminology.

Thanks @VonC! I also want to take this opportunity to point out that the git attributes can be configured in a per-repisitory basis in the .git folder rather than globally, which might make more sense.

Make git automatically remove trailing whitespace before committing - ...

git whitespace githooks
Rectangle 27 6

Using git attributes, and filters setup with git config

OK, this is a new tack on solving this problem My approach is to not use any hooks, but rather use filters and git attributes. What this allows you to do, is setup, on each machine you develop on, a set of filters that will strip extra trailing white space and extra blank lines at the end of files before committing them. Then setup a .gitattributes file that says which types of files the filter should be applied to. The filters have two phases, clean which is applied when adding files to the index, and smudge which is applied when adding them to the working directory.

git config --global core.attributesfile ~/.gitattributes_global
git config --global filter.fix-eol-eof.clean fixup-eol-eof %f
git config --global filter.fix-eol-eof.smudge cat
git config --global filter.fix-eol-eof.required true

Finally, put the fixup-eol-eof script somewhere on your path, and make it executable. The script uses sed to do some on the fly editing (remove spaces and blanks at the end of lines, and extraneous blank lines at the end of the file)

#!/bin/bash
sed -e s/[  ]*$// -e :a -e '/^\n*$/{$d;N;ba' -e '}' $1

Lastly, create or open ~/.gitattributes_global in your favorite editor and add lines like:

pattern attr1 [attr2 [attr3 []]]

So if we want to fix the whitespace issue, for all of our c source files we would add a line that looks like this:

*.c filter=fix-eol-eof

The filter has two phases, the clean phase which is applied when things are added to the index or checked in, and the smudge phase when git puts stuff into your working directory. Here, our smudge is just running the contents through the cat command which should leave them unchanged, with the exception of possibly adding a trailing newline character if there wasnt one at the end of the file. The clean command is the whitespace filtering which I cobbled together from notes at http://sed.sourceforge.net/sed1line.txt. It seems that it must be put into a shell script, I couldnt figure out how to inject the sed command, including the sanitation of the extraneous extra lines at the end of the file directly into the git-config file. (You CAN get rid of trailing blanks, however, without the need of a separate sed script, just set the filter.fix-eol-eofto something like sed 's/[ \t]*$//' %f where the \t is an actual tab, by pressing tab.)

The require = true causes an error to be raised if something goes wrong, to keep you out of trouble.

Please forgive me if my language concerning git is imprecise. I think I have a fairly good grasp of the concepts but am still learning the terminology.

Thanks @VonC! I also want to take this opportunity to point out that the git attributes can be configured in a per-repisitory basis in the .git folder rather than globally, which might make more sense.

Make git automatically remove trailing whitespace before committing - ...

git whitespace githooks
Rectangle 27 32

ngRepeat creates a copy of the array when it applies a filter, so you can't use the source array to reference only the filtered elements.

In your case, in may be better to apply the filter inside of your controller using the $filter service:

function MainCtrl( $scope, filterFilter ) {
  // ...

  $scope.filteredData = myNormalData;

  $scope.$watch( 'myInputModel', function ( val ) {
    $scope.filteredData = filterFilter( myNormalData, val );
  });

  // ...
}
filteredData

What I understood is that I use {{filteredData.length}} instead of data.length. I also understood that myInputModel is the model mapped to the input query which filters the data. val would be the text that is typed in the input (basically query) but each time I type, it changes. But what is filterFilter here? I might add that I have my own customFilter created (wherein I can specify which key of the object to consider for filtering).

That's right. Also just use ng-repeat="person in filteredData" as there is no sense filtering it twice. With the $filter service, you can ask for a specific filter by just suffixing it with "Filter", e.g.: dateFilter, jsonFilter, etc. If you are using your own custom filter, just use that one instead of the generic filterFilter.

What about applying multiple filters to one ng-repeat, say you have 2 dropdowns with values and one text input field?

The filter is just a function, so you'd just pass the output of the first filter to the second filter.

javascript - How to display length of filtered ng-repeat data - Stack ...

javascript angularjs
Rectangle 27 25

The $query variable in the filter represents a WP_Query object, so you shouldn't be passing a new WP_Query object into the method for setting that object's properties.

The question you copied code from was incorrectly using the filter, which i feel is the crux of your issue.

Yes, tax_query can be used inside a pre_get_posts (or similarly parse_request) filter/action.

Here is an example: Specify a custom taxonomy for search queries

function search_filter_get_posts($query) {
    if ( !$query->is_search )
        return $query;

    $taxquery = array(
        array(
            'taxonomy' => 'career_event_type',
            'field' => 'id',
            'terms' => array( 52 ),
            'operator'=> 'NOT IN'
        )
    );

    $query->set( 'tax_query', $taxquery );

}
add_action( 'pre_get_posts', 'search_filter_get_posts' );

could you give a working example of setting the tax_query inside a pre_get_posts action?

$tax_query is an object that contains a nested array. You can't override the object with a nested array.

$tax_query is not an object, $query is though(it's an instance of WP_Query).

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

pre-get-posts
Rectangle 27 232

Here's an example of applying dropshadow to some svg using the 'filter' property. If you want to control the opacity of the dropshadow have a look at this example. The slope attribute controls how much opacity to give to the dropshadow.

Relevant bits from the example:

<filter id="dropshadow" height="130%">
  <feGaussianBlur in="SourceAlpha" stdDeviation="3"/> <!-- stdDeviation is how much to blur -->
  <feOffset dx="2" dy="2" result="offsetblur"/> <!-- how much to offset -->
  <feComponentTransfer>
    <feFuncA type="linear" slope="0.5"/> <!-- slope is the opacity of the shadow -->
  </feComponentTransfer>
  <feMerge> 
    <feMergeNode/> <!-- this contains the offset blurred image -->
    <feMergeNode in="SourceGraphic"/> <!-- this contains the element that the filter is applied to -->
  </feMerge>
</filter>
<circle r="10" style="filter:url(#dropshadow)"/>

Box-shadow is defined to work on CSS boxes (read: rectangles), while svg is a bit more expressive than just rectangles. Read the SVG Primer to learn a bit more about what you can do with SVG filters.

Is there a way of controlling the opacity of the dropshadow?

@HughGuiney: yes, of course. Here's an example of one way of doing that, xn--dahlstrm-t4a.net/svg/filters/. Just vary the slope attribute to tweak how much opacity you want.

@LorenzoPolidori IE10 and Safari 5.2 both support SVG filters.

Example on how to implement this approach in D3.js: bl.ocks.org/cpbotha/5200394

css - SVG drop shadow using css3 - Stack Overflow

css html5 css3 svg svg-filters
Rectangle 27 1

You can do this using a filter.

Once you have a list of all the lines, use something like the following:

def f(line):
    return re.match(r'ion', line)

matches = filter(f, all_lines)

The list matches will contain the subset of the lines in all_lines which contain 'ion'

regex - How to find and count each line in a text file using regular e...

python regex python-2.7 text-files
Rectangle 27 3

You are using a filter, where you want to alter the left-hand-side expression instead, using a conditional expression:

[1 if x % 2 == 0 else 0 for x in range(99)]
[1 - (x % 2) for x in range(99)]

Thanks! Spent some time struggling with this issue and you've showed me how simple the syntax really is. In terms of left/right hand side of expressions and filtering, is there any good content on web which explains this for a beginner? None of the basic expressions I've encountered to date in lists seem to deal with this? I did try to create a function first, and then call the function within the list to generate. Struggled with this too:

` def odd_even(): for x in range(0,99): if x % 2 == 0: x = 1 else: x = 0 List1 = [odd_even()] print(List1) `

@MarkGuk: this doesn't really work in comments, but it looks like you are not returning anything from the function. You'd still have to build a list in the function itself, or read up on generator functions (which is perhaps a little too advanced at this stage).

how do I format the above text as code?

@MarkGuk: you can't; you can use backticks (`, no spaces between the backtick and the text) to format the line but you cannot have newlines or indentation. Comments are not for code.

Create Python List using a True/False expression check? - Stack Overfl...

python list if-statement expression