w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Django Clear All Admin List Filters
If you have at least one entry in search_fields and therefore are showing a search box on your admin changelist page, if you have any filters or search terms in effect you should see information to the right of it showing the number of rows that match your current filter and search criteria. It'll be worded as something like "5 results (50 total)". The "50 total" text will be a link to an unfiltered version of the list, showing the whole set. Possibly paginated, but all filters will be cleared. This doesn't appear to be automatically exposed without the search box. The filter settings are simple arguments in the URL querystring, so it should be easy to add a link similar to the one in the search box that just drops the querystring, but you'd have to learn a little about the admin temp

Categories : Python

In R, how can I construct an anonymous list containing an element whose name is contained in a variable?
One option: a <- "b" > setNames(list(2),a) $b [1] 2 or the somewhat more "natural": l <- list(2) names(l) <- a and if you look at the code in setNames you'll see that these two methods are so identical that "the way to do this" in R really is basically to create the object, and then set the names, in two steps. setNames is just a convenient way to do that.

Categories : R

Django lte/gte query on a list
If I understand correctly, gpstime is a list of the times, and you want to produce a list of framenames with one for each gpstime. Your current way of doing this is indeed very slow because it makes a db query for each timestamp. You need to minimize the number of db hits. The answer that comes first to my head uses numpy. Note that I'm not making any extra assumptions here. If your gpstime list can be sorted, i.e. the ordering does not matter, then it could be done much faster. Try something like this: from numpy import array frame_start_times=array(Frame.objects.all().values_list('start_time')) frame_end_times=array(Frame.objects.all().values_list('end_time')) frame_names=array(Frame.objects.all().values_list('frame_name')) frame_names_for_times=[] for time in gpstime: frame_inds=

Categories : Python

Using django filters
Your current query is incorrect because, You are filtering poll ids, if choice objects of the same ids are present in the database, which is not accurate. To filter out polls with no choice, you need to do queryset=Poll.objects.filter(choice__isnull=False).order_by('-pub_date').distinct()[:5] #Get only polls with a choice. Now,every Poll before now can be filtered like this: queryset = Poll.objects.filter(choice__isnull=False, pub_date__lte=timezone.now()).order_by('-pub_date').distinct()[:5]

Categories : Python

how to combine filters in Django
I don't believe normal QuerySet object support those operators but you can dynamically build a dictionary of kwargs and pass it using ** dynamic_lookup_dict = {} if condition: dynamic_lookup_dict['session_inicio__gte'] = 'avalue' elif other_condition: dynamic_lookup_dict['session_inicio__lte'] = 'avalue' django_filters.filter(**dynamic_lookup_dict)

Categories : Python

Complex filters in Django Model
Q objects. resultquery = (Q(field1='val11') | Q(field1='val12')) & ... result = SomeModel.objects.filter(resultquery) Also, in.

Categories : Python

Django on SQL Server database filters
Try looking at the raw SQL that Django generates >>> from django.db import connection >>> from myapp.models import Medico >>> Medico.objects.using('emanager2').get(id=1) # you said this one works <Medico object> >>> connection['emanager2'].queries [{u'sql': u'YOUR SQL WILL BE HERE', u'time': u'0.117'}] >>> Medico.objects.using('emanager2').all() # you said this one didn't work [] >>> connection['emanager2'].queries ... more SQL printed here

Categories : Sql Server

How to filter a Django query set by passing in a list of options?
You can use __contains or __exact and for case insensitive matches __icontains and __iexact You can use Q model lookups to do an and filtering: options = ['X1', 'X2', 'X3'] qs = [Q(attribute_name=option) for option in options] #or attribute_name__icontains - or whatever query = qs.pop() #get the first element for q in qs: query |= q qs = MyModel.objects.filter(query)

Categories : Python

How to query list of ancestors using closure tables in Django?
OK, I got it right, query for ancestors should say: ancestors = Part.objects.filter(closures_a__descendant_id__exact=self.id) instead of: ancestors = Part.objects.filter(closures_d__descendant__id__exact=self.id) Query returns correct results, but displayed SQL still looks wrong (no JOIN), I have no idea why, I got generated query using this code (path function from class Part from question): def path(self): ancestors = Part.objects.filter(closures_a__descendant_id__exact=self.id) from django.db import connection print(connection.queries) return "{}".format(reduce(lambda a, b: a+" &gt; "+b, map(lambda x: x.name, ancestors), ""))

