Prepend multiple data to beginning of Core Data (Swift) - ios

Could someone give some guidance on how to prepend newly ingested data to Core Data in the correct index order?
I have Core Data with an attribute, contentID. The objects are listed as: 5, 4, 3, 2, 1, 0
I query a web database that pushes updates since the highest contentID, 5, and it returns an array with updates: 7, 6
If you simply append it to Core Data, the order will go: 5, 4, 3, 2, 1, 0, 7, 6
How do you prepend it to the front correctly?
And also how do you prepend it in the correct order so that when you prepend the first new object, 7, and then prepend the second item, 6, it doesn't go: 6, 7, 5, 4, 3, 2, 1, 0
Hope this makes sense... Thanks!

In general, you should not concern yourself with the order in which objects are written to or stored in the database. Instead, specify the sort order in which you wish to receive the data when you fetch it from the database.
The sort order for a fetch is determined by the sortDescriptors property of the NSFetchRequest. Each NSSortDescriptor specifies the key to determine the order, and whether the results should be in ascending order (v. descending).
So when you perform a fetch, you should in your case specify:
let sort = NSSortDescriptor(key:"contentID", ascending:false)
fetchRequest.sortDescriptors = [sort]
let fetchedResults = managedObjectContent.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]

Related

subscript Array change coordinates

How can I change subscript coordinates in an Array of Arrays [[Int]] so that the way to address a cell would be table[column-letter][row-number], same as Excel, instead of current ios table[row-number][column-number] for a given table like:
var table = [[0, 1, 2, 3],
[1, 32, 44, 25],
[2, 12, 66, 43],
[3, 3, 4, 5]]
Today table[2][1] = 12, but I want table[C][1] = 44.
I need this change to adapt formulas from excel into my app without changing the coordinate system or the tables from an Excel.
I know there are subscript functions in Array class which may help, but I couldnĀ“t make it work so far.
Today table2 = 12, but I want tableC = 44.
Do you know what is [2][1] actually means you are telling the compiler,
i want the element in the array that has index of [2] and by adding another [1], you are telling it that you need the element that has index of [1] that its inside the result of [2].
its an Array of Arrays if you take another look at it empty would be something like this ,
[[],[],[]] // no matter what is the values inside indexing is always the same
with that pointed out now lets take a look on what are you trying to do.
[C][1] = 44
As you can now probably tell this is not valid because [C] is not a valid index as index accept only Integer Types.
So what can we try ?.
Well you can try dictionaries
Read about them here
With dictionary at some point you will be able to get a value like this
value = table["C"]?[1]
or take a look on this example.
var foo :[String:[Int]] = ["A":[1,2,3], "B":[1,2,3]]
let colm = foo["A"]?[0]
Edit another solution inspired by #Paulw11
using this "A".utf16.first! - 65 will return 0 index to use inside the Array so you can additionally say from A to Z
table = ["MyChar".utf16.first! - 65][2]

