Compare two arrays in Ruby and create a third array of elements - mysql

I have two arrays, array1 and array2. I need to compare both of these arrays and I want to create a third array, array3, whereby it shows the elements that are in array2, that are not in array1.
This is what I have so far:
my_buckets = Model.select("DISTINCT bucket").where(["my_id = ?", params[:user]])
all_buckets = Model.select("DISTINCT bucket").collect { |x| x.bucket }.uniq.compact
buckets_not_in_my_buckets = Model.select("DISTINCT bucket").where(["bucket NOT IN (?)", my_buckets]).collect { |x| x.bucket }.uniq.compact
For some reason, the buckets_not_in_my_buckets is always returning an empty array ([]). Is there a better way to approach this? Any help would be appreciated.

buckets_not_in_my_buckets = all_buckets - my_buckets
I'm assuming that you have the eql? operator on your buckets object working how you'd like.
Please see the Array docs for more detail.

Related

extract rows and columns from dictionary of JSON responses consisting of lists of dictionaries in python

sorry for the confusing title.
So im trying to read a butload of JSON responses using grequests with this loop:
def GetData():
urlRespDict = {}
for OrderNo in LookupNumbers['id']:
urls1 = []
for idno in ParameterList:
urlTemp = url0_const + OrderNo + url1_const + idno + param1_const
urls1.append(urlTemp)
urlRespDict[OrderNo] = grequests.map((grequests.get(u) for u in urls1))
return urlRespDict
Which is all fine and dandy, my response is a dictionary of 4 keys with consisting of a lists with sizes 136.
When i read one of the responses with (key and index are random):
d1 = dict_responses['180378'][0].json()
I get a list of dictionaries that has a dictionary inside see picture below.
Basically all i want to get out is the value from the 'values' key where in this case is '137' and
'13,80137' ideally i want to create a df that has columns with the 'key' (in this case the '137') and rows with the values extracted from d1.
I've tried using apply(pd.Series) on the values dict. But it is very time consuming.
like:
df2 = [(pd.DataFrame.from_records(n))['values'].apply(pd.Series,dtype="string") for n in df1]
just to see the data.
I hope theres another alternative, i am not an experienced coder
I hope i explained it good enough and i hope you can help. Thank you so much in advance

Why does encoding an array into json format result in an json object?

This is strange, I've used json encoding arrays and the output is something like [{" etc, but in another code this time the output is "{"1":{".. causing multiple errors. I don't understand what is going on.
this is the part of the code:
$json_arr = json_decode($json_str, true);
$fecha = date("Y-m-d H:i:s");
foreach (array_column($json_arr, 'f') AS $k => $fecha) {
if($fecha < $ahora){
unset($json_arr[$k]);
}
}
$json_str = json_encode($json_arr,true);//this will be inserted in the DB table
but the $json_str is in the form of "{"1":{".. but I need in the form of [{".
Here some of the images when debugging:
in orange, the json_str is readed from the BD table
after decoding, you see the json_arr is an array of three elements
after deleting some row, you see json_arr is still an array
after encoding the json_arr, I get the "{"1":{" format, in other cases of encoding arrays I had the [{" format, which is what I need.
You are starting with an array of 3 arrays, with the indices of 0, 1, and 2.
Then you are deleting the first one. If you compare your 2nd and 3rd screenshots, specifically the popup portion, you'll see that what you have lost is index 0. Your array now starts with index 1.
But in JavaScript, an array can't start with index 1. It has to start with index 0, so PHP is encoding it as an object, instead of an array.
If you use the PHP function array_values() it will re-index your array and you should be good to go.

How to check if JSON response fields are alphabetically sorted?

How to validate the JSON Response fields? After validating the fields I need to check whether the fields are alphabetically sorted or not. How would I do it ?
The JSON object is unordered set of name/value pairs. There is no guarangee of ordering at all. You need to take json object keys list and sort them. After sorting access to object fields by sorted keys list.
If you mean how to check list (array) of values. You need to implement simple loop through array and check that each element must be less than next element in sorting comparision criteria.
For js language checking array for alpha ordering may be done like this:
var array = ["Apple", "Application", "AppName", "Happy"];
var isSortedAlpha = array.reduce(function(res, current, index, arr) {
return res && arr[index&&index-1] <= current
}, true);

List json processing

I have difficulty processing a list a Scala:
Currently I have a list of like this
(List(JString(2437), JString(2445), JString(2428), JString(321)), CompactBuffer((4,1)))
and I would like after processing, the result will look like below:
( (2437, CompactBuffer((4,1))), (2445, CompactBuffer((4,1))), (2428, CompactBuffer((4,1))), (321, CompactBuffer((4,1))) )
Can any body help me with this issue?
Thank you very much.
Try this:
val pair = (List(JString(2437), JString(2445), JString(2428), JString(321)),
CompactBuffer((4,1)))
val result = pair._1.map((_, pair._2))
First, pair._1 gets the list from the tuple. Then, map performs the function on each element of the list. The function (_, pair._2) puts the given element from the list in a new tuple together with the second part of the pair tuple.

SortOn an m-array of objects

Alright, so I have an m-array (Or an array of arrays in actionscript as it doesn't really have m-arrays) and each array in the superarray has a number of objects created at different times in it. I want to sort the superarray by in descending order of the value of the "time" paramater of the object at index 0 in each subarray.
I've tried
superarray.sortOn([0].time, Array.DESCENDING);
and
superarray.sortOn("0.time", Array.DESCENDING);
but this doesn't seem to work. Any suggestions? Will I just have to write my own sort function to do this? If so what's the best way to go about it?
Try using the Array.sort function passing a compare function. Something like this:
var superarray:Array = [
[{time:900}, {time:715}, {time:655}],
[{time:450}, {time:333}, {time:100}],
[{time:999}, {time:75}, {time:30}]
];
var sorted:Array = superarray.sort( function(A:Array,B:Array):int {
return ObjectUtil.numericCompare(A[0].time, B[0].time);
});