I have the following query:
view.reduce.group_level(5).keys
which returns:
[["1f9c79a33f399a7937d880c5f31e8dbc", 2011, 12, 29, 13], ["1f9c79a33f399a7937d880c5f31e8dbc", 2011, 12, 29, 14], ["c38332ffc275b6c70bcf06ffc39ddbdd", 2011, 12, 29, 13], ["c38332ffc275b6c70bcf06ffc39ddbdd", 2011, 12, 29, 14]]
The first key is an id and the other keys are year, month, day, hour
I would like all the rows between 2010 and 2013. So I want to ignore the first key.
The problem is that i need to set the first parameter to get the results but i want to get all the results for all the keys.
for example: view.reduce.group_level(5).startkey(["every_possible_key", 2010]).endkey(['every_possible_key", 2013, {}])
If i leave the first key blank than i get nothing. If i give it "\u9999" than i get everything and it ignores the 2nd key.
Somebody knows what I am doing wrong?
Thanks a lot.
map:
function(d) {
if (d['type'] == 'State' && d['driver_id'] && d['name'] && d['created_at']) {
var dt = new Date(d.created_at);
emit([d.driver_id, dt.getFullYear(), dt.getMonth() + 1, dt.getDate(), dt.getHours()], d.name);
}
}
reduce:
function(k,v,r) {
var result = {
'hire': 0, 'hired': 0, 'arrived': 0, 'pick up': 0, 'drop off': 0,
'missed': 0, 'rider cancel': 0, 'driver cancel': 0, 'no show': 0,
'avail': 0, 'unavail': 0, 'other': 0
};
if (r) {
var row = null;
for (i in v) {
row = v[i];
for (j in row) {
result[j] += row[j];
}
}
} else {
for (i in v) {
if (result[v[i]] != null) {
result[v[i]] += 1;
} else {
result['other'] += 1;
}
}
}
return result;
}
What you're "doing wrong" is to use a key you don't need in your query as the first key of your view.
If you need it for another query, create another view.
Related
In Python, you can specify a "step" argument to a list slice that specifies the separation between indices that are selected to be in the slice:
my_list[start:stop:step]
However, none of the list methods in Dart seem to offer this functionality: sublist and getRange just take the start and end index.
How can I do this in Dart without using an ugly for-loop?
For example, to select only the even indices of a list I currently see no alternative to this:
List<Object> myList = ...;
List<Object> slice = [];
for (var i = 0; i < myList.length; i += 2) {
slice.add(myList[i]);
}
Or slightly less ugly with a list comprehension:
[for (var i = 0; i < myList.length; i += 2) myList[i]]
I could write my own function or extension method, but that defeats the purpose, I'm looking for ideally a built-in or a third package solution.
For this you can create extension on list to return custom result.
List<T> slice([int? start, int? end, int? step]) {
if (start == null && end == null && step == null) {
return this!;
} else if (start != null && end == null && step == null) {
return this!.sublist(start);
} else if (start != null && end != null && step == null) {
return this!.sublist(start, end);
} else if (start != null && end != null && step != null) {
// iterate over the list and return the list
// iterator start from start index
// iterator end at end index
// iterator step by step
final list = <T>[];
for (var i = start; i < end; i += step) {
list.add(this![i]);
}
return list;
} else {
return this!;
}
}
You can use the slice extension on any list. Below are examples of how to use it.
Example 1
This example will return the slice list of the list depending starting and ending index.
final list1 = [1, 2, 3, 4, 5];
final result = list1.slice(1, 4);
print(result); // [2, 3, 4]
Example 2
This example will return the slice list of the list depending starting index.
final list1 = [1, 2, 3, 4, 5];
final result = list1.slice(1);
print(result); // [2, 3, 4, 5]
Complate program.
You can run this example in Dartpad to check results.
void main() {
final list1 = [1, 2, 3, 4, 5,6,7,8,9,10,11,12,13,14,15,15,17,18,19,20];
// Example - 1
final result = list1.slice(1, 4);
print(result); // [2, 3, 4]
//Example - 2
final result2 = list1.slice(10);
print(result2); // [11, 12, 13, 14, 15, 15, 17, 18, 19, 20]
//Example - 3
final result4 = list1.slice(4, 10, 2);
print(result4); // [5, 7, 9]
//Example - 4
final result3 = list1.slice();
print(result3); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 17, 18, 19, 20]
}
extension ListHelper<T> on List<T>? {
List<T> slice([int? start, int? end, int? step]) {
if (start == null && end == null && step == null) {
return this!;
} else if (start != null && end == null && step == null) {
return this!.sublist(start);
} else if (start != null && end != null && step == null) {
return this!.sublist(start, end);
} else if (start != null && end != null && step != null) {
// iterate over the list and return the list
// iterator start from start index
// iterator end at end index
// iterator step by step
final list = <T>[];
for (var i = start; i < end; i += step) {
list.add(this![i]);
}
return list;
} else {
return this!;
}
}
}
You can easily create your own slice method in Dart.
The first thing to decide is whether you want it to be lazy or eager—does it create a list or an iterable.
The traditional Dart way would be an iterable, created from another iterable, which is also slightly more complicated to write.
extension LazySlice<T> on Iterable<T> {
/// A sub-sequence ("slice") of the elements of this iterable.
///
/// The elements of this iterable starting at the [start]th
/// element, and ending before the [end]th element, or sooner
/// if this iterable has fewer than [end] elements.
/// If [end] is omitted, the sequence continues
/// to the end of this iterable.
/// If [step] is provided, only each [step]th element of the
/// [start]..[end] range is included, starting with the first,
/// and skipping `step - 1` elements after each that is included.
Iterable<T> slice([int start = 0, int? end, int step = 1]) {
// Check inputs.
RangeError.checkNotNegative(start, "start");
if (end != null && end < start) {
throw RangeError.range(end, start, null, "end");
}
if (step < 1) {
throw RangeError.range(step, 1, null, "step");
}
// Then return an iterable.
var iterable = this;
if (end != null) iterable = iterable.take(end);
if (start > 0) iterable = iterable.skip(start);
if (step != 1) iterable = iterable.step(step);
return iterable;
} // slice
/// Every [step] element.
///
/// The first element of this iterable, and then every
/// [step]th element after that (skipping `step - 1`
/// elements of this iterable between each element of
/// the returned iterable).
Iterable<T> step(int step) {
if (step == 1) return this;
if (step < 1) {
throw RangeError.range(step, 1, null, "step");
}
return _step(step);
}
/// [step] without parameter checking.
Iterable<T> _step(int step) sync* {
var it = iterator;
if (!it.moveNext()) return;
while (true) {
yield it.current;
for (var i = 0; i < step; i++) {
if (!it.moveNext()) return;
}
}
} // _step
} // extension LazySLice
Working with a list is much easier:
extension EagerSlice<T> on List<T> {
List<T> slice([int start = 0, int? end, int step = 1]) {
if (step == 1) return sublist(start, end); // Checks parameters.
end = RangeError.checkValidRange(start, end, length);
if (step < 1) {
throw RangeError.range(step, 1, null, "step");
}
return <T>[for (var i = start; i < end; i += step) this[i]];
}
}
(Effectively the same approach proposed by #Anakhand in the comments above, just with better parameter checking.)
The list approach is easier, mainly because we don't already have a step method on iterables, which picks every nth element.
Is there a method we use to reach the desired number in an array given in dart language.. I can do this for binary ones, but I can't do it for a code that finds the sum of 3 or more elements
For example
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
this is the my code i have done until now
void main() {
var candidates = [10, 1, 2, 7, 6, 1, 5], target = 8;
var answer = [];
for (int i = 0; i < candidates.length; i++) {
for (int j = 0; j < candidates.length; j++) {
if (candidates[i] + candidates[j] == target && i != j && i < j) {
answer.add([candidates[i], candidates[j]]);
}
}
}
}
I am sure this can be done more efficient but since the solution is for some Leetcode assignment, I don't really want to spend too much time on optimizations.
I have tried added some comments in the code which explains my way of doing it:
void main() {
getSumLists([10, 1, 2, 7, 6, 1, 5], 8).forEach(print);
// [5, 1, 2]
// [1, 6, 1]
// [1, 7]
// [6, 2]
getSumLists([2, 5, 2, 1, 2], 5).forEach(print);
// [2, 1, 2]
// [5]
}
Iterable<List<int>> getSumLists(
List<int> candidates,
int target, {
List<int>? tempAnswer,
int sum = 0,
}) sync* {
// We cannot use default value in parameter since that makes list const
final tempAnswerNullChecked = tempAnswer ?? [];
if (sum == target) {
// We got a result we can return.
// OPTIMIZATION: If you know the returned list from each found result is not
// being used between found results, you can remove the `.toList()` part.
yield tempAnswerNullChecked.toList();
} else if (sum > target) {
// No need to search further in this branch since we are over the target
return;
}
// Make a copy so we don't destroy the input list but also so it works even
// if provided list as input is non-growing / non-modifiable
final newCandidates = candidates.toList();
while (newCandidates.isNotEmpty) {
// We take numbers from the end of the list since that is more efficient.
final number = newCandidates.removeLast();
// Recursive call where we return all results we are going to find given
// the new parameters
yield* getSumLists(
newCandidates,
target,
tempAnswer: tempAnswerNullChecked..add(number),
sum: sum + number,
);
// Instead of creating a new tempAnswerNullChecked, we just reuse it and
// make sure we remove any value we are temporary adding
tempAnswerNullChecked.removeLast();
// Ensure we don't get duplicate combinations. So if we have checked the
// number `1` we remove all `1` so we don't try the second `1`.
newCandidates.removeWhere((element) => element == number);
}
}
I have a trouble inserting new rows and tables into an already existing one.
Lets call the source SourceFile.lua and its simplified contents:
SourceFile = {};
SourceFile.list = {
BrandName1 = {
number = 10,
products = {
"Product1", 3,
"Product2", 4,
"Product3", 7,
},
},
BrandName2 = {
number = 5,
products = {
"Product1", 10,
"Product2", 3,
"Product3", 6,
},
},
-- and so on
}
I want to do something like this:
require 'SourceFile'
local myData = {
BrandName2 = { -- add new products for the existing brand
products = {
"Product4", 2,
},
},
MyBrandName1 = { -- add new brand
number = 12,
products = {
"MyProduct1", 21,
"MyProduct2", 95,
},
},
-- and so on
}
table.insert(SourceFile.list, myData)
However there's something wrong in my code and I get the following result (printed with inspect):
{
list = { {
BrandName2 = {
products = { "Product4", 2 }
},
MyBrandName1 = {
number = 12,
products = { "MyProduct1", 21, "MyProduct2", 95 }
}
},
BrandName1 = {
number = 10,
products = { "Product1", 3, "Product2", 4, "Product3", 7 }
},
BrandName2 = {
number = 5,
products = { "Product1", 10, "Product2", 3, "Product3", 6 }
}
}
}
What am I doing wrong?
I'm new to lua and pretty sure that it's something obvious, but not for me. Please, help me.
Addition
After these answers I've also found a way to insert new brand names one by one:
SourceFile.list.MyBrandName1 = {
number = 12,
products = {
"MyProduct1", 21,
"MyProduct2", 95,
},
}
This does not fully answer my question, but might be useful to someone new to lua.
table.insert adds its second argument to an array (its first argument). Your SourceFile.list is only supposed to have string keys, so it can't work as an array. You'll need a recursive function to merge the data from one table into the other:
local function meld(data, newData)
for k, v in pairs(newData) do
local oldValue = data[k]
if type(oldValue) ~= 'table' or type(v) ~= 'table' then
-- One of the values is not a table, so let's clobber the old value.
data[k] = v
else
-- Both are tables.
meld(oldValue, v)
end
end
end
meld(SourceFile.list, myData)
You are pushing a table of brandnames into a list of brandnames.
Which makes it a list of brandnames + table with brandnames.
table.insert(SourceFile.list, myData)
This inserts myData to SourceFile.list. myData is a table with brandnames.
SourceFile.list is also a table with brandnames.
List in list.
You have 2 choices to solve this:
Insert each brandname separately
Make a function to merge contents of myData to SourceFile.list
first thing first my question is very similar to this one. In fact, it's the same thing, except that I need to group every user like this below:
Everyone under 12 (exclusive)
Then, from 12 - 19
Then, from 20 - 29
...
More than 80 (inclusive)
Based on the answer from dasblinkenlight in the other question, I was able to do:
var ageStats = vModel
.GroupBy(l => 10 * (l.Age / 10))
.OrderBy(x => x.Key)
.Select(g => new
{
Name = g.Key,
Count = g.Select(l => l.Age).Count()
}).ToList();
For a result set of :
0-9
10-19
20-29
...
So what should I do to accomplish the pattern I have to ?
Thank you very much !!
var ages = new[] { 12, 19, 29, 80 };
var grouped = ages.Select(r => new {
Name = r,
Count = vModel.Count(x => x.Age >= r)
});
try this, but i don't know the performance
var ages = new int[12, 19, 29, 80];
var func = new Func<int, int>(a=>{
for(var i = 0; i<ages.Length; i++){
if(a<ages[i])
continue;
return i;
}
return 0;
});
vModel.GroupBy(m=>func(m.Age))....
You could use approach mentioned here and use this code:
var ages = new List<int> { 12, 19, 29, 39, 49, 59, 69, 80, int.MaxValue};
var categories = vModel.GroupBy(item => ages.FirstOrDefault(ceil => ceil >= item));
I have run in to issue that days that have to be disabled are shifted to the next day.
The idea is that day that does not exist in our booking object or have a value less than 1 should be disabled on calendar.
here is simplified version of my script and demonstration on jsfiddle:
var bookings = {
"2012-09-01": 24,
"2012-09-03": 31,
"2012-09-05": 27,
"2012-09-06": 9,
"2012-09-07": 18,
"2012-09-08": 0,
"2012-09-10": 20,
"2012-09-12": 19,
"2012-09-13": 0,
"2012-09-14": 9,
"2012-09-15": 24,
"2012-09-17": 19,
"2012-09-19": 28,
"2012-09-20": 15,
"2012-09-21": 12,
"2012-09-22": 25,
"2012-09-24": 19,
"2012-09-26": 0,
"2012-09-27": 0,
"2012-09-28": 0,
"2012-09-29": 0
};
function MyEvent(date)
{
bookings = bookings || {};
this.date = date.toISOString().substr(0, 10);
this.display = (typeof bookings[this.date] == 'number' && bookings[this.date] > 0);
return this;
}
MyEvent.prototype.toArray = function () {
return [this.display, null, null];
};
$(function ()
{
$('#eventCalendar').datepicker({
dateFormat: "yy-mm-dd",
firstDay: 1,
defaultDate: "2012-09-24",
beforeShowDay: function (date)
{
return new MyEvent(date).toArray();
}
}
);
});
Can some one suggest me what am I doing wrong or is it a bug?
It was a little struggle, but is not a bug.
There is a problem using:
date.toISOString()
the operation can return a different date (for example next day) from the original date passed from the plug in, because the function ignores timezone offsets
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString
so your condition will not work well.
Here is a working fiddle the is not using that function: http://jsfiddle.net/nBejK/2/