-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunderscore3.py
2175 lines (1809 loc) · 64.2 KB
/
underscore3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import inspect
try:
import idc
import idautils
import idaapi
# from sftools import get_ea_by_any
except ImportError:
pass
from types import *
import re
import functools
import random
import time
from threading import Timer
from collections import Sequence
import six
from six.moves import builtins
def oget(obj, key, default=None, call=False):
"""Get attribute or dictionary value of object
Parameters
----------
obj : object
container with optional dict-like properties
key : str
key
default : any
value to return on failure
call : bool
call attr if callable
Returns
-------
any
similar to obj[key] or getattr(obj, key)
See Also
--------
dotted : creates `path` from dotted string
deep_get : uses `oget` to traverse deeply nested objects
Examples
--------
>>> oget(sys.modules, '__main__')
<module '__main__' (built-in)>
>>> oget(sys.modules['__main__'], 'oget')
<function oget at 0x000001A9A1920378>
"""
if not isinstance(key, str):
raise TypeError("oget(): attribute ('{}') name must be string".format(key))
r = None
if isinstance(obj, dict):
return obj.get(key, default)
try:
r = obj[key] if key in obj else getattr(obj, key, default)
except TypeError:
# TypeError: 'module' object is not subscriptable
r = getattr(obj, key, default)
if call and callable(r):
r = r()
return r
# https://stackoverflow.com/questions/42095393/python-map-a-function-over-recursive-iterables
def _recursive_map(seq, func):
for item in seq:
if isinstance(item, Sequence):
yield type(item)(_recursive_map(item, func))
else:
yield func(item)
def _recursive_obj_map(seq, func):
for key, item in _.items(seq):
if isinstance(item, Sequence):
yield key, type(item)(_recursive_map(item, func))
elif isinstance(item, Collection):
yield key, type(item)(_recursive_map(item, func))
else:
yield func(item)
def _recursive_obj_map_wrapper(seq, func):
return type(seq)(next(_recursive_obj_map(seq, func)))
def _makeSequenceMapper(f):
def fmap(seq, iteratee):
return _recursive_map(seq, iteratee)
def function(item):
if str(type(item)) == "<class 'generator'>":
return [f(x) for x in item]
if isinstance(item, Sequence):
return type(item)(fmap(item, f))
return [f(item)]
return function
# An iterable object is an object that implements __iter__, which is expected
# to return an iterator object.
def _isIterable(o):
return hasattr(o, '__iter__') and not hasattr(o, 'ljust')
__asList = _makeSequenceMapper(lambda x: x)
def _asList(o):
l = []
if _isIterable(o):
l = [x for x in o]
else:
l = __asList(o)
if not isinstance(l, list) or len(l) == 1 and l[0] == o:
return [o]
return l
def Array(o):
if o is None:
return []
elif isinstance(o, list):
return o
else:
return list([o])
def _us_xrefs_to(ea, types=None):
if types is None:
types = [ idc.fl_CF,
idc.fl_CN,
idc.fl_JF,
idc.fl_JN,
# idc.fl_F
]
return [x.frm for x in idautils.XrefsTo(ea)]
class _IdCounter(object):
""" Array Global Dictionary for uniq IDs
"""
count = 0
pass
class __(object):
"""
Use this class to alter __repr__ of
underscore object. So when you are using
it on your project it will make sense
"""
def __init__(self, repr, func):
self._repr = repr
self._func = func
functools.update_wrapper(self, func)
def __call__(self, *args, **kw):
return self._func(*args, **kw)
def __repr__(self):
return self._repr(self._func)
def u_withrepr(reprfun):
""" Decorator to rename a function
"""
def _wrap(func):
return __(reprfun, func)
return _wrap
@u_withrepr(lambda x: "<Underscore Object>")
def _(obj):
"""
_ function, which creates an instance of the underscore object,
We will also assign all methods of the underscore class as a method
to this function so that it will be usable as a static object
"""
return underscore(obj)
class underscore(object):
fns = dict()
"""
Instead of creating a class named _ (underscore) I created underscore
So I can use _ function both statically and dynamically just as it
is in the original underscore
"""
_object = None
""" Passed object
"""
VERSION = "0.1.6"
chained = False
""" If the object is in a chained state or not
"""
Null = "__Null__"
"""
Since we are working with the native types
I can't compare anything with None, so I use a Substitute type for checking
"""
_wrapped = Null
"""
When object is in chained state, This property will contain the latest
processed Value of passed object, I assign it no Null so I can check
against None results
"""
def __init__(self, obj):
""" Let there be light
"""
self.chained = False
self._object = obj
class Namespace(object):
""" For simulating full closure support
"""
pass
self.Namespace = Namespace
def __str__(self):
if self.chained is True:
return "Underscore chained instance"
else:
return "Underscore instance"
def __repr__(self):
if self.chained is True:
return "<Underscore chained instance>"
else:
return "<Underscore instance>"
@property
def obj(self):
"""
Returns passed object but if chain method is used
returns the last processed result
"""
if self._wrapped is not self.Null:
return self._wrapped
else:
return self._object
@obj.setter
def obj(self, value):
""" New style classes requires setters for @propert methods
"""
self._object = value
return self._object
def _wrap(self, ret):
"""
Returns result but ig chain method is used
returns the object itself so we can chain
"""
if self.chained:
self._wrapped = ret
return self
else:
return ret
@property
def _clean(self):
"""
creates a new instance for Internal use to prevent problems
caused by chaining
"""
return _(self.obj)
def _toOriginal(self, val):
""" Pitty attempt to convert itertools result into a real object
"""
if self._clean.isTuple():
return tuple(val)
elif self._clean.isList():
return list(val)
elif self._clean.isDict():
return dict(val)
else:
return val
def _oget(self, obj, key, default=None, call=False):
return oget(obj, key, default=default, call=call)
"""Get attribute or dictionary value of object
Parameters
----------
obj : object
container with optional dict-like properties
key : str
key
default : any
value to return on failure
call : bool
call attr if callable
Returns
-------
any
similar to obj[key] or getattr(obj, key)
See Also
--------
dotted : creates `path` from dotted string
deep_get : uses `oget` to traverse deeply nested objects
Examples
--------
>>> oget(sys.modules, '__main__')
<module '__main__' (built-in)>
>>> oget(sys.modules['__main__'], 'oget')
<function oget at 0x000001A9A1920378>
"""
if not isString(key):
raise TypeError("oget(): attribute ('{}') name must be string".format(key))
r = None
try:
r = obj[key] if key in obj else default
except TypeError:
# TypeError: 'module' object is not subscriptable
r = getattr(obj, key, default)
if call and callable(r):
r = r()
return r
"""
Collection Functions
"""
def items(self):
"""
generator: iterates through each item of an dict or list,
using index for a key if not a dict. same as:
enumerate(list) or dict.items()
"""
if self.hasCallable('items'):
for key, value in self._clean.obj.items():
yield key, value
else:
for key, value in enumerate(self._clean.obj):
yield key, value
def each(self, func):
"""
iterates through each item of an object
:Param: func iterator function
underscore.js:
Iterates over a list of elements, yielding each in turn to an iteratee
function. The iteratee is bound to the context object, if one is
passed. Each invocation of iteratee is called with three arguments:
(element, index, list).
If list is a JavaScript object, iteratee's arguments will be (value,
key, list). Returns the list for chaining.
"""
if callable(getattr(self._clean.obj, 'items', None)):
for key, value in self.obj.items():
r = func(value, key, self.obj)
if r == "breaker":
break
else:
for index, value in enumerate(self.obj):
r = func(value, index, self.obj)
if r == "breaker":
break
return self._wrap(self)
forEach = each
def mapObject(self, func):
""" Return the results of applying the iterator to each element.
"""
newlist = {}
for k, v in self._clean.items():
# if k not in values: # use indexof to check identity
k2, v2 = func(v, k, self.obj)
newlist[k2] = v2
return self._wrap(newlist)
def map(self, func=None):
""" Return the results of applying the iterator to each element.
"""
if func is None:
func = lambda x, *a: x
ns = self.Namespace()
ns.results = []
def by(value, index, list, *args):
ns.results.append(func(value, index, list))
_(self.obj).each(by)
return self._wrap(ns.results)
collect = map
def reduce(self, func, memo=None):
"""
**Reduce** builds up a single result from a list of values,
aka `inject`, or foldl
"""
if memo is None:
memo = []
ns = self.Namespace()
ns.initial = True # arguments.length > 2
ns.memo = memo
obj = self.obj
def by(value, index, *args):
if not ns.initial:
ns.memo = value
ns.initial = True
else:
ns.memo = func(ns.memo, value, index)
_(obj).each(by)
return self._wrap(ns.memo)
foldl = inject = reduce
def reduceRight(self, func):
""" The right-associative version of reduce, also known as `foldr`.
"""
#foldr = lambda f, i: lambda s: reduce(f, s, i)
x = self.obj[:]
x.reverse()
return self._wrap(functools.reduce(func, x))
foldr = reduceRight
def find(self, func):
"""
Return the first value which passes a truth test.
Aliased as `detect`.
"""
self.ftmp = None
def test(value, index, list):
if func(value, index, list) is True:
self.ftmp = value
return True
self._clean.any(test)
return self._wrap(self.ftmp)
detect = find
def findKey(self, predicate):
keys = self._clean.keys()
for key in keys:
if predicate(self.obj[key], key, self.obj):
return self._wrap(key)
def filterObject(self, func):
""" Return all the items that pass a truth test
"""
if self._clean.isDictlike():
# https://stackoverflow.com/questions/2844516/how-to-filter-a-dictionary-according-to-an-arbitrary-condition-function
# method a: {k: v for k, v in r.items() if not v['data'].startswith('False')};
# method b: dict((k, v) for k, v in r.items() if not v['data'].startswith('False'))
return self._wrap(type(self.obj)((k, v) for k, v in self.items() if func(v, k, self._clean.obj)))
return self._wrap(type(self.obj)(v for k, v in self.items() if func(v, k, self._clean.obj)))
def filter(self, func):
""" Return all the elements that pass a truth test.
"""
return self._wrap(list(filter(func, self.obj)))
select = filter
def remove(self, func):
"""
Removes all elements from array that predicate returns truthy for
and returns an array of the removed elements. The predicate is invoked
with three arguments: (value, index, array).
"""
ns = self.Namespace()
ns.remove = []
ns.result = []
obj = self.obj
def by(value, index, list):
if func(value, index, list):
ns.remove.append(index)
ns.result.append(value)
_(obj).each(by)
ns.remove.reverse()
for index in ns.remove:
try:
self.obj.pop(index)
except ValueError:
print("{} is not in {}".format(index, self.obj))
return self._wrap(ns.result)
def without(self, *values):
"""
Return a version of the array that does not contain the specified
value(s), or object that doesn't contain the specified key(s)
"""
if self._clean.isDict():
newlist = {}
for i, k in enumerate(self.obj):
# if k not in values: # use indexof to check identity
if _(values).indexOf(k) == -1:
newlist[k] = self.obj[k]
else:
newlist = []
for i, v in enumerate(self.obj):
# if v not in values: # use indexof to check identity
if _(values).indexOf(v) == -1:
newlist.append(v)
return self._wrap(newlist)
def only(self, *values):
"""
Return a version of the array that only contains the specified
value(s), or object that only contains the specified key(s)
"""
if self._clean.isDictlike():
newlist = {}
for i, k in enumerate(self.obj):
# if k not in values: # use indexof to check identity
if _(values).indexOf(k) != -1:
newlist[k] = self.obj[k]
else:
newlist = []
for i, v in enumerate(self.obj):
# if v not in values: # use indexof to check identity
if _(values).indexOf(v) != -1:
newlist.append(v)
return self._wrap(newlist)
def reject(self, func):
""" Return all the elements for which a truth test fails.
"""
return self._wrap(list(filter(lambda val: not func(val), self.obj)))
def all(self, func=None):
""" Determine whether all of the elements match a truth test.
"""
if func is None:
func = lambda x, *args: x
self.altmp = True
def testEach(value, index, *args):
if func(value, index, *args) is False:
self.altmp = False
self._clean.each(testEach)
return self._wrap(self.altmp)
every = all
def same(self):
"""
Determine if all of the elements hold the same value. Returns False
if there are no elements.
"""
if not self._clean.obj or not len(self._clean.obj):
return False
_first = _.first(self._clean.obj)
return self.all(lambda x, *a: x == _first)
def any(self, func=None):
"""
Determine if at least one element in the object
matches a truth test.
"""
if func is None:
func = lambda x, *args: x
self.antmp = False
def testEach(value, index, *args):
if func(value, index, *args):
self.antmp = True
return "breaker"
self._clean.each(testEach)
return self._wrap(self.antmp)
some = any
def include(self, target):
"""
Determine if a given value(s) is included in the
array or object using `is`.
"""
target = _asList(target)
if self._clean.isDict():
return self._wrap(_.any(target, lambda x, *a: x in self.obj.values()))
else:
return self._wrap(_.any(target, lambda x, *a: x in self.obj))
contains = include
def invoke(self, method, *args):
""" Invoke a method (with arguments) on every item in a collection.
"""
def inv(value, *ar):
if (
_(method).isFunction() or
_(method).isLambda() or
_(method).isMethod()
):
return method(value, *args)
else:
return getattr(value, method)(*args)
return self._wrap(self._clean.map(inv))
def pluck(self, key):
"""
Convenience version of a common use case of
`map`: fetching a property.
"""
# allow pluck to operate on numeric indexes to quickly
# grab items from tuples and lists
if _.isInt(key):
return list(list(zip(*self.obj))[key])
if _.isList(key) or _.isTuple(key) and len(key) == 2:
r1 = []
for x in self.obj:
r2 = []
for _key in key:
r2.append(self._oget(x, _key, call=1))
r1.append(tuple(r2))
return(r1)
return self._wrap([self._oget(x, key, call=1) for x in self.obj])
def re_findall(self, pattern, flags=0):
"""
Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result.
"""
results = []
for ob in Array(self.obj):
results.extend(re.findall(pattern, ob))
return self._wrap(results)
# _([idc.get_screen_ea()]).chain().
# code_refs_to().
# func_start().
# code_refs_to().
# map(lambda x, *y: GetFunctionName(x)).filter(lambda x, *y: x.startswith('sub_')).
# invoke(lambda x, *y: LabelAddressPlus(LocByName( x ), 'allocsub_%s' % x[4:]))
def ida_code_refs_to(self):
return self._wrap(self._flatten(_(asList(self.obj)).map(lambda x, *y: asList(idautils.CodeRefsTo(x, 0))), shallow=True))
def ida_func_start(self):
return self._wrap(self._flatten(_(asList(self.obj)).map(lambda x, *y: GetFuncStart(x)), shallow=True))
def ida_decompile(self):
return self._wrap([str(idaapi.decompile(get_ea_by_any(e), hf=None, flags=idaapi.DECOMP_WARNINGS)) for e in self.obj])
def ida_xrefs_to(self):
return self._wrap([_us_xrefs_to(get_ea_by_any(e)) for e in self.obj])
def ida_all_xrefs_from(self):
def iter(x):
if x[2] == 'fl_CN':
return x[0]
return None
return self._wrap(_.uniq(_.filter(self._flatten(self.obj + [all_xrefs_from(get_ea_by_any(e), iteratee=iter) for e in self.obj]), lambda x, *a: x)))
def where(self, attrs=None, first=False):
"""
Convenience version of a common use case of `filter`:
selecting only objects
containing specific `key:value` pairs.
"""
if attrs is None:
return None if first is True else []
method = _.find if first else _.filter
def by(val, *args):
for key, value in attrs.items():
try:
if attrs[key] != val[key]:
return False
except KeyError:
return False
return True
return self._wrap(method(self.obj, by))
def findWhere(self, attrs=None):
"""
Convenience version of a common use case of `find`:
getting the first object
containing specific `key:value` pairs.
"""
return self._wrap(self._clean.where(attrs, True))
def max(self):
""" Return the maximum element or (element-based computation).
"""
if(self._clean.isDict()):
return self._wrap(list())
return self._wrap(max(self.obj))
def maxBy(self, key):
""" Return the maximum element or (element-based computation).
"""
if(self._clean.isDict()):
return self._wrap(list())
return self._wrap(max(self.obj, key=key))
def min(self):
""" Return the minimum element (or element-based computation).
"""
if(self._clean.isDict()):
return self._wrap(list())
return self._wrap(min(self.obj))
def minBy(self, key):
""" Return the minimum element or (element-based computation).
"""
if(self._clean.isDict()):
return self._wrap(list())
return self._wrap(min(self.obj, key=key))
def shuffle(self):
""" Shuffle an array.
"""
if(self._clean.isDict()):
return self._wrap(list())
cloned = self.obj[:]
random.shuffle(cloned)
return self._wrap(cloned)
def reverse(self):
cloned = self.obj[:]
cloned.reverse()
return self._wrap(cloned)
def sort(self, val=None):
""" Sort the object's values by a criterion produced by an iterator.
"""
if val is not None:
return self._wrap(sorted(self.obj, cmp=val))
else:
return self._wrap(sorted(self.obj))
def sortBy(self, val=None):
"""
Sort the object's values by a criterion produced by an iterator or
attribute name.
"""
# def get(obj, key):
# if callable(getattr(obj, 'get', None)):
# return obj.get(key)
# return getattr(obj, key)
if val is not None:
if _(val).isString():
return self._wrap(sorted(self.obj, key=lambda x,
*args: _.get(x, val)))
else:
return self._wrap(sorted(self.obj, key=val))
else:
return self._wrap(sorted(self.obj))
def sortObjectBy(self, val=None, reverse=None):
""" Sort the object's values by a criterion produced by an iterator.
"""
keys = _.sortBy(self.obj, val)
if reverse:
keys.reverse()
o = {}
for k in keys:
o[k] = self.obj[k]
return self._wrap(o)
def _lookupIterator(self, val):
""" An internal function to generate lookup iterators.
"""
if val is None:
return lambda el, *args: el
return val if _.isCallable(val) else lambda obj, *args: obj[val]
def _group(self, obj, val, behavior):
""" An internal function used for aggregate "group by" operations.
"""
ns = self.Namespace()
ns.result = {}
iterator = self._lookupIterator(val)
def e(value, index, *args):
key = iterator(value, index)
behavior(ns.result, key, value)
_.each(obj, e)
if False:
if len(ns.result) == 1:
try:
return ns.result[0]
except KeyError:
return list(ns.result.values())[0]
return ns.result
def groupBy(self, val):
"""
Groups the object's values by a criterion. Pass either a string
attribute to group by, or a function that returns the criterion.
"""
def by(result, key, value):
if key not in result:
result[key] = []
result[key].append(value)
res = self._group(self.obj, val, by)
return self._wrap(res)
def grouper(self, n, fillvalue=None):
"""
https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks/312644#312644
> grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')
"""
# from itertools import zip_longest # for Python 3.x
from six.moves import zip_longest # for both (uses the six compat library)
return zip_longest(*[iter(self.obj)]*n, fillvalue=fillvalue)
def indexBy(self, val=None):
"""
Indexes the object's values by a criterion, similar to
`groupBy`, but for when you know that your index values will be unique.
"""
if val is None:
val = lambda *args: args[0]
def by(result, key, value):
result[key] = value
res = self._group(self.obj, val, by)
return self._wrap(res)
def countBy(self, val):
"""
Counts instances of an object that group by a certain criterion. Pass
either a string attribute to count by, or a function that returns the
criterion.
"""
def by(result, key, value):
if key not in result:
result[key] = 0
result[key] += 1
res = self._group(self.obj, val, by)
return self._wrap(res)
def sortedIndex(self, obj, iterator=lambda x: x):
"""
Use a comparator function to figure out the smallest index at which
an object should be inserted so as to maintain order.
Uses binary search.
"""
array = self.obj
value = iterator(obj)
low = 0
high = len(array)
while low < high:
mid = (low + high) >> 1
if iterator(array[mid]) < value:
low = mid + 1
else:
high = mid
return self._wrap(low)
def toArray(self):
""" Safely convert anything iterable into a real, live array.
"""
return self._wrap(list(self.obj))
def size(self):
""" Return the number of elements in an object.
"""
return self._wrap(len(self.obj))
def first(self, n=1):
"""
Get the first element of an array. Passing **n** will return the
first N values in the array. Aliased as `head` and `take`.
The **guard** check allows it to work with `_.map`.
"""
keys = _.keys(self.obj)[0:n]
res = [self.obj[x] for x in keys]
if len(res) == 1:
res = res[0]
# keys = getattr(self.obj, 'keys', None)
# res = []
# for i, v in enumerate(self.obj):
# if i >= n:
# break
# res.append(v)
return self._wrap(res)
head = take = first
def initial(self, n=1):
"""
Returns everything but the last entry of the array.
Especially useful on the arguments object.
Passing **n** will return all the values in the array, excluding the
last N. The **guard** check allows it to work with `_.map`.
"""
return self._wrap(self.obj[0:-n])
def last(self, n=1):
"""
Get the last element of an array. Passing **n** will return the last N
values in the array.
The **guard** check allows it to work with `_.map`.
"""
res = self.obj[-n:]
if len(res) == 1:
res = res[0]
return self._wrap(res)
def rest(self, n=1):
"""
Returns everything but the first entry of the array. Aliased as `tail`.
Especially useful on the arguments object.
Passing an **index** will return the rest of the values in the
array from that index onward.
The **guard** check allows it to work with `_.map`.
"""
return self._wrap(self.obj[n:])
tail = rest
def compact(self):
""" Trim out all falsy values from an array.
"""
return self._wrap(self._clean.filter(lambda x: x))
def _flatten(self, input, shallow=False, output=None):
ns = self.Namespace()
ns.output = output
if ns.output is None:
ns.output = []
def by(value, *args):
if _.isList(value) or _.isTuple(value):
if shallow:
ns.output = ns.output + value
else:
self._flatten(value, shallow, ns.output)
else:
ns.output.append(value)
_.each(input, by)
return ns.output
def flatten(self, shallow=None):
""" Return a completely flattened version of an array.
"""
return self._wrap(self._flatten(self.obj, shallow))
def partition(self, predicate=None):
"""
Split an array into two arrays: one whose elements all satisfy the given
predicate, and one whose elements all do not satisfy the predicate.
"""