I am looking for an example how to store one key and multiple values example qualifications as below:
[name:'Test1',job:'QA',qualifications:['Selenium','Java']]
Map<String,String>=new HashMap<String,String>//not allowing multiple values.
You need to know, that you are using a map containing entries of different key type. In your case, the most common key type for all values is Object, becuase name and job keys are of type String, while qualifications is of type List<String>. If you want to create such a map step by step (by specifying each key-value entry), you need to make sure that qualifications is a list. You can do it by assigning a list of predefined entries, or by assigning an empty list and then adding elements to it with << operator. Consider the following example:
def expected = [name:'Test1',job:'QA',qualifications:['Selenium','Java']]
def emp = [:]
emp.name = "Test1"
emp.job = "QA"
emp.qualifications = []
emp.qualifications << "Selenium"
emp.qualifications << "Java"
assert emp == expected
In this example, we create an empty list and later we add values to. Alternatively, we could assign a list containing both values already.
def expected = [name:'Test1',job:'QA',qualifications:['Selenium','Java']]
def emp = [:]
emp.name = "Test1"
emp.job = "QA"
emp.qualifications = ["Selenium", "Java"]
assert emp == expected
Your example from comment did something different. Instead of adding an element to a list, it was overriding emp.qualification entry with a value of type String. This is why it stored only single the last assigned value.
Related
so I have a django filter that looks like this:
class ModelFilter(FilterSet):
user_name = CharFilter(method="some_method")
boss = ModelChoiceFilter(...)
My model looks simillar to this:
class Employee(Model):
username = Charfield(...)
boss = ForeignKey("self", ''')
So an employee can be the boss of another employee. Now, this filter will return the correct queryset based on what values the user is searching for. Let's say we have three objects:
O1= Employee(usename="u1", boss=None)
O2= Employee(usename="u2", boss=O1)
O3= Employee(usename="u3", boss=O2)
If I apply the above mentioned filter on this data, and search for boss=O1 I will get the Object O2 as a result. I want to add a new boolean field in the filter, let's say "with_subordinates", that will return the whole "tree" relationship if it is true. So for instance if I would search for: boss=O1, with_subordinates=True, the resulte should be O2 and O3. Basically, with this new option, the filter should recursively show the employees, of previous employees and so forth.
Is there a way to achieve something like this?
Apart from core concepts, we will do it the pythonic way. For this, we need to get the all objects and their boss_id from the database.
boss_object_ids = [1,] # this is the input boss id
have_to_wait = True
while have_to_wait:
prev_ids = boss_object_ids
if Employee.objects.filter(boss__in=boss_object_ids).count() > 0:
boss_ids_list = Employee.objects.filter(boss__in=boss_object_ids).values_list('id', flat=True)
boss_object_ids.extend(boss_ids_list)
boss_object_ids = list(set(boss_object_ids))
if set(boss_object_ids) == set(prev_ids):
have_to_wait = False
all_subordinates = Employee.objects.filter(boss__in=boss_object_ids)
Explanation:
At first time we pass input boss_id = [1,] or some integer.
The second time it will loop and find 2,3,4,5 are the ids, hence the list will be [1,2,3,4,5].
The third time it will get 2,3,4,1,6 ids, hence the list will be [1,2,3,4,5,6].
Like wise it will filter until it gets the same list again.
That means, in this example, it will check if there is no extra number other than [1,2,3,4,5,6].
At last, we can filter using the boss_object_ids list. This is the desired all subordinates id's list.
I have a list of objects which contain several properties. I am looking to break the list into several lists composed of objects which posses the same sub-property.
Here is a hypothetical example, say I have a list of Cars. Each Car has properties: id, manufacturerId and color.
I would like to create lists of Cars for those with matching manufacturerId properties.
I have tried using list.where within list.forEach to create new sub-lists, however I get duplicate lists because when the property I am comparing against (A) matches with another property (B), I get another sub-list when:
B = A.
You can use groupBy from package:collection
var carsByManufacturer = groupBy(cars, (car) => car.manufacturerId);
This will create a Map where the keys are the manufacturerID, and the values are lists of cars with that manufacturer.
Then do,
for (final manufacturerEntry in carsByManufacturer) {
final key = manufacturerEntry.key;
final value = manufacturerEntry.value;
final listOfCarsFromSameManufactuer = List.from(entry.value);
...
}
You will now have lists called: listOfCarsFromSameManufactuer.
Initially I have inserted integer values hence schema created with column type number, later string values were also inserted in same column. Now I am facing issue while fetching values. Need tho update column type number to string.
Well, there are no columns in DynamoDB and even if you consider attributes as columns which they are not, they don't enforce specific type, except for primary key. Therefore you can't change the type of a column.
If you are asking about how to change type of a specific attribute for all items in a table, then you need to run update command on all of the items. DynamoDB unfortunately doesn't support batch update operation, therefore you need to fetch keys of all the items that you need to updated, loop through that list and update each item separately.
I recently had to do this. Here is my script that I used:
Assume that 'timestamp' is name of column you need to change from string to number. So here is solution:
import boto3
from boto3.dynamodb.conditions import Key
db_client = boto3.resource('dynamodb', region_name="eu-west-3")
table_res = db_client.Table(TABLE_NAME)
not_finished = True
ret = table_res.scan()
while not_finished:
for item in ret['Items']:
if 'timestamp' in item and isinstance(item['timestamp'], str):
new_item = item
new_item['timestamp'] = int(float(item['timestamp']))
print("fixing {}, {} -> {}".format(item['SK'], item['timestamp'], new_item['timestamp']))
table_res.put_item(Item = new_item)
if "LastEvaluatedKey" in ret:
last_key = ret['LastEvaluatedKey']
ret = table_res.scan(ExclusiveStartKey = last_key)
else:
not_finished = False
I do understand you probably don't need this anymore, but I still hope this will help somebody.
I am capturing events from a stream, each event is a Device Object. The way the stream work is that it is on a timer, so it picks up the same device multiple times and adds to the stream.
I am putting all theres is a List<Device> and putting that into another stream.
I have create a StreamTransformer in the attempt to remove duplicate from the list and then add the unique list back into the stream.
This transform code below, I have tried to add to set and back to list, but this hasn't worked I assume due to the fact they are objects not strings.
//Transform Stream List by removing duplicate objects
final deviceList = StreamTransformer<List<Device>, List<Device>>.fromHandlers(
handleData: (list, sink) {
List<Device> distinctList = list.toSet().toList();
sink.add(distinctList);
});
I have attempted to use .where and other libraries but to no avail and am hoping for some guidance.
Device Object contains unique id and name that could be used to filter
out duplicates
Question: How can I remove duplicate objects from a List in Dart?
Thanks in advance.
First of all you would need to define by which criteria the objects are supposed to be unique. Is there an identifying property for example? If that is the case the following options should work.
The most efficient way is probably to make the approach with a set working. For that you would need to turn your objects into data objects, meaning have them identify for equality by property values. For that you would override the equality operator and hashCode getter. However this changes how your objects behave on every equality operation, so you would have to judge if that is suitable. See this article.
Another option is to just filter manually using a Map:
class MyObj {
String val;
MyObj(this.val);
}
TestListFiltering(){
List<MyObj> l = [
MyObj("a"),
MyObj("a"),
MyObj("b"),
];
// filter list l for duplicate values of MyObj.val property
Map<String, MyObj> mp = {};
for (var item in l) {
mp[item.val] = item;
}
var filteredList = mp.values.toList();
}
How should I search for all null values for a given object (name)?
model:
name = models.CharField(max_length=150,null=True,blank=True)
u_name=models.CharField(max_length=25,null=True,blank=True)
year=models.PositiveSmallInteger(blank=True,null=True)
I am looking to back populate some data through various 'lookups'.
It may or may not have value for various fields for a given object. I want to populate those fields that are null with the available values through lookups.
I can fetch one field that is null. But is there a way fetch all the null values for a give name 'rig'
u_name = Name.objects.filter(name='rig', u_name__isnull=True)
Thanks
Note that CharFields will store 'null' values as empty strings (https://docs.djangoproject.com/en/1.8/ref/models/fields/#null), so you may want to try the following:
u_name = Name.objects.filter(name='rig').filter(u_name=None)
or
u_name = Name.objects.filter(name='rig').filter(u_name="")
Update based on comments:
To get the Names with name='rig':
rigs = Name.objects.filter(name='rig')
then loop over empty u_names:
for u_name in rigs.filter(u_name=""):
# do things
and then loop over empty years:
for empty_year in rigs.filter(year=None):
# do things