w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Cast List to AnonymousTypes list
You can take advantage of generics and type inference to create the list for you: public static List<T> CreateAnonymousList<T>(params T[] entries) { return new List<T>(entries); } Usage like: var someList = CreateAnonymousList(new { foo = 1 }, new { foo = 2 }, new { foo = 1 }); someList.Where(x => x.foo == 1); Naturally you won't be able to do much with it. You'll never be able to strongly type it in your code to anything other than var or return it out from your method or anything you normally wouldn't be able to do with anonymous types. If you want to do more, you'll just have to bite the (small) bullet and define a class for your anonymous type. Rereading your question, you can still perform LINQ queries on an array: var someArray = new[]{new { foo =

Categories : C#

Can List.Distinct() apply to the list type of List>?
That's because List<T> has no Equals and GetHashCode implemented, so standard reference comparison is being performed. And it returns false, because you have two separated lists. You can write your own IEqualityComparer<List<string>> implementation and provide it as Distinct method parameter. Within the comparer you can use Enumerable.SequenceEqual) method to check if lists has the same content.

Categories : C#

Python: given a list of lists, create a list ordered by the number of occurrences in inner list
You can use collections.Counter to keep a counter for each element inside each sublist. Something like this, >>> from collections import Counter >>> lst = [['a','b','c'], ['a'], ['a','b']] >>> counts = Counter() >>> for sublst in lst: ... for ele in sublst: ... counts[ele] += 1 ... >>> [ele for ele, _ in counts.most_common()] ['a', 'b', 'c']

Categories : Python

In a responsive site design, how do i put a list below other list that contains a sub-list without overlap the main lists
Pretty simple : remove the fixed height of your li.menulinks, add a "header" (green rounded rectangle with 35px height) div as first child of the li and...you're set ! Look at this fiddle : http://jsfiddle.net/32pga/ <div class="sitemap"> <div class="row-fluid"> <ul> <li class="menulinks"> <div class="menulinks-header"></div> <ul> <li class="submenulinks"> <div>Test 1</div> </li> <li class="submenulinks"> <div>Test 2</div> </li> <li class="submenulinks"> <div>Test

Categories : HTML

iterating list of array-list and assigning each list to single dynamically created div in jsp
Try this, <c:forEach var="user" items="${userList}" varStatus="count"> <div id="col${count}"> <c:out value="${user.name}"/> </div> </c:forEach>

Categories : Java

java generics - cast to List issues unchecked cast warning while cast to SomeType not
You get the warning because the cast (List<ScanResult>) data is not safe. Due to type erasure, List<ScanResult> will be List during runtime, so there will be no real type check regarding the element type of the list. That is, that cast will succeed even if you get List<String> as a parameter and later you will get a ClassCastException when you try to access the list: ScanResult result = data.get(0); // ClassCastException: String One way to avoid it is making the interface generic: public interface DataProvider<T> { public List<byte[]> getData(T data); } And then define the specific type argument at implementations: public class DataProviderFromLocation implements DataProvider<Location> { public List<byte[]> getData(Location data) {

Categories : Java

How to modify the style in list(ordered list and unordered list) in HTML?
Here you go. WORKING DEMO The HTML: <ul style="list-style-type:decimal;"> <li>First</li> <li>Second</li> <li>Third</li> </ul> The CSS: li{ position: relative; } li:before{ position: absolute; left: -13px; content: ')'; background:white;} Hope this helps.

Categories : HTML

Why does Haskell let me return an empty list where a list inside a list is expected?
Because [] is of type [[a]] in this case: it is a list containing exactly 0 alpha lists. In general, the empty list can match any list type because every element (all zero of them) is of the correct type.

Categories : Haskell

Unmarshall xml list of objects to java list without class list
You could use JAXB with StAX to do the following: import java.util.*; import javax.xml.bind.*; import javax.xml.stream.*; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(User.class); XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource("src/forum17047306/input.xml"); XMLStreamReader xsr = xif.createXMLStreamReader(xml); List<User> users = new ArrayList<User>(); Unmarshaller unmarshaller = jc.createUnmarshaller(); while(xsr.getEventType() != XMLStreamReader.END_DOCUMENT) { if(xsr.isStartElement() && "User".equals(xsr.getLocalName())) {

Categories : Java

What kind of List is List list = Database.getAllData();?
You don't have to know; that's the point. The interface is what matters to you, not the implementation. You can't know without looking at the source of that method. But even if you do, it's immaterial to your client. All you call are List methods.

Categories : Java

Getting a list of values from a list of dict in python: Without using list comprehension
You could use map() here. map() applies the lambda to every item of testList and returns it as a list. >>> testList = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name': u'Sports'}] >>> map(lambda x: x['name'], testList) [u'Library', u'Arts', u'Sports']

Categories : Python

Why does adding a list to another list, using add range, remove the elements from the first list?
It's because of the IEnumerable. When you set groupsToAdd to the result of groups1.Where(g => false == groups2.Contains(g)) there is deferred execution, which means that the query is not run until AddRange() and then again at Dump(). Because the list, groups2, now contains the elements they no longer are a result of the original query.

Categories : C#

when appending a list with math using another list, how do i make the second list the same length as the first ?
You need to iterate over each elements in start_list: for item in start_list: # for each element in `start_list` square_list.append(item ** 2) # add square of `item` in `square_list` square_list.sort(); # finally sort the list or you can use sorted() function over generator expression: >>> sorted(item ** 2 for item in start_list)

Categories : Python

In python, what happens, will the length of a list decrease if I add part of the list to another list?
The string "hi" will be split into chars and assigned to example when you do example+=python[0] So example in this case will contain ['h','i']. Also, the list python will not lose an element.

Categories : Python

Create larger list from an existing list using a list comprehension or map()
How about: >>> atom_indices = [0, 4, 5, 8] >>> coords = [3*a+k for a in atom_indices for k in range(3)] >>> coords [0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26] We can nest loops in list comprehensions in the same order we'd write the loops, i.e. this is basically coords = [] for a in atom_indices: for k in range(3): coords.append(3*a+k) Don't be afraid of for loops, though, if they're clearer in the situation. For reasons I've never fully understood, some people feel like they're being more clever when they write code horizontally instead of vertically, even though it makes it harder to debug.

Categories : Python

create a list from another list and remove elements from copied list
Yes your understanding is correct. List newList = new ArrayList(collection); will do a shallow copy. You can modify the newList without affecting the original collection, but they will each reference the same elements so if you modify an element in one list, the other list's element will also get the change. This is called a Shallow Copy. Here's a visual representation of what I've described: The things at the bottom are the objects in your array.

Categories : Java

Appending to create a list instead of creating a list inside a list
Use extend: for item in items: forename = re.findall(pattern2, item) surname = re.findall(pattern3, item) mainlist.extend(surname) myList.extend(L) adds the individual elements of L onto myList. It's similar to: for element in L: myList.append(element)

Categories : Python

How to assign List or List to List
I don't think there's an easy way to do that using only strongly typed collections1, since there is no covariant collection interface that exposes a Remove method... I see 2 possible solutions: use the non-generic ICollection interface, that is implemented by List<T>: var collection = (ICollection) CouldBeBearsOrGoats; collection.Remove(whatever); The drawback is that a collection that implements ICollection<T> might not implement ICollection... use dynamic: dynamic collection = CouldBeBearsOrGoats collection.Remove(whatever); But it's probably slower than the previous approach. 1 assuming you don't want to change the actual type of the collections by casting items to IAnimal

Categories : C#

List within a List - How to put new line with LinQ after List within List is over?
Console.Write( String.Join(Environment.NewLine, f.Select(flight => { var segments = flight.Segments.Where(x => x.DepartureDate > DateTime.Now); return String.Join(" ", segments.Select(segment => { return String.Format("Departure: {0}, Arrival: {1};", segment.DepartureDate, segment.ArrivalDate)); }); }); ); I personally prefer to have a Joined extension method on IEnumerable<T> which wraps String.Join (taking a delimiter and an optional transformation delegate), and a Formatted extension method on String which wraps String.Format: var output = f.Joined(Environment.NewLine, flight => flight.Segments .Where(s => s.DepartureDate > DateTime.Now) .Joined(" ", s => "Departure:

Categories : C#

Using a list as "list of indexes" to address elements of another list
You could use reduce(operator.getitem, index, mylist) Here is a complete example: import operator mylist = [[1,2,3],[4,5,6],[7,8,9]] index = [1,2] val = reduce(operator.getitem, index, mylist) print(val) For NumPy arrays, there is a simpler method: import numpy as np ... myarr = np.array(mylist) val = myarr[tuple(index)] print(val)

Categories : Python

How to get the list elements using list inside another list in java
You can try this ,Let say you have variables like double dtime; Timestamp tp; And listofresults is coming from query results. listofresults = results.getResultList(); If list is coming from query then put it in the loop this way in the condition of for loop for(int i=0;i< listofresults.size() ;i=i+2) { dtime=(double) listofresults.get(i); //cast because the value is of object type tp=(TimeStamp) listofresults.get(i+1); //cast because the value is of object type //do something with these variables }

Categories : Java

TSQL - Faster to use IN (list) or use NOT IN (list) for a small list?
NOT IN ('val4') is basically equivalent to WHERE NOT (column = 'val4') /* or column <> 'val4' */ whereas IN ('val1', 'val2', 'val3') is basically equivalent to WHERE ( column = 'val1' OR column = 'val2' OR column = 'val3' ) I would hope that the first option is faster, if only negligibly. The SQL engine might optimize IN differently depending on how many values you specify in the IN function and what indexes are available on your table. What behavior are you seeing that you're questioning the method to use?

Categories : SQL

How to show inner content in list item outside of that list item without being covered up by descending list items
You must set the z-index of the clicked 'li' higher and in return the former clicked 'li' back. Here is the example: fiddle And here the script: var oldli; $('li').click( function(){ $(oldli).toggleClass('displayNone displayBlock'); $(oldli).css("z-index","1"); $(this).toggleClass('displayBlock displayNone'); $(this).css("z-index","5"); oldli=$(this); } );

Categories : Javascript

How to cast a List to an ObservableCollection in wpf?
you can do it by using extension method public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll) { var c = new ObservableCollection<T>(); foreach (var e in coll) c.Add(e); return c; } or you can use this constructor The elements are copied onto the ObservableCollection in the same order they are read by the enumerator of the list. ObservableCollection<YourObject> collection = new ObservableCollection<YourObject>(yourList);

Categories : C#

Why does IEnumerable not need a cast but a List does?
Check out this post about covariance. He gives an explanation and a way to make the code work without the cast. Lists are not covariant, but you can just change the method like so: public void ListMethod<T>(List<T> dbItems) where T : IDbItem { Console.WriteLine(dbItems); } Covariance is the ability to assign a more derived generic type to a base generic type. The reason List is not covariant is because you could do this: class Animal {} class Dog : Animal {} class Cat : Animal {} void someFunction() { List<Animal> dogs = new List<Dog>(); dogs.Add(new Cat()); } dogs is really a list of dogs, not of animals. Therefore adding a Cat to it would be a problem, specifically causing a compiler error.

Categories : C#

Cast dynamic to List
Is there a way to cast my dynamicList to List at runtime I don't know why you declare it as dynamic when it has to be a List<T>, but I'm guessing it is because you don't know what T is. If you did, you could just directly cast it: private static void GetData() { dynamic dynamicList = new List<string> (); FilterAndSortDataList((List<string>)dynamicList); } private static void FilterAndSortDataList<T>(List<T> dataList) { ... } but obviously that could fail at runtime. Another option might be to make GetData generic as well: private static void GetData<T>() { List<T> list = new List<T>(); FilterAndSortDataList(list); } private static void FilterAndSortDataList<T>(List<T> dataList) { ... }

Categories : C#

How to cast an object to a List
Generics and reflection don't play very nicely. Your best bet is to use the non-generic IList API: IList list = (IList)Value; Then you can iterate, access by index, Add, Remove, etc.

Categories : C#

Create sorted list while creation
You can use bisect to perform ordered insertions within a sequence. bisect.bisect_left(a, x, lo=0, hi=len(a)) Locate the insertion point for x in a to maintain sorted order. [...] The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted.

Categories : Python

How To Cast Generic List of One Type To Generic List of an Unknown Type
If you know that each item in the list is of type ObjectType, you can do this: List<object> sourceList = new List<object>() { 1, 2, 3 }; List<int> resultList = sourceList.Cast<int>().ToList(); If you actually want to convert each item in the list in a generic way, the simplest way would be to do something like this: public static IEnumerable<T> ConvertTo<T>(this IEnumerable items) { return items.Cast<object>().Select(x => (T)Convert.ChangeType(x, typeof(T))); } This would be implemented as an extension method, so you can write: List<object> sourceList = new List<object>() { 1, 2, 3 }; List<string> resultList = sourceList.ConvertTo<string>().ToList(); If the target type isn't known at compile-time, you would i

Categories : C#

Fast way to get the label of an item x (in DATA) from a list of labels
Use a dict here, with the item from DATA as key and corresponding item from LABELS as value. Dicts provide O(1) lookup, while searching in lists is an O(N) operation. >>> DATA = [ [2,5,8], [2,4,3], [5,5,7], [9,8,4] ] >>> LABELS = [ "AAA", "BBB", "AAA", "CCC" ] >>> get_labels = {tuple(x):y for x,y in zip(DATA,LABELS)} >>> get_labels[5,5,7] 'AAA' >>> get_labels[9,8,4] 'CCC'

Categories : Python

Fast allocation of linked list and slow deallocation
This is probably an artifact of how the run time library deallocates memory. During allocation, finding a block for each node item is probably just a few operations to take the main pool, and split it into two parts and return the smaller part for your program's use. Freeing that block might include walking a free list to see if these small allocations can be combined into larger free blocks.

Categories : C++

Getting a list of cast-capable devices
The ChromeCast devices are DIAL servers: http://www.dial-multiscreen.org/dial-protocol-specification You can discover their broadcasts on the network and determine their capabilities. You can do all of this in a service. I have written a DIAL client in Android that you could try: https://github.com/entertailion/DIAL Google TV devices are also DIAL servers, so you would have to distinguish between those and the ChromeCast devices.

Categories : Android

List , cast and IEnumerable issues
I suppose you need to put the select results into a new object of type Councur. Then you will be able to add the query to the Councours list: ' pseudo code!!! Dim ccrs = From concours In liste Select new Councur Num = concours.numero_concours Typ = concours.numero_type, Nat = concours.numero_nature, Dat = concours.date_de_sortie, Mat = concours.nbre_matchs, Ran = concours.nbre_rangs, Con = concours.titre_concours, Eta = concours.numero_etape

Categories : Dotnet

Sharepoint 2010 list creation using ecmascript
You can use SPServices with "GetListCollection" to find all the lists in a Sharepoint, and then use "AddList" to create it. Something like: var myList="My List Test"; // the name of your list var listExists=false; $().SPServices({ operation: "GetListCollection", async: true, webURL:"http://my.share.point/my/dir/", completefunc: function (xData, Status) { // go through the result $(xData.responseXML).find('List').each(function() { if ($(this).attr("Title") == myList) { listExists=true; return false } }) // if the list doesn't exist if (!listExists) { // see the MSDN documentation available from the SPService website $().SPServices({ operation: "AddList", async: true, webURL:"http://my.share.point/my/dir/", listN

Categories : Sharepoint

linked list creation run-time error
when I strip your code I come to this Seltsamkeit: start = (N*)malloc(sizeof(N)); for(i=0;i<n;i++) { if(start==NULL) start can never be NULL in this context i normally use "head" and "next" for the pointer to the working memory, and "list" as a running pointer to the last element of the list for the really allocated memory-linked-list. the metacode is: list = NULL; head = NULL; for (i = 0; i < n; i++) { next = malloc(); if (head == NULL) { head = next; // setting the first haed; } else { list->next = next; // attaching to the end } list = next; // pointing to the last element }

Categories : C

Write list of list to file and then retrieve it from the file as a list of list
>>> import pickle >>> banana, beans = ['Banana' , .54 , 'No' , 'Food'], ['Beans' , 1.39, 'Yes', 'Food'] >>> food = [banana, beans] >>> with open('data', 'wb') as f: pickle.dump(food, f) >>> with open('data', 'rb') as f: print pickle.load(f) [['Banana', 0.54, 'No', 'Food'], ['Beans', 1.39, 'Yes', 'Food']]

Categories : Python

Cast List to unknown T[] using reflection
I don't know what you're doing wrong. Here is a LINQPad program that demonstrates, and it seems it uses the same calls that you do, yet I do get an output of the right type of array. void Main() { object valueObj = new List<object> { 1, 2, 3 }; Type type = typeof(int[]); Type elementType = type.GetElementType(); MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast") .MakeGenericMethod( new System.Type[]{ elementType } ); MethodInfo toArrayMethod = typeof(Enumerable).GetMethod("ToArray") .MakeGenericMethod( new System.Type[]{ elementType } ); var castedObjectEnum = castMethod.Invoke(null, new object[] { valueObj }); var castedObject = toArrayMethod.Invoke(null, new object[] { castedObjectEnum }); castedObject.Dump(); } I do g

Categories : C#

Cast ListView Items to List?
The Cast method will essentially try to perform a box/unbox, so it will fail if the items in the list aren't already strings. Try this instead: List<string> list = lvFiles.Items.Cast<ListViewItem>() .Select(x => x.ToString()).ToList(); Or this List<string> list = lvFiles.Items.Cast<ListViewItem>() .Select(x => x.Text).ToList();

Categories : C#

Python: filter list of list with another list
Use a list comprehension: result = [x for x in list_a if x[0] in list_b] For improved performance convert list_b to a set first. As @kevin noted in comments something like list(5,8)(unless it's not a pseudo-code) is invalid and you'll get an error. list() accepts only one item and that item should be iterable/iterator

Categories : Python

Shortest list in list of list (Haskell)
First what you have already: shortest [] = [] I actually don't like this very much because this means there is no difference between shortest [] and shortest [[]] But, if you like this behavior then Data.List has minimumBy which has the type (a -> a -> Ordering) -> [a] -> a So we first need that (a -> a -> Ordering) which we can get with compare and a useful little function called on from Data.Function. on acts like a "nozzle" of sorts and applies a function to 2 arguments before feeding them into another function. cmp = compare `on` length Which just gives us shortest = minimumBy cmp But this breaks when given an empty list so shortest [] = [] shortest ls = minimumBy cmp ls shortest [] = Nothing shortest ls = Just $ minimumBy cmp ls

Categories : List



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