w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python Object list keep changing when I change an other object list
Lose the class attributes. You are not using them anyway. In fact it's causing your bug because all the instances appear to share the same CHAN list class ircServer: def __init__(self, HOST, PORT): self.HOST = HOST self.PORT = PORT self.CHAN = [] def addChan(self, CHANEL): self.CHAN.append(CHANEL) Also consider reading PEP8 and following at least most of the guidelines there

Categories : Python

Take parameter, determine if its an object or list<>; if list<> then loop and treat each item as object
You could do something like this: public static Dictionary<string, object> Pick(object obj, Array Picklist) { Dictionary<string, object> dic = new Dictionary<string, object> (); IEnumerable items = obj as IEnumerable ?? new[] { obj }; foreach(string key in Picklist) { foreach(object item in items) { dic.Add(key, item.GetType().GetProperty(key).GetValue(item, null)); } } return dic; } Note however, this will fail if you actually try to provide two or more items, since it will attempt to add the same key to the dictionary twice. It will also fail if you try to pass an object which doesn't have one of the specified properties. It's unclear exactly what you want this method to do in these cases, but this code s

Categories : C#

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

casting list to list
You should be able to use the Cast() extension method in Linq Objects = HttpContext.Current.Items["Objects"].Cast<object>().ToList() http://msdn.microsoft.com/en-us/library/bb341406.aspx

Categories : C#

Search list of object based on another list of object c#
Well, you could just use: bool hasCode = arts.Any(a => a.BarCode.Intersect(eans).Any()); That's assuming that either you want to treat each Ean object individually, or you've actually overridden Equals and GetHashCode appropriately. It would be more efficient to create a set though: var set = new HashSet<Ean>(eans); bool hasCode = arts.Any(a => a.BarCode.Any(e => set.Contains(e))); As an alternative approach, you could flatten your list to basically be a sequence of barcodes: bool hasCode = arts.SelectMany(a => a.BarCode) .Intersect(eans) .Any(); That's actually probably the cleanest approach, as you don't care about which article has the matching barcode.

Categories : C#

Session Variable List, when adding a new Object I get Object reference not set to an instance of an object
After Session["SessionStats"] = new UserSession(); you have added a new UserSession, whose Option property is null, to Session. Then, when you do ((UserSession)Session["SessionStats"]).Options.Add(RO); you are pulling out that very same object and accessing the Option property, which is null, hence the NullReferenceException. It looks like you are forgetting to assign something to the newly created UserOption's Option property. However, you don't seem to be using the Options you are instantiating in the foreach for anything...

Categories : Asp Net

Is there a way to print out an object from a script as it would appear in the REPL? (e.g. myList: List[String] = List(Hello there, World!)
The Scala equivalent of this would be the getClass method (from Java) on java.lang.Object. For instance: scala> 1.getClass res0: Class[Int] = int scala> Nil.getClass res1: Class[_ <: scala.collection.immutable.Nil.type] = class scala.collection.immutable.Nil$ scala> "hello".getClass res2: Class[_ <: String] = class java.lang.String

Categories : Scala

AutoMapper for a list scenario only seems to repeat mapping the first object in the list
For anyone else with this problem, it appears as if the documentation was not working for me. A colleague made the following suggestion: userSearchModel.UserList = UserEvent.Select(item => Mapper.Map<User, UserListModel>(item)); It worked like a charm.

Categories : C#

Using C# LINQ to concat a filtered List to List
If names is empty, what you're meant to do is this: var names = businessNames.Select(item => item.Name).ToList(); Another option is to use the List<T>'s ConvertAll method, like so: var names = buisnessNames.ConvertAll(item => item.Name); However, if it may be not empty, you'd need to use an if statement too: var names = new List<string>(); //some code if (names.Any()) names.AddRange(/*your selected method*/); else names = //your selected method;

Categories : C#

Getting List for Select tag from Map> based in iterator index
When iterating a map via the iterator tag var attribute is not necessary, because the current item pushed to the value stack on each iteration. So, referencing value attribute of the map entry as a list collection. <s:iterator value="listOne" status="stat"> <s:select name="col%{#stat.index}" listKey="KEY" listValue="VALUE" list="dynamicList['%{top}']" /> </s:iterator>

Categories : Java

Error converting an object list to tag list with dynamic UI in shiny
I would guess one problem is that the plot_output_list should not be indexed by strings, but instead by number, i.e. plot_output_list[[symbol]] <- ... should be plot_output_list[[i]] <- ...; i <- i + 1 If that doesn't work, try running traceback() right after you hit the error so we can see where the error comes from.

Categories : R

How to creat a new list from existing list with elements which contains the same id in Linq to object?
list.GroupBy(x => new { x.RefId, x.RefName }) .Select(g => new TestNew() { RefId = g.Key.RefId, RefName = g.Key.RefName, ListGroup = g.Select(y => new Group() { ID = y.ID, Name = y.Name }).ToList() }).ToList();

Categories : C#

When I access a list on an object it incorrectly returns as empty list
You replace the neighbours parameter with an empty list def __init__(self, (x,y,z), n, radius, neighbours): neighbours = [] # <- HERE self.neighbours = neighbours Remove that line, and you should be able to access the neighbour list.

Categories : Python

Append different object into list but the list result in same objects repeating
Whenever you call neighbor_list.append(neighbor) you just add a reference to neighbor, rather than a new list. This means that every list in neighbor_list is just the current value of neighbor. To fix this, you should make a copy of the list like this: neighbor_list.append(copy.copy(neighbor) Documentation for copy

Categories : Python

How to parse String List into List using Gson
Your getGenericClass() won't work, you need to retrieve the class of T. You can provide it : Class<T> type; public Class<T> getType() { return this.type; } or get it at runtime (unsafe, you can find many post on this subjet I think) public Class<T> getType() { return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } Then to build the list token you can use this code : static TypeToken<?> getGenToken(final Class<?> raw, final Class<?> gen) throws Exception { Constructor<ParameterizedTypeImpl> constr = ParameterizedTypeImpl.class.getDeclaredConstructor(Class.class, Type[].class, Type.class); constr.setAccessible(true); ParameterizedTypeImpl paramType = cons

Categories : List

How to short*cirtcuit [] to create a list-like object instead of the standard list ? Is it even possible?
As stated here, python doesn't allow you to override its syntax. Although, this answer contains a hack that might help you (probably not).

Categories : Python

Sorted/unique list of object instances from a larger list?
One way to do this is using itertools.groupby(): import itertools x3 = [next(g) for k, g in itertools.groupby(x2, lambda x:(x.a, x.b))] This picks the first element of each group with the same key.

Categories : Python

Reading values into a List object - Object reference not set to an instance of an object
This change should solve the problem: MyVec::MyVec(void) { MyVector = gcnew List<double>(); } Class member MyVector is initailly null reference. You need to initialize it before using, and MyVec constructor is appropriate place to do it.

Categories : List

What does List.Add(List[index]) creates a new object or a reference?
So this is what I ended up doing... Kindly suggest a better method if you know one. for (int k = 0; k < (count); k++) { myList.Add((string[][])myList[k].Clone()); } Is there any other way to do this? Without having to iterate through every list member?

Categories : C#

Modifying one object in list modifies all objects in list
def touchingBlocks(sourceBlock): touching = [] for t in range(6): touching.append(sourceBlock) # Here is your error touching[0].x += 1 touching[1].x -= 1 touching[2].y += 1 touching[3].y -= 1 touching[4].z += 1 touching[5].z -= 1 return touching You are adding the same object 6 times. Everytime you edit one object, you edit them all. You should create copies of your obect using copy.depcopy (deepcopy will copy the nested objects as well, not just their reference) import copy [...code...] touching.append(copy.deepcopy(sourceBlock))

Categories : Python

scala accessing a list object inside another list
So x is of type List[Object]**, because you've used two different (otherwise unrelated) classes as elements of that list. You'll be unable to access elements other than of type Any without a type cast: val listFromX = x(2).asInstanceOf[List[String]] This is not type-safe, so you'll want to check element types (x(2).isInstanceOf[List[_]]) or pattern matching. ** Use the REPL to verify this; though val x: List[Any] = List ("item1" , "item2" , List ("a,b,c")) works

Categories : Scala

Marshalling List of Object without affecting existing list
JAXB (JSR-222) implementations do not alter the List when marshalling an object to XML1. The marshalled order will match the order of the items in the List. The List.add(Object) method will put the item at the end, but List.add(int, Object) will let you specify the position. 1An exception to this is something like a JPA implementation offering a List that lazy loads data as it is accessed. In this case JAXB implementation would cause the list to change as the data is accessed.

Categories : Java

ComboBox not updating when object added to bound list
Well, it doesn't work that way. The inner List<T> has no change notification mechanism, so adding directly to inner List<T> will not generate any change notification that would eventually reach the combo box. Most convenient way to do what you want is adding the item through the BindingList<T> instead.

Categories : C#

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#

set list of object as dropdown list datasource
Like this: dropdownList.DataSource = GetAllCategories(); dropdownList.DateTextField= "CategoryName"; dropdownList.DataValueField = "JobCategoryid"; dropdownList.DataBind();

Categories : Asp Net

Convert List of object into another List of object
R = V.GroupBy(x => x.id) .Select(g => new Result(){ id = g.Key, vachelid = string.Join(",", g.Select(x => x.vachelid).Distinct()), title = string.Join(",", g.Select(x => x.title).Distinct()), }).ToList();

Categories : C#

Passing whole object instance (that contains an empty List) from View -> Controller results in List.Count==1 in Controller
Use explicit for loop instead of a foreach loop, and reference your elements by their index Have a look at this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx It's a bit old but still applies.

Categories : Asp Net Mvc

Ember-Data: RESTAdapter: It is possible to sideload an object list inside a sideloaded object?
Yes this is possible but it's not called sideloading - ember supports this technique but refers to it as embedded. So replace of the DS.RESTAdapter.configure {(.... sideLoadAs... try: DS.RESTAdapter.map('App.Flight', { flightDetails: { embedded: 'always' } }; Also since this is a hasMany relationship I would suggest changing your model definition to use the plural flightDetails: DS.hasMany('App.FlightDetail') instead of singular. See this SO post for another example of embedded hasMany relationships: How to make embedded hasMany relationships work with ember data

Categories : Rest

Search in a List of List Object in C#
You can use Any()extension method to see if any of the string in list of strings matches your keyword- List<IntVector> newList = UserData.FindAll(s => s.ClientName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 || s.CustomerID.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 || s.AddInfo.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 || s.MobileNo.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 || s.CustomerInfo.Any(t => t.IndexOf(searchSt

Categories : C#

Get unique list of ids from object list
You can add the id's as keys to a dictionary and obtain back the keys of it: d = {} for item in items: d[item.id] = item print d.keys() Now, d.values() contains the items which have the unified ids. As long as no two different items have the same id the above is lossless. Contrasting with other solutions (at the time of writing) this also provides a good mapping between the id and the item with the specified id.

Categories : Python

Map List to List in MVC#
Here is an example AutoMapper configuration: See Custom Type Converters. public class EmployeeDC { public int EmployeeID { get; set; } public string EmployeeName { get; set; } public string EmployeeLocation { get; set; } } public class EmployeeConverter : ITypeConverter<object, EmployeeDC> { public EmployeeDC Convert(ResolutionContext context) { var model = context.SourceValue; var employeeId = ???; var employeeName = ???; var employeeLocation = ???; return new EmployeeDC { EmployeeId = employeeId, EmployeeName = employeeName, EmployeeLocation = employeeLocation }; } } Mapper.CreateMap<object, EmployeeDC>

Categories : C#

CheckedListBox and List of Object's list
It's not binding the List to your DataSource correctly. Instead of passing in the list, you could add them like the first answer in using datasource with CheckBoxList foreach (var item in MyList) MyListBox.Items.Add(item.WhateverFieldYouWantToBind, false); // second param is whether it's checked or not

Categories : C#

Object reference not set to an instance of an object when creating observable collection from list
In this code, either db or Tables is null. var list = db.Tables.ToList(); Make sure to check that before: if (db != null && ds.Tables != null) { var list = db.Tables.ToList(); }

Categories : C#

Object reference not set to an instance of an object when attempting to assign array from list
You never initialize rootAndKey before trying to assign elements to it. Your looping logic also looks a little funny to me. I'm guessing you'll need something like: string[][] rootAndKey = new string[allRoots.Count][]; for(var i = 0; i < allRoots.Count; i++) { var subkeys = root.GetSubKeyNames(); rootAndKey[i] = new string[subkeys.Length]; for(var h = 0; h < subkeys.Length; h++) { rootAndKey[i][h] = subkeys[h]; } }

Categories : C#

object reference not set to an instance of object exception when I try to add element to an array of type List
You haven't created any lists. When you create an array of lists, it won't automatically create all the lists in the array, you have to do that manually: List<string>[] Toursist = new List<string>[numtoursut]; for (int i = 0; i < Toursist.Length; i++) { Toursist[i] = new List<string>(); }

Categories : Asp Net

Data List Header Template causing 'Object reference not set to an instance of an object' error
It's difficult to diagnose this without seeing your code, but I would guess that your DataList1_ItemDataBound method is trying to find the lblExp control in the e.Item without checking the e.Item.ItemType first. This event will be raised for every item in the list, including the header, and the header doesn't contain a control called lblExp. You need to check the ItemType before processing the item: protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) { switch (e.Item.ItemType) { case ListItemType.Item: case ListItemType.AlternatingItem: case ListItemType.SelectedItem: case ListItemType.EditItem: { Label lblExp = (Label)e.Item.FindControl("lblExp"); ... } } }

Categories : C#

Django REST framework: Can a nested object access its parent object's details in a List View?
Moment of clarity: the solution is to use a SerializerMethodField to instantiate the RepSummarySerializer and pass the customer_id in the context: class CustomerSummarySerializer(serializers.HyperlinkedModelSerializer): id = ... name = ... rep = serializers.SerializerMethodField('get_rep') def get_rep(self, obj): rep = obj.rep serializer_context = {'request': self.context.get('request'), 'customer_id': obj.id} serializer = RepSummarySerializer(rep, context=serializer_context) return serializer.data The customer_id can now be accessed in RepSummarySerializer.get_rep_url like this: def get_rep_url(self, obj): customer_id = self.context.get('customer_id') ... Don't know why I didn't think of this thr

Categories : Django

C# Metro Unable to access object properties from List
Your properties in your Tile class are set to private. To be able to access the properties from outside the class you will need to declare them as public: public class Tile { public int ID { get; set; } public string Name { get; set; } public double Frequency { get; set; } public double Divider { get; set; } public int Value { get; set; } public int Turns { get; set; } public int StartLevel { get; set; } } You can keep your same constructor, although that will end up being a mess to maintain as you add/subtract properties. Another way you can instantiate your list of Tile objects is like so: List<Tile> tList = new List<Tile> { new Tile { ID = 0, Name = "Example1" } }; ...for as many public properties as you need to set

Categories : C#

Stop the thread started within a object after the object is no longer in a list?
you have to have a variable for your AsyncTask first, so that you can call: myTasks.get(0).getMyAsyncTask().cancel(boolean); As you can see here, it is not that easy to cancel an AsyncTask. After you call cancel(boolean), it will: (from docs: invoking this method will cause subsequent call to isCancelled() to return true. onCancelled(Object) will be invoked after doInBackground instead of onPostxecute. To ensure that a task is cancelled, you should always check the return value of isCancelled from doInBackground. So, you call cancel(booelan) onto your reference variable of your AsyncTask and in doInBackground, you always check for isCancelled() in order to stop some processes in your doInBackground method. You should handle your doInBackground method manually in order t

Categories : Java

how to convert parent object with child object list into xml file using c#?
XmlSerializer doesn't support IList<T> interface. You have several options: change type from IList<T> to concrete class (e.g. List<T>); use DataContractSerializer instead of XmlSerializer; implement IXmlSerializable; create fake property of type List<T> for XmlSerializer reading and writing to classSubjectList and mark classSubjectList with [XmlIgnore] attribute.

Categories : Dotnet



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