Ok, I've reimplemented your solution in C#, and what makes the difference
is the fact that you didn't provide the namespace for TaskRequests in
MobileRequest class.
To summarize:
1) You mix attributes for DataContractSerializer and XmlSerializer which
makes this code hard to manage, I've used only XmlSerializer related
attributes.
2) The XML you've provided cannot be the result of serializing the classes
you've presented. It contains "MyNameSpace" on TaskReqests field, whereas
in your code there are no namespaces for XmlSerializer (only for
DataContractSerializer which is not relevant here).
3) The minimal fix of your code to make XML you've given deserialize
correctly (see edit below) is:
[Serializable]
public class MobileRequest
{
[XmlArray(Namespace="MyNameSpace")] //note the n
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.
This blog posting gives examples of how the JAXB XmlElementWrapper is
supposed to work.
According to it, what you have written should give you an empty collection;
see "Mapping #3".
So I think that the real problem is somewhere else. Maybe the schema does
not allow the list to be empty. Maybe the input XML is not what you think
it should be.
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.
As I replied to you on the Salat mailing list, Salat doesn't support
deserializing nested collections right now.
https://github.com/novus/salat/wiki/Collections
I tried your example with this:
public static void main(String[] args) {
String s =
"{"avgEngLength":[{"time":1378905300000,"total":0},{"time":1378906200000,"total":2,"sum":130000,"avgLen":65000.0}]}";
Gson gson = new GsonBuilder().create();
Api a = gson.fromJson(s, Api.class);
System.out.println(a);
}
and it worked (pay attention that your string in example has no escaped
quotes).
Api [avgEngLength=[ApiData [time=1378905300000, total=0, sum=null,
avgLen=null], ApiData [time=1378906200000, total=2, sum=130000,
avgLen=65000.0]]]
So my best guess it that your team is working with different versions of
the library. I'm using Gson 2.2.4 and I checked the source code: that error
string is not present in the library.
This JSON looks badly designed. If you can have multiple children, it
should be an array, such as:
{
"id":"123", "result":
[
{ "children_id": "0", "name": "some name" },
{ "children_id": "1", "name": "some other name" }
]
}
If you have control over the JSON generation, change that (your current C#
code would work in deserialization). If you don't, you are better off
deserializing that to a dictionary, which would make your RootObject look
like this:
public class RootObject
{
public string id { get; set; }
public Dictionary<int, Data> result { get; set; }
}
Jackson does not contains any XPath feature but you can define converter
for each property. This converter will be used by Jackson to convert input
type to output type which you need. In your example input type is
Map<String, Object> and output type is List<String>. Probably,
this is not the simplest and the best solution which we can use but it
allows us to define converter for only one property without defining
deserializer for entire entity.
Your POJO class:
class MyProfileDto {
@JsonDeserialize(converter = SkillConverter.class)
private List<String> skills;
public List<String> getSkills() {
return skills;
}
public void setSkills(List<String> skills) {
this.skills = skills;
}
}
Converter for List<String> s
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
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;
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
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.
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.
You must have a bug elsewhere in your script. The attrgetter works just
fine for both strings and lists:
>>> from operator import attrgetter
>>> class Book:
def __init__(self, author):
self.author_split = author.split()
self.author_first = self.author_split[0]
self.author_last = self.author_split[1]
def __repr__(self):
return 'Book(%r)' % ' '.join(self.author_split)
>>> books = Book('Stephen King'), Book('Dean Koontz')
>>> sorted(books, key=attrgetter('author_first'))
[Book('Dean Koontz'), Book('Stephen King')]
>>> sorted(books, key=attrgetter('author_last'))
[Book('Stephen King'), Book('Dean Koontz')]
>>> sorted(books, key=attrgetter('author_split'))
[Book('Dean Koontz'), Book('Stephen King')
It sounds like you want to group a List to a Map. You haven't provided
enough detail to solve your particular problem. Here's a generic utility
method:
public interface GroupingExpression<T, U> {
T groupBy(U item);
}
public static <T, U> Map<T, List<U>> group(List<U>
list, GroupingExpression<T, U> groupingExpression) {
Map<T, List<U>> groupedMap = new LinkedHashMap<T,
List<U>>();
for(U item : list) {
T key = groupingExpression.groupBy(item);
List<U> keyedList = groupedMap.get(key);
if(keyedList == null) {
keyedList = new ArrayList<U>();
groupedMap.put(key, keyedList);
}
keyedList.add(item);
}
return groupedMap;
}
If you drop this part of the code everything works as expected:
[OnDeserialized]
internal void OnSerializingMethod(StreamingContext context)
ListOfTwo = new List<Two>();
}
If you wish to make sure you always have an empty ListOfTwo change it to:
[OnDeserialized]
internal void OnSerializingMethod(StreamingContext context)
{
if(ListOfTwo == null) {
ListOfTwo = new List<Two>();
}
}
I ran the code with a small modification (not reading from file)
string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<RootLevel> <!--Container-->
<ListOfOne> <!--List of One -->
<One>
<ListOfTwo> <!--List of Two -->
&
I believe in your update function you need to construct a pygame.Rectout of
self.rect because map returns a list type. Right now, you are trying to
call a method of a pygame.Rect on a list object, which certainly will not
work.
I don't know what your alg.w_avg function returns, so you may have to do
something more complicated than a simple cast, but I believe that is the
source of your problem. A potential solution is (if alg.w_avg returns
something 'nice' enough to be easily allow a Rect to be constructed from
it) :
self.rect = Rect(map(alg.w_avg, zip(self.rect, self.dest_vector)))
Edit:
Seeing your w_avg method, I believe what you are going to want to do is
self.rect.topleft = map(alg.w_avg, zip(self.rect, self.dest_vector))
or some other location (center, etc.) on self.re
It is definitely possible to pickle List objects within Python. It is
possible that the custom class you are using may have overridden the
__getstate__ and __setstate__ methods, where-in the developer has decided
not to pickle the widget list by deleting it from the set of attributes to
be pickled/un-pickled for that class.
Refer here for more information. It would be good if you can observe the
source code for this custom class and check if this indeed the case
max() takes a key parameter, a function that when passed one of the objects
returns the value by which to compare them.
Use operator.attrgetter() to get that value:
from operator import attrgetter
max(self.allPartners, key=attrgetter('attrOne'))
This returns the matching object for which that attribute is the maximum.
If you wanted to store just that maximum value itself, you have two
options:
Take the attribute from the returned object:
max(self.allPartners, key=attrgetter('attrOne')).attrOne
Pass just the attributes instead to max() with a generator expression:
max(p.attrOne for p in self.allPartners)
If you find that you need to order the One classes in various directions by
the same attribute again and again (to find the minimum, maximum, sort
them, etc.) you may want to m
You'll need to use the XmlReader and XmlWriter classes or the
DataContractSerializer.
See: How to keep XmlSerializer from killing NewLines in Strings?
public static string XmlSerialize<T>(T objectToSerialize)
{
XmlSerializer s = new XmlSerializer(typeof(T));
var settings = new XmlWriterSettings
{
NewLineHandling = NewLineHandling.Entitize
};
using(var stream = new StringWriter())
using(var writer = XmlWriter.Create(stream, settings))
{
s.Serialize(writer, objectToSerialize);
return stream.ToString();
}
}
public static T XmlDeserialize<T>(string serializedObject)
{
XmlSerializer s = new XmlSerializer(typeof(T));
using(var stream = new StringReader(seria
Is this considered a list of lists, or strings within a list?
This is a list of list.
[
[element],
[element],
[element],
[element],
]
A list of strings would be this:
[
'element',
'element',
'element',
'element',
]
I have tried a for loop but that seems to just bypass the empty strings
and only lists the zip files present in the folder.
Please post what you have tried so far, and the output it gives. I'll edit
this answer with any corrections I can suggest.
Unless there is a Maya specific issue that I don't know about, there are a
couple of ways to do this in Python:
for myObject in myList:
# directly getting and setting attribute
myObject.translateY = 30.0 # set
a = myObject.translateY # get
# alternatively, via setattr and getattr built-in functions.
setattr(myObject, "translateY", 40.0)
# getter which Raises exception if myObject has no "translateY" attr:
a = getattr(myObject, "translateY")
# getter which supplies defaultVal if myObject has no "translateY" attr
a = getattr(myObject, "translateY", defaultVal)
As an aside, it is bad form to call your variable "list", as this name will
shadow Python's built-in list function. Better to use something like
"myList" instead.
You can use the appropriate constructor:
List<List<String>> yourList = new
ArrayList<>(yourCollection);
The order of the elements in the list is the order of the iterator of the
collection.
strip() is a method for strings, you are calling it on a list, hence the
error.
>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False
To do what you want, just do
>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
Since, you want the elements to be in a single list (and not a list of
lists), you have two options.
Create an empty list and append elements to it.
Flatten the list.
To do the first, follow the code:
>>> l1 = []
>>> for elem in l:
l1.extend(elem.strip().split(';'))
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
To do the second, use itertools.
There's no point in having a specific list of values if you also accept any
other value as valid too.
Let's imagine you are a schema validator, trying to validate whether a
value correctly matches this type. You could go through the predefined list
looking for a match, but what happens when the value isn't in that list?
You accept it anyway, because the schema considers any other string value
to be valid too. So there was really no point in checking the list.
Just make the type xs:string or xs:token and leave it at that.
Now Michael Kay had made the argument that a more complex data type (a
union of your enumeration with a string) might still be of some use if
you're using the schema for data typing. Such a schema might look something
like this (just showing the contents of the xs:list
I would rather call the dbSet.add method when the object is new and the
dbSet.attach method when the object already exists. Like this
_dbset.Add(entity); //object is new (create)
_context.SaveChanges();
Or
_dbset.Attach(entity); //object already exists in the dbset (update/modify)
_context.Entry(entity).State = EntityState.Modified;
_context.SaveChanges();
I suppose you are using EF. Btw, why are you using 'virtual List Tag'. How
is this saved to the database? In a separate table? Did you already check
if the date was added to the table?
Kr
YOU got the result because [tb_groups].[f_member_id_creator], maybe, the
empty instead of null. Try this:
coalesce(NULLIF(LTRIM(RTRIM(cast([tb_groups].[f_member_id_creator] as
varchar))), '') + ',', '') + ...
If you agree that you haven't trailing and/or leading spaces you can omit
LTRIM/RTRIM.
Writing a custom JsonConverter for a primitive type is pretty
straghtforward:
using System;
using Newtonsoft.Json;
namespace So17171737_ArrayOrString
{
class StringOrArrayConverter : JsonConverter
{
public override object ReadJson (JsonReader reader, Type
objectType, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType) {
case JsonToken.String:
case JsonToken.Null:
return reader.Value;
case JsonToken.StartArray:
reader.Read();
if (reader.TokenType != JsonToken.EndArray)
throw new JsonReaderException("Empty array
expected.");
return "";
}
throw new JsonReade
No, it doesn't. The replacement list may well be empty. #define FOO means
that defined FOO is true, but FOO is replaced with nothing.
Example:
#define FOO
#define BAR 1
#if defined FOO && defined BAR
int a = FOO + BAR ;
#endif
Result of preprocessing:
int a = + 1 ;
Try this:
Cursor data = database.query("notes", fields, null, null, null, null,null);
data.moveToNext();
dataSource = new SimpleCursorAdapter(this, R.layout.highscores, data,
fields, new int[] { R.id.first }, 0);
Does it works?
Remember to add 0 as last parameter to use the non deprecated method.
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.
Remember that indexes start at 0:
sample_list = [1,2,3,4,5,6,7]
# 0 1 2 3 4 5 6
When you do sample_list[-2:2], you're trying to get the second last element
to the third element.
But you can't just go from negative to positive (unless you add in a
negative step). If you wish to obtain a reversed list, then add a step:
>>> print sample_list[2:-2][::-1]
[5, 4, 3]
This is the same problem with your second example. You're trying to go
backwards with negative indicies, but you can't... unless... you add in a
negative step!:
>>> print sample_list[-3:-7:-1]
[5, 4, 3, 2]
result = sorted(result.iteritems(), key=operator.itemgetter(1))
result is not a dictionary anymore.
If I am not mistaken, your problem can be solved this way (assuming lines
comes from somewhere):
result = sorted({(calculate_score(line), line) for line in lines})
print(result[:20])
Take a look at OrderedDict for making an ordered dictionary.
I think you should replace this code
object_list.append(model.objects.order_by('-date_created').all())
with this code :
object_list.append(model.objects.all().order_by('-date_created'))
And I think you don't need to use this code
object_list = sorted(object_list, key=attrgetter('date_created'))
Because you've sorted already using "order by"
I wrote this extension, hope it helps!
public static void MapListIfNotEmpty<TSource, TMapFrom>(this
IMemberConfigurationExpression<TSource> map,
Func<TSource, IEnumerable<TMapFrom>> mapFrom)
{
map.Condition(src => !mapFrom(src).IsNullOrEmpty());
map.MapFrom(mapFrom);
}
and you can use it like this:
Mapper.CreateMap<Model.Event, DataContracts.Event>()
.ForMember(des => des.Divisions, e =>
e.MapListIfNotEmpty(source => source.Geographies));
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