Categories : Django

django tastypie filters returns use format=json
You just need to tell tastypie the format you want your data in. HTTP clients use Accept header to tell the web server what kind of data it expects. For example, my browsers sends following Accept header: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 The problem here is that tastypie does only implement application/json, application/xml and whatever HATEOAS uses. If tastypie doesn't find any of these in your Accept header it will give the error you describe. You can override this by using get parameter format: localhost:8000/api/v1/requests/?origin__exact=sample&format=json

Categories : Django

input type hidden value into the django template filters
The standard way of using templates in Django consists in passing context variables to it. Consequently So, at some point, you should have context = {'form': form}, 'movpath': movpath} render("template_name.html", context) where movpath is obtained from the form's hidden field. This way, the value of the hidden field of the form is passed to the context, which is passed to the template during rendering.

Categories : HTML

Array null element HasValue construct
The statement: vm[0].CustomerId.HasValue shouldn't return an exception provided that vm[0] is not null. You should be checking this before checking the CustomerId value. There's plenty of resources to explain how array's work (e.g. Arrays C#) so I'm not going to explain that here.

Categories : C#

Query database for an element in an List attribute of a model
This is so called "hole expression" in Opa: [_]. For the database value of list type: list(anything) /my_db/my_list_val the path my_list_val[_] in the query refers to any element of the list. In chapter Querying / Sub-queries of the manual (in the WIKI) the example: dbset(_, _) x = /dbname/complex[smap["key"].lst[_] == "value"] finds the documents based on the list(string) value named lst. If list (actually, record with string map where key is "key" and value is nested record with field lst) contains string "value", then it satisfies the search condition. In your case, the query could be: myToto = /toto/toto[tata_list[_] == "id1"]

Categories : Misc

Getting current element in scipy.ndimage.filters.generic_filter
The current element should be the element in the centre of size (or A[1] in your example), but this can't be relied upon at the edges of the input array, and depends on the mode for handling array borders. The docs instead provide a neat example (adapted for your situation below) for determining the current position in the filter using a class to maintain some state between iterations. This always iterates through the last dimension first; all you should have to do is replace the result line with whatever your filter function actually needs to do, in your case this would be something like result = self._array[self.coordinates] == buffer.max(). a = arange(12).reshape(3,4) class fnc_class: def __init__(self, _array): # store the shape: self.shape = _array.shape

Categories : Python

Convert Image element with CSS3 filters to a Blob
@NielsKeurentjes correctly points out that browsers prevent javascript from saving of most web page content locally for security concerns. However, I offer that you could use canvas to do your image filters. Then simply convert the canvas to an image and open the modified image by itself in a new browser tab. Instruct the user to "right-click-save-as" and you're good. I suggest this method for a couple of reasons: Users are often aware of (and comfortable with) the right-click-save-as method. Even if you find a hack to force JS save locally, browsers will consider the hack a security concern and eventually forbid the hack. Not to mention, hacks are almost always cross-browser nightmares. BTW: In addition to CamanJS, Pixastic is another good image filter library: http://www.

Categories : Javascript

SQL Query conditional where with filters
AND ( ( @includedependants = 0 AND (@groupuid = @emptyuid OR emp.groupuid = @groupuid) ) OR emp.specialgroupuid = @groupuid ) The OR part will always run, no matter the value of @includedependants, which I guess is not what you want. What you want is something more like; AND ( ( @includedependants = 0 AND (@groupuid = @emptyuid OR emp.groupuid = @groupuid) ) OR ( @includedependants = 1 AND emp.specialgroupuid = @groupuid ) )

Categories : SQL

Construct LINQ query using variables in asp.net WebAPI
You need to look a dynamic linq library i think then you can execute string statements inside your linq http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx or you can execute direct query http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.executequery.aspx

Categories : C#

Construct a query as a condition to insert set of records
I'll take a stab at it. Try this in the stored procedure: if (EXISTS(select 3465,pr.plan_id,pr.id,epr.credits,effective_date from providers pr left join @EmployeeProviders epr on pr.id = epr.id and pr.plan_id = epr.plan_id and pr.credits = epr.credits and effective_date = '2013-07-01' where epr.credits is NULL )) INSERT INTO @EmployeeProviders (employee_id, plan_id, id, credits, effective_date) select 3463,plan_id,id,credits,'2013-07-01' from @Providers See it in action

Categories : SQL

Construct an SQL query to populate one table using data from another
You could use WHERE NOT IN based on the date. INSERT INTO holdings (accountid, holdingdate, holdingid, holdingvalue) SELECT accountid, valuationdate, NULL, valuation FROM valuations WHERE valuationdate NOT IN ( SELECT holdingdate FROM holdings ) I don't know if you still need both an Id column and a holdingid column. You'll have to decide what to do with those.

Categories : SQL

Is it possible to construct this sql update query without wrapping it in a cursor?
Try this one - Query: DECLARE @Dictionary TABLE (WordKey VARCHAR(255), WordValue VARCHAR(400)) INSERT INTO @Dictionary (WordKey, WordValue) VALUES ('[key1]', 'Value1'), ('[key2]', 'Value2'), ('[key3]', 'Value3') DECLARE @Phrasings TABLE (Phrasing1 VARCHAR(400), Phrasing2 VARCHAR(400), Phrasing3 VARCHAR(400)) INSERT INTO @Phrasings (Phrasing1, Phrasing2, Phrasing3) VALUES ('[key1]', 'random text', 'random text'), ('random text', 'random [key2] text', 'random text'), ('random text [key1]', 'random [key2] text', 'random [key1] [key3] text') ;WITH cte AS ( SELECT x = ( SELECT Phrasing1 , Phrasing2 , Phrasing3 FROM @Phrasings t FOR XML PATH('ID') ), lvl = 1 UNION ALL SELECT REPLACE(x,

Categories : Sql Server

How to construct a more complex mysql query for optimization
Assuming your first query returns a single result, then this should work: DELETE p FROM possessions p INNER JOIN goods_meta_data gmd ON p.good_id = gmd.id INNER JOIN cities c ON c.name = 'St Charles' WHERE p.day_created < c.day - gmd.durability

Categories : PHP

How to construct a list of float?
I reported this to the F# team a while ago, but you need to specify the step manually when using Measures. let testFunc (x: float<metre>) = x let otherTestFunc = [0.0 <metre> .. 1.0<metre> .. 10.0 <metre>] // How do I make this return float<metre> |> List.map (fun x -> testFunc x)

Categories : F#

Combination of two different filters in one Query - Elastica
Why don't you add the range filter as another must term in the bool filter: $rangeFilter = new Elastica_Filter_Range(); $rangeFilter->addField('date', array( 'from' => $datepicker, 'to' => $datepicker1 ) ); $elasticaFilterBool->addMust($rangeFilter); $elasticaQuery->setFilter($elasticaFilterBool); You need to use filters, not queries, in a boolean filter. Note I have used Elastica_Filter_Range instead of the range query you were using. Also, you know you are using an outdated version of Elastica, the new ones use namespaces!

Categories : PHP

How to construct MySQL query to get Products with all selected Features?
This is an example of a set-within-sets query. I think the best approach is aggregation, because it provides the most flexibility. Here is how you would find the products with all three features: SELECT p.* FROM products p INNER JOIN features_products fp ON p.id = fp.product_id group by p.id having sum(fp.feature_id = 1) > 0 and sum(fp.feature_id = 5) > 0 and sum(fp.feature_id = 11) > 0; Each condition in the having clause is checking for the existence of one product. What makes this flexible is if you wanted to have inclusion and exclusion lists. For instance, always has 1 and 5, but never 11: SELECT p.* FROM products p INNER JOIN features_products fp ON p.id = fp.product_id group by p.id having sum(fp.feature_id = 1) > 0 and su

Categories : Mysql

How to construct a jpeg from a list of grayscale weights
Something like this should get you going (not tested): old_image = Image.open("old.jpg") old_data = old_image.load() new_image = Image.new("RGB", old_image.size) new_data = new_image.load() width, height = old_image.size for x in range(width): for y in range(height): new_data[x, y] = old_data[x, y] new_image.save("new.jpg")

Categories : Python

C++ - construct vector of unique_ptr via initialization list
You can make an initialization list like this: #include<memory> class base{}; class derived1 : public base{}; class derived2 : public base{};; class derived3 : public base{};; using namespace std; int main (){ auto ptrs={ unique_ptr<base>(new derived1()) , unique_ptr<base>(new derived2()) , unique_ptr<base>(new derived3()) }; } But the problem seems to be that you can not move from that initializer list since initializer lists are constant. There is more on this here. initializer_list and move semantics I asked a related but different question at in-place vector construction from initialization list (for class with constructor arguments)

Categories : C++

Construct container with initializer list of iterators
From §13.3.2/1 ([over.match.list]) When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases: — Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument. — If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list. In your case the initializer list constructor is deemed non-viable (because std::istream_iterator<std::string> is not convertible to std::string), and the second condition applies

Categories : C++

Appengine query seems to ignore one of my filters (Java)
Have you tried to use .addFilter instead of .setFilter ? Although addFilter is deprecated so it would be more appropriate to use setFilter with CompositeFilterOperator.and(filter ...) Examples on: Datastore Queries documentation.

Categories : Java

Query that filters out results if they exist in a second table
Try the following: SELECT e.employee FROM employees e WHERE status=1 AND NOT EXISTS ( SELECT 1 FROM timecard t WHERE t.employee=e.employee AND t.Date = '8/27/13') where '8/27/13' will work only, if date is a varchar column. Otherwise you should use a more standard date format like '2013-8-27'. Edit: In MSSQL '8/27/13' will actually work, but it is still not a good idea to use this notation as it is not unambiguous when smaller numbers are used, like '5/6/7'. Depending on who entered it (and from which country they come), this could mean either May 6 2007, or 2005 May the 7th or 5 June 2007 ... 2. Edit: Evidently not a good idea to prepare supper while you are putting together a SQLfiddle! The whole thing was buggy. I just fixed it and, of cours

Categories : SQL

filters to query fusion table no working
You have a lot of small mistakes in your code, I created a working example of your code on jsFiddle. You need to properly initialize the FusionTablesLayer. It takes a configuration object where you can define stuff like the query to use or which style to apply: var tableid = "1wPUbMMUyZQkrodr7zk6-_mYJmH4RPc48NvDuzBY"; var layer = new google.maps.FusionTablesLayer({ query: { select: 'lat', from: tableid }, styleId: 2, templateId: 2 }); The styleId defines how the element look on the page, the style with the id two is the one you defined in your Fusion Table. The templateId defines which template should be used for the InfoWindow (when you click on an item on the map). Again, id 2 is the one you defined. The filtering part

Categories : Javascript

Caching results of query when filters are unchanged
I recommend not worrying about this until you can show you have a problem. If you did have a problem you could: Return all results and do the filtering in JavaScript Cache all results on the server and do the filtering in Ruby there

Categories : Ruby On Rails

Search query for multiple date filters
You can do the following, which essentially ignores each parameter if it's null (by forcing the predicate criteria to be true) or uses it in the comparison if it is present. select * from Table 1 where Column1 < case when @StartDateForColumn1 is null then Column1 + 1 else @StartDateForColumn1 end and Column1 < case when @FinishDateForColumn1 is null then Column1 + 1 else @FinishDateForColumn1 end and ...

Categories : SQL

ElasticSearch : Combining query string with term filters
You have to use the multi_field feature of Elasticsearch and filter on the non-analyzed fields; see eg. Why multi-field mapping is not working with tire gem for elasticsearch?

Categories : Ruby On Rails

Elasticsearch - Create report filters using Bool (MUST & AND) DSL query
Since, I cannot post comments yet. I'm answering with some assumptions. First of all, I'm using ES 0.90.2 version and your query works fine for my inputs. However, depending on your input size and the platform that you executed your query, my answer may not be the right one. Assumption: Number of data in the index is less than 20. I've added following inputs to my index: '{"name": "ann", "grade": "vi"}' '{"name": "ann", "grade": "ii"}' '{"name": "johan", "grade": "vi"}' '{"name": "johan", "grade": "ii"}' And my test query was the same as yours, and here is the result: "hits" : { "total" : 2, "max_score" : null, "hits" : [ ] // <-- see this part is blank } As you can see, it didn't listed hits, but there are two hits. That's because of the from:20 code se

Categories : PHP

Simple query table multi search filters
Use a comma to separate the selectors $("#kwd_search, #kwd_search_lang").keyup(function() { You can also use .add $("#kwd_search").add( $("#kwd_search_lang")).keyup(function() { Code $(document).ready(function () { $("#kwd_search, #kwd_search_lang").keyup(function () { var word = $(this).val() if (word != "") { $("#menu_list_comparisons tbody>tr").hide(); $("#menu_list_comparisons td").filter(function () { return $(this).text().toLowerCase().indexOf(word) > -1 }).parent("tr").show(); } else { $("#menu_list_comparisons tbody>tr").show(); } return false; }); });

Categories : Jquery

Query 1 table output same column twice with different filters showing what the other isn't
Something like this? Or were you wanting to do more with rows? EDIT: Modified for SQL Server compatibility: SELECT CASE WHEN WkRoDesc.Job_Code = 'abc' OR WkRoDesc.Job_Code = 'xyz' THEN NULL ELSE WkRoDesc.Job_Code END AS WorkNeeded, CASE WHEN WkRoDesc.Job_Code = 'abc' OR WkRoDesc.Job_Code = 'xyz' THEN WkRoDesc.Job_Code ELSE NULL END AS DPO FROM vhstock, WkInvReg, WkRoDesc WHERE vhstock.no = WkInvReg.Stock_No AND WkInvReg.Ro_Number = WkRoDesc.Ro_Number Note: It almost sounded like you were looking for a GROUP_CONCAT() as well, but I thought I'd wait to be sure... EDIT2: This uses some ugly XML processing in SQL Server to do something like MySQL GROUP_CONCAT. SELECT stuff(( select cast(',' as varchar(max)) + j.Job_Code from WkRoDesc AS j

Categories : SQL

LINQ and web service cannot return anonymous types, and you cannot construct an object in a query?
I think the answer is to create another object to serve as a DTO. This object would not be mapped to the data context and can contain fields that cross the mapped objects. This solves the problems of repetitive properties in the mapped objects, and allows for instantiation of the DTO class in the query as it is not mapped. FYI: with respect to the problem with the join- I revisited that and I think I may have had the inner and outer components of the join switched around before.

Categories : Asp Net

Rackspace - php-opencloud filters - Documentation for valid ObjectList filters?
Unfortunately, the underlying API doesn't support filtering for objects in Swift/Cloud Files containers (cf. http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_Objects-d1e1284.html). The $filter parameter is supported as part of the shared code, but it doesn't actually do anything with Cloud Files here. I'll see if I can get the docs updated to reflect that.

Categories : PHP

Haskell - List pattern matching on multiple parameters? (cannot construct the infinite type)
Your function snippet is perfectly sound: (! 514)-> ghci GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Prelude> let f (x:xs) (y:ys) = x:[y] Prelude> :type f f :: [a] -> [a] -> [a] But the context contradicts that type, and the type inference give you that error. For instance, I can create a context that will give this error: Prelude> let g xs ys = xs : ys Prelude> :type g g :: a -> [a] -> [a] And then if I combine f and g like below, then I get your error: Prelude> let z x y = g x (f x y) <interactive>:7:20: Occurs check: cannot construct the infinite type: a0 = [a0] In the first argu

Categories : List

Using Prolog: Given a list check if the first element of the list equals the last element
Here's an easy one: fela(L) :- first(E, L), last(E, L). Stare at that for a minute and let it really sink in. Actually, it would be right, but your last/2 isn't, simply traversing the list with no base case that will ever succeed. A correct last/2 would look like this: last(L, [L]). last(E, [_|L]) :- last(E, L). I see a lot of confused ideas in your case analysis. For one thing, in Prolog, you don't explicitly return true and false. You simply match what you match and the rest is failure. When dealing with lists, you automatically inherit the base case of the empty list and the inductive case of an element and the remainder of the list. This isn't sufficient to implement fela/1 from scratch because you have no way of remembering what your first element was. So if you want to build i

Categories : List



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.