Rail postgres array contains (<#) dont include nil

I have a Matchups table that includes a field that is equipment_id and stores an array
I am trying to search the Matchups table to get any records that have an array where it contains specific equipment ids. For example:
So I am running:
search_equipment_ids = [1, 2, 3, 4, 5]
Matchup.where("equipment_id <# ARRAY[?]", search_equipment_ids)
The following are a few examples of arrays that are stored in the table in equipment_id and what the above query would result in
[1, 2] = True
[3, 5] = True
[1, 2, 3] = True
[1, 2, nil, 3] = False
How can get the search to ignore that there might be a nil included in the array. I am going to make a change to how the array is stored so from here on out there will be no nil values...but in the mean time I need to take these into account.
I am using: https://www.postgresql.org/docs/9.5/static/functions-array.html as a reference.
I dont want to use the && operator because the Matchups table is huge it will return to many results if just comparing if one equipment id is present. I want to only return if all the equipment_ids are contained (excluding any nils).
Thank you!
How about removing the nil values from the array? That's easy:
Matchup.where(..., equipment_ids.compact)

How can I delete certain indeces defined in an array from an other array in ruby

I have a method that iterates over an array, does a bunch of stuff under certain conditions and depending on these conditions I would ALSO like to delete some of the elements. In order to keep track of the indexes I like to delete I converted the each in to an each_with_index loop and store the index of the elements that I like to delete in an array index_array. How can I delete exactly the items on those indexes in my original array? Looping over the index_array and using delete_at would change the original index. Please see below description of the scenario:
> my_array = [0,1,2,3,4,5,6,7]
> delete_these_indexes = [1,2,5]
the desired result is:
> my_array => [0,3,4,6,7,8]
How about this?
my_array = [0, 1, 2, 3, 4, 5, 6, 7]
delete_these_indices = [1, 2, 5]
delete_these_indices.sort.reverse_each {|i| my_array.delete_at(i) }
p my_array
# => [0, 3, 4, 6, 7, 8]
It's important to delete from the end of the array, since deleting an item will change the indices of all subsequent items, ergo sort.reverse_each. If you know the array is already sorted, you can just do reverse_each.
If you don't care bout modifying the delete_these_indices array, you can be somewhat more terse:
delete_these_indices.sort!
my_array.delete_at(i) while (i = delete_these_indices.pop)
Again, you can skip sort! if you know delete_these_indices is already sorted.
keep_these_indexes = my_array.each_index.to_a - delete_these_indexes
#=> [0, 3, 4, 6, 7]
If you wish to modify my_array (which appears to be the case):
my_array.replace(my_array.values_at(*keep_these_indexes))
#=> [0, 3, 4, 6, 7]
If not:
new_array = my_array.values_at(*keep_these_indexes)
See Array#values_at.
delete_these_indexes.each_with_index do |val, i|
my_array.delete_at(val - i)
end
deletes at the desired index taking into account how many have previously been deleted and adjusting for that
https://repl.it/CeHZ
Probably not the best answer, but you can do this as well:
delete_at_indices.each {|ind| my_array[ind] = nil }
my_array.delete(nil)
Takes a first pass to conceptually invalidate the data at the specified indices, then the call to .delete will blow out any values that match what's passed in.
This solution assumes that you can define a value that isn't valid for your array. Using nil will be problematic if you're treating this as a sparsely populated array (where nil is a valid value)
Technically you're iterating through each array once, but that Gentleman's Agreement on what your deletable value might make some people uncomfortable

Efficient way to randomize data model in Rails

Creating a programming schedule based on videos in object model.
I want to run a task every day to shuffle this model so the programming each day would be different.
I am aware of
product.shuffle.all for ex. but I want the order to be saved one time each day to do so vs on each server call.
I am thinking to add an attribute to each product, named order which would be an integer to order by. How would I shuffle just product.order for all products in this case?
Would this be the most efficient way? Thanks for the help!
You could use the random parameter of shuffle. It allows for stable randomization:
# When the Random object's seed is different, multiple runs result in different outcome:
pry(main)> [1,2,3,4,5,6,7].shuffle(random: Random.new)
=> [5, 6, 3, 4, 1, 7, 2]
pry(main)> [1,2,3,4,5,6,7].shuffle(random: Random.new)
=> [1, 7, 6, 4, 5, 3, 2]
# When the Random object is created with the same seed, multiple runs return the same result:
pry(main)> [1,2,3,4,5,6,7].shuffle(random: Random.new(1))
=> [7, 3, 2, 1, 5, 4, 6]
pry(main)> [1,2,3,4,5,6,7].shuffle(random: Random.new(1))
=> [7, 3, 2, 1, 5, 4, 6]
By basing the seed e.g. on the number of day in the year you can determine when the results randomization changes. You can (obviously) restore the randomization for any given day if you need to do so.
What I think you want to do would be best solved with a combination of the gem paper_trail along with your product.shuffle.all and an update_attributes call to the DB. That way you can view past versions as they are updated in your DB.

Get documents by querying over an array

I have an array of ids. Now I want to get all the documents corresponding to the ids inside that array from a collection.
Is there any command by which I can achieve this?
I don't want to run a loop over that array and query for every element of the array.
Assume the array is
id = [1,2,3,4]
The collection is Scores, which has the field id among other fields.
I'm looking for something like Scores.find(..)
In ActiveRecord, the following query works as expected
Scores.find([1, 2, 3, 4])
Depending on the MongoDB adapter you use, it may work as well. According to this documentation, the same syntax is also supported in Mongoid.
Otherwise, you can generally use
Scores.where(id: [1, 2, 3, 4])
that will return a collection of records matching the given IDs.

Resources