code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
splits = yield asyncGetSplits(_INPUT, conf['RULE'], **kwargs) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) _OUTPUT = yield asyncStarMap(asyncParseResult, parsed) returnValue(iter(_OUTPUT))
def asyncPipeStrreplace(context=None, _INPUT=None, conf=None, **kwargs)
A string module that asynchronously replaces text. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'RULE': [ { 'param': {'value': <match type: 1=first, 2=last, 3=every>}, 'find': {'value': <text to find>}, 'replace': {'value': <replacement>} } ] } Returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of replaced strings
15.303635
15.658498
0.977337
splits = get_splits(_INPUT, conf['RULE'], **kwargs) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
def pipe_strreplace(context=None, _INPUT=None, conf=None, **kwargs)
A string module that replaces text. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'RULE': [ { 'param': {'value': <match type: 1=first, 2=last, 3=every>}, 'find': {'value': <text to find>}, 'replace': {'value': <replacement>} } ] } Returns ------- _OUTPUT : generator of replaced strings
13.26754
12.360447
1.073387
_input = yield _INPUT asyncFuncs = yield asyncGetSplits(None, conf, **cdicts(opts, kwargs)) pieces = yield asyncFuncs[0]() _pass = yield asyncFuncs[2]() if _pass: _OUTPUT = _input else: start = int(pieces.start) stop = start + int(pieces.count) _OUTPUT = islice(_input, start, stop) returnValue(_OUTPUT)
def asyncPipeUniq(context=None, _INPUT=None, conf=None, **kwargs)
An operator that asynchronously returns a specified number of items from the top of a feed. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items conf : { 'start': {'type': 'number', value': <starting location>} 'count': {'type': 'number', value': <desired feed length>} } returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of unique items
9.292661
10.250425
0.906563
funcs = get_splits(None, conf, **cdicts(opts, kwargs)) pieces, _pass = funcs[0](), funcs[2]() if _pass: _OUTPUT = _INPUT else: try: start = int(pieces.start) except AttributeError: start = 0 stop = start + int(pieces.count) _OUTPUT = islice(_INPUT, start, stop) return _OUTPUT
def pipe_truncate(context=None, _INPUT=None, conf=None, **kwargs)
An operator that returns a specified number of items from the top of a feed. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) kwargs -- terminal, if the truncation value is wired in conf : { 'start': {'type': 'number', value': <starting location>} 'count': {'type': 'number', value': <desired feed length>} } Returns ------- _OUTPUT : generator of items
7.538857
7.68222
0.981338
conf['delimiter'] = conf.pop('to-str', dict.get(conf, 'delimiter')) splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) items = yield asyncStarMap(partial(maybeDeferred, parse_result), parsed) _OUTPUT = utils.multiplex(items) returnValue(_OUTPUT)
def asyncPipeStringtokenizer(context=None, _INPUT=None, conf=None, **kwargs)
A string module that asynchronously splits a string into tokens delimited by separators. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'to-str': {'value': <delimiter>}, 'dedupe': {'type': 'bool', value': <1>}, 'sort': {'type': 'bool', value': <1>} } Returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of items
13.99322
13.925429
1.004868
offline = conf.get('offline', {}).get('value') # TODO add async rate data fetching rate_data = get_offline_rate_data() if offline else get_rate_data() rates = parse_request(rate_data) splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) _OUTPUT = starmap(partial(parse_result, rates=rates), parsed) returnValue(iter(_OUTPUT))
def asyncPipeExchangerate(context=None, _INPUT=None, conf=None, **kwargs)
A string module that asynchronously retrieves the current exchange rate for a given currency pair. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings (base currency) conf : { 'quote': {'value': <'USD'>}, 'default': {'value': <'USD'>}, 'offline': {'type': 'bool', 'value': '0'}, } Returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of hashed strings
10.076847
10.138783
0.993891
offline = conf.get('offline', {}).get('value') rate_data = get_offline_rate_data(err=False) if offline else get_rate_data() rates = parse_request(rate_data) splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(partial(parse_result, rates=rates), parsed) return _OUTPUT
def pipe_exchangerate(context=None, _INPUT=None, conf=None, **kwargs)
A string module that retrieves the current exchange rate for a given currency pair. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings (base currency) conf : { 'quote': {'value': <'USD'>}, 'default': {'value': <'USD'>}, 'offline': {'type': 'bool', 'value': '0'}, } Returns ------- _OUTPUT : generator of hashed strings
9.370102
9.549529
0.981211
splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
def pipe_strtransform(context=None, _INPUT=None, conf=None, **kwargs)
A string module that splits a string into tokens delimited by separators. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : {'transformation': {value': <'swapcase'>}} Returns ------- _OUTPUT : generator of tokenized strings
16.513052
18.60117
0.887743
value = utils.get_input(context, conf) while True: yield value
def pipe_privateinput(context=None, _INPUT=None, conf=None, **kwargs)
An input that prompts the user for some text and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : unused conf : { 'name': {'value': 'parameter name'}, 'prompt': {'value': 'User prompt'}, 'default': {'value': 'default value'}, 'debug': {'value': 'debug value'} } Yields ------ _OUTPUT : text
13.204105
14.662534
0.900534
conf = DotDict(conf) loop_with = kwargs.pop('with', None) date_format = conf.get('format', **kwargs) # timezone = conf.get('timezone', **kwargs) for item in _INPUT: _with = item.get(loop_with, **kwargs) if loop_with else item try: # todo: check that all PHP formats are covered by Python date_string = time.strftime(date_format, _with) except TypeError as e: if context and context.verbose: print 'Error formatting date: %s' % item print e continue else: yield date_string
def pipe_dateformat(context=None, _INPUT=None, conf=None, **kwargs)
Formats a datetime value. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipedatebuilder pipe like object (iterable of date timetuples) conf : { 'format': {'value': <'%B %d, %Y'>}, 'timezone': {'value': <'EST'>} } Yields ------ _OUTPUT : formatted dates
5.473547
5.645518
0.969539
path = DotDict(conf).get('path', **kwargs) for item in _INPUT: element = DotDict(item).get(path, **kwargs) for i in utils.gen_items(element): yield {'content': i} if item.get('forever'): # _INPUT is pipeforever and not a loop, # so we just yield our item once break
def pipe_subelement(context=None, _INPUT=None, conf=None, **kwargs)
An operator extracts select sub-elements from a feed. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : {'path': {'value': <element path>}} Yields ------ _OUTPUT : items
12.51466
12.811807
0.976807
conf = DotDict(conf) urls = utils.listize(conf['URL']) for item in _INPUT: for item_url in urls: url = utils.get_value(DotDict(item_url), DotDict(item), **kwargs) url = utils.get_abspath(url) if context and context.verbose: print "pipe_feedautodiscovery loading:", url for entry in autorss.getRSSLink(url.encode('utf-8')): yield {'link': entry} # todo: add rel, type, title if item.get('forever'): # _INPUT is pipeforever and not a loop, # so we just yield our item once break
def pipe_feedautodiscovery(context=None, _INPUT=None, conf=None, **kwargs)
A source that searches for and returns feed links found in a page. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : URL -- url Yields ------ _OUTPUT : items
10.300124
10.248328
1.005054
value = utils.get_input(context, conf) value = utils.url_quote(value) while True: yield value
def pipe_urlinput(context=None, _INPUT=None, conf=None, **kwargs)
An input that prompts the user for a url and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : unused conf : { 'name': {'value': 'parameter name'}, 'prompt': {'value': 'User prompt'}, 'default': {'value': 'default value'}, 'debug': {'value': 'debug value'} } Yields ------ _OUTPUT : url
8.535097
8.791811
0.970801
# todo: get from a config/env file url = "http://query.yahooapis.com/v1/public/yql" conf = DotDict(conf) query = conf['yqlquery'] for item in _INPUT: item = DotDict(item) yql = utils.get_value(query, item, **kwargs) # note: we use the default format of xml since json loses some # structure # todo: diagnostics=true e.g. if context.test # todo: consider paging for large result sets r = requests.get(url, params={'q': yql}, stream=True) # Parse the response tree = parse(r.raw) if context and context.verbose: print "pipe_yql loading xml:", yql root = tree.getroot() # note: query also has row count results = root.find('results') # Convert xml into generation of dicts for element in results.getchildren(): yield utils.etree_to_dict(element) if item.get('forever'): # _INPUT is pipeforever and not a loop, # so we just yield our item once break
def pipe_yql(context=None, _INPUT=None, conf=None, **kwargs)
A source that issues YQL queries. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : yqlquery -- YQL query # todo: handle envURL Yields ------ _OUTPUT : query results
8.740616
8.717748
1.002623
value = utils.get_input(context, conf) try: value = int(value) except: value = 0 while True: yield value
def pipe_numberinput(context=None, _INPUT=None, conf=None, **kwargs)
An input that prompts the user for a number and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : not used conf : { 'name': {'value': 'parameter name'}, 'prompt': {'value': 'User prompt'}, 'default': {'value': 'default value'}, 'debug': {'value': 'debug value'} } Yields ------ _OUTPUT : text
4.484286
5.837646
0.768167
pkwargs = cdicts(opts, kwargs) get_params = get_funcs(conf.get('PARAM', []), **kwargs)[0] get_paths = get_funcs(conf.get('PATH', []), **pkwargs)[0] get_base = get_funcs(conf['BASE'], listize=False, **pkwargs)[0] parse_params = utils.parse_params splits = get_splits(_INPUT, funcs=[get_params, get_paths, get_base]) parsed = utils.dispatch(splits, *get_dispatch_funcs('pass', parse_params)) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
def pipe_urlbuilder(context=None, _INPUT=None, conf=None, **kwargs)
A url module that builds a url. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : { 'PARAM': [ {'key': {'value': <'order'>}, 'value': {'value': <'desc'>}}, {'key': {'value': <'page'>}, 'value': {'value': <'2'>}} ] 'PATH': {'type': 'text', 'value': <''>}, 'BASE': {'type': 'text', 'value': <'http://site.com/feed.xml'>}, } Yields ------ _OUTPUT : url
7.08032
6.610292
1.071105
conf = DotDict(conf) conf_sep = conf['separator'] conf_mode = conf['col_mode'] col_name = conf['col_name'] for item in _INPUT: item = DotDict(item) url = utils.get_value(conf['URL'], item, **kwargs) url = utils.get_abspath(url) separator = utils.get_value(conf_sep, item, encode=True, **kwargs) skip = int(utils.get_value(conf['skip'], item, **kwargs)) col_mode = utils.get_value(conf_mode, item, **kwargs) f = urlopen(url) if context and context.verbose: print "pipe_csv loading:", url for i in xrange(skip): f.next() reader = csv.UnicodeReader(f, delimiter=separator) fieldnames = [] if col_mode == 'custom': fieldnames = [DotDict(x).get() for x in col_name] else: fieldnames = _gen_fieldnames(conf, reader, item, **kwargs) for rows in reader: yield dict(zip(fieldnames, rows)) f.close() if item.get('forever'): # _INPUT is pipeforever and not a loop, # so we just yield our item once break
def pipe_csv(context=None, _INPUT=None, conf=None, **kwargs)
A source that fetches and parses a csv file to yield items. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : URL -- url skip -- number of header rows to skip col_mode -- column name source: row=header row(s), custom=defined in col_name col_name -- list of custom column names col_row_start -- first column header row col_row_end -- last column header row separator -- column separator Yields ------ _OUTPUT : items Note: Current restrictions: separator must be 1 character assumes every row has exactly the expected number of fields, as defined in the header
4.420496
4.026083
1.097964
splits = yield asyncGetSplits(_INPUT, conf['RULE'], **cdicts(opts, kwargs)) _OUTPUT = yield maybeDeferred(parse_results, splits, **kwargs) returnValue(_OUTPUT)
def asyncPipeRename(context=None, _INPUT=None, conf=None, **kwargs)
An operator that asynchronously renames or copies fields in the input source. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : asyncPipe like object (twisted Deferred iterable of items) conf : { 'RULE': [ { 'op': {'value': 'rename or copy'}, 'field': {'value': 'old field'}, 'newval': {'value': 'new field'} } ] } kwargs : other inputs, e.g., to feed terminals for rule values Returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of items
23.572712
24.227474
0.972974
splits = get_splits(_INPUT, conf['RULE'], **cdicts(opts, kwargs)) _OUTPUT = parse_results(splits, **kwargs) return _OUTPUT
def pipe_rename(context=None, _INPUT=None, conf=None, **kwargs)
An operator that renames or copies fields in the input source. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : { 'RULE': [ { 'op': {'value': 'rename or copy'}, 'field': {'value': 'old field'}, 'newval': {'value': 'new field'} } ] } kwargs : other inputs, e.g., to feed terminals for rule values Returns ------- _OUTPUT : generator of items
20.029902
17.943232
1.116293
for item in reversed(list(_INPUT)): yield item
def pipe_reverse(context=None, _INPUT=None, conf=None, **kwargs)
An operator that reverses the order of source items. Not loopable. Not lazy. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : unused Yields ------ _OUTPUT : items
8.812396
11.388156
0.773821
count = len(list(_INPUT)) # todo: check all operators (not placeable in loops) while True: yield count
def pipe_count(context=None, _INPUT=None, conf=None, **kwargs)
An operator that counts the number of _INPUT items and yields it forever. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : not used Yields ------ _OUTPUT : number of items in the feed Examples -------- >>> generator = (x for x in xrange(5)) >>> count = pipe_count(_INPUT=generator) >>> count #doctest: +ELLIPSIS <generator object pipe_count at 0x...> >>> count.next() 5
29.912802
29.445593
1.015867
conf['start'] = conf.pop('from', dict.get(conf, 'start')) splits = yield asyncGetSplits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = yield asyncDispatch(splits, *get_async_dispatch_funcs()) _OUTPUT = yield asyncStarMap(partial(maybeDeferred, parse_result), parsed) returnValue(iter(_OUTPUT))
def asyncPipeSubstr(context=None, _INPUT=None, conf=None, **kwargs)
A string module that asynchronously returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} } returns ------- _OUTPUT : twisted.internet.defer.Deferred generator of substrings
13.441789
15.579649
0.862779
conf['start'] = conf.pop('from', dict.get(conf, 'start')) splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs)) parsed = utils.dispatch(splits, *get_dispatch_funcs()) _OUTPUT = starmap(parse_result, parsed) return _OUTPUT
def pipe_substr(context=None, _INPUT=None, conf=None, **kwargs)
A string module that returns a substring. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : { 'from': {'type': 'number', value': <starting position>}, 'length': {'type': 'number', 'value': <count of characters to return>} } Returns ------- _OUTPUT : generator of substrings
13.005397
13.8803
0.936968
ret = b'' if fmt == SER_BINARY: while x: x, r = divmod(x, 256) ret = six.int2byte(int(r)) + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, b'\0') return ret assert fmt == SER_COMPACT while x: x, r = divmod(x, len(COMPACT_DIGITS)) ret = COMPACT_DIGITS[r:r + 1] + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, COMPACT_DIGITS[0:1]) return ret
def serialize_number(x, fmt=SER_BINARY, outlen=None)
Serializes `x' to a string of length `outlen' in format `fmt'
1.993438
1.97468
1.009499
ret = gmpy.mpz(0) if fmt == SER_BINARY: if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") for c in s: ret *= 256 ret += byte2int(c) return ret assert fmt == SER_COMPACT if isinstance(s, six.text_type): s = s.encode('ascii') for c in s: ret *= len(COMPACT_DIGITS) ret += R_COMPACT_DIGITS[c] return ret
def deserialize_number(s, fmt=SER_BINARY)
Deserializes a number from a string `s' in format `fmt'
4.234901
4.260514
0.993988
if not a: return True p1 = p // 2 p2 = pow(a, p1, p) return p2 == 1
def mod_issquare(a, p)
Returns whether `a' is a square modulo p
4.143887
4.106461
1.009114
if a == 0: return 0 if not mod_issquare(a, p): raise ValueError n = 2 while mod_issquare(n, p): n += 1 q = p - 1 r = 0 while not q.getbit(r): r += 1 q = q >> r y = pow(n, q, p) h = q >> 1 b = pow(a, h, p) x = (a * b) % p b = (b * x) % p while b != 1: h = (b * b) % p m = 1 while h != 1: h = (h * h) % p m += 1 h = gmpy.mpz(0) h = h.setbit(r - m - 1) t = pow(y, h, p) y = (t * t) % p r = m x = (x * t) % p b = (b * y) % p return x
def mod_root(a, p)
Return a root of `a' modulo p
3.028806
3.01774
1.003667
curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk, pk_format) return p.encrypt(s, mac_bytes)
def encrypt(s, pk, pk_format=SER_COMPACT, mac_bytes=10, curve=None)
Encrypts `s' for public key `pk'
4.118964
4.076684
1.010371
curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.decrypt(s, mac_bytes)
def decrypt(s, passphrase, curve='secp160r1', mac_bytes=10)
Decrypts `s' with passphrase `passphrase'
3.294237
3.115738
1.057289
close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file, 'rb') close_in = True if stringlike(out_path_or_file): out_file = open(out_path_or_file, 'wb') close_out = True _encrypt_file(in_file, out_file, pk, pk_format, mac_bytes, chunk_size, curve) finally: if close_out: out_file.close() if close_in: in_file.close()
def encrypt_file(in_path_or_file, out_path_or_file, pk, pk_format=SER_COMPACT, mac_bytes=10, chunk_size=4096, curve=None)
Encrypts `in_file' to `out_file' for pubkey `pk'
1.603554
1.619594
0.990096
close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file, 'rb') close_in = True if stringlike(out_path_or_file): out_file = open(out_path_or_file, 'wb') close_out = True _decrypt_file(in_file, out_file, passphrase, curve, mac_bytes, chunk_size) finally: if close_out: out_file.close() if close_in: in_file.close()
def decrypt_file(in_path_or_file, out_path_or_file, passphrase, curve='secp160r1', mac_bytes=10, chunk_size=4096)
Decrypts `in_file' to `out_file' with passphrase `passphrase'
1.609418
1.626138
0.989718
if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk, pk_format) return p.verify(hashlib.sha512(s).digest(), sig, sig_format)
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT, curve=None)
Verifies that `sig' is a signature of pubkey `pk' for the message `s'.
5.026433
5.109766
0.983691
if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.sign(hashlib.sha512(s).digest(), sig_format)
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1')
Signs `s' with passphrase `passphrase'
4.934387
4.914984
1.003948
if randfunc is None: randfunc = Crypto.Random.new().read curve = Curve.by_name(curve) raw_privkey = randfunc(curve.order_len_bin) privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT) pubkey = str(passphrase_to_pubkey(privkey)) return (privkey, pubkey)
def generate_keypair(curve='secp160r1', randfunc=None)
Convenience function to generate a random new keypair (passphrase, pubkey).
4.608019
4.840561
0.95196
s = deserialize_number(sig, sig_fmt) return self.p._ECDSA_verify(h, s)
def verify(self, h, sig, sig_fmt=SER_BINARY)
Verifies that `sig' is a signature for a message with SHA-512 hash `h'.
10.46898
9.947296
1.052445
ctx = EncryptionContext(f, self.p, mac_bytes) yield ctx ctx.finish()
def encrypt_to(self, f, mac_bytes=10)
Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'.
11.237281
10.785588
1.041879
if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") out = BytesIO() with self.encrypt_to(out, mac_bytes) as f: f.write(s) return out.getvalue()
def encrypt(self, s, mac_bytes=10)
Encrypt `s' for this pubkey.
5.436167
5.140712
1.057474
ctx = DecryptionContext(self.curve, f, self, mac_bytes) yield ctx ctx.read()
def decrypt_from(self, f, mac_bytes=10)
Decrypts a message from f.
10.458449
11.840301
0.883293
outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT else self.curve.sig_len_bin) sig = self._ECDSA_sign(h) return serialize_number(sig, sig_format, outlen)
def sign(self, h, sig_format=SER_BINARY)
Signs the message with SHA-512 hash `h' with this private key.
5.302438
5.041009
1.051861
ctr = Crypto.Util.Counter.new(128, initial_value=0) cipher = Crypto.Cipher.AES.new(h, Crypto.Cipher.AES.MODE_CTR, counter=ctr) buf = cipher.encrypt(b'\0' * self.order_len_bin) return self._buf_to_exponent(buf)
def hash_to_exponent(self, h)
Converts a 32 byte hash to an exponent
4.556983
4.251001
1.071979
parser = argparse.ArgumentParser(description='The DomainTools CLI API Client') parser.add_argument('-u', '--username', dest='user', default='', help='API Username') parser.add_argument('-k', '--key', dest='key', default='', help='API Key') parser.add_argument('-c', '--credfile', dest='credentials', default=os.path.expanduser('~/.dtapi'), help='Optional file with API username and API key, one per line.') parser.add_argument('-l', '--rate-limit', dest='rate_limit', action='store_true', default=False, help='Rate limit API calls against the API based on per minute limits.') parser.add_argument('-f', '--format', dest='format', choices=['list', 'json', 'xml', 'html'], default='json') parser.add_argument('-o', '--outfile', dest='out_file', type=argparse.FileType('wbU'), default=sys.stdout, help='Output file (defaults to stdout)') parser.add_argument('-v', '--version', action='version', version='DomainTools CLI API Client {0}'.format(version)) parser.add_argument('--no-https', dest='https', action='store_false', default=True, help='Use HTTP instead of HTTPS.') parser.add_argument('--no-verify-ssl', dest='verify_ssl', action='store_false', default=True, help='Skip verification of SSL certificate when making HTTPs API calls') subparsers = parser.add_subparsers(help='The name of the API call you wish to perform (`whois` for example)', dest='api_call') subparsers.required = True for api_call in API_CALLS: api_method = getattr(API, api_call) subparser = subparsers.add_parser(api_call, help=api_method.__name__) spec = inspect.getargspec(api_method) for argument_name, default in reversed(list(zip_longest(reversed(spec.args or []), reversed(spec.defaults or []), fillvalue='EMPTY'))): if argument_name == 'self': continue elif default == 'EMPTY': subparser.add_argument(argument_name) else: subparser.add_argument('--{0}'.format(argument_name.replace('_', '-')), dest=argument_name, default=default, nargs='*') arguments = vars(parser.parse_args(args) if args else parser.parse_args()) if not arguments.get('user', None) or not arguments.get('key', None): try: with open(arguments.pop('credentials')) as credentials: arguments['user'], arguments['key'] = credentials.readline().strip(), credentials.readline().strip() except Exception: pass for key, value in arguments.items(): if value in ('-', ['-']): arguments[key] == (line.strip() for line in sys.stdin.readlines()) elif value == []: arguments[key] = True elif type(value) == list and len(value) == 1: arguments[key] = value[0] return (arguments.pop('out_file'), arguments.pop('format'), arguments)
def parse(args=None)
Defines how to parse CLI arguments for the DomainTools API
2.486953
2.411372
1.031344
sys.stderr.write('Credentials are required to perform API calls.\n') sys.exit(1) api = API(user, key, https=arguments.pop('https'), verify_ssl=arguments.pop('verify_ssl'), rate_limit=arguments.pop('rate_limit')) response = getattr(api, arguments.pop('api_call'))(**arguments) output = str(getattr(response, out_format) if out_format != 'list' else response.as_list()) out_file.write(output if output.endswith('\n') else output + '\n')
def run(): # pragma: no cover out_file, out_format, arguments = parse() user, key = arguments.pop('user', None), arguments.pop('key', None) if not user or not key
Defines how to start the CLI for the DomainTools API
4.086063
3.69053
1.107175
login_url = kwargs.pop('login_url', settings.LOGIN_URL) redirect_field_name = kwargs.pop('redirect_field_name', REDIRECT_FIELD_NAME) redirect_to_login = kwargs.pop('redirect_to_login', True) def decorate(view_func): def decorated(request, *args, **kwargs): if request.user.is_authenticated(): params = [] for lookup_variable in lookup_variables: if isinstance(lookup_variable, string_types): value = kwargs.get(lookup_variable, None) if value is None: continue params.append(value) elif isinstance(lookup_variable, (tuple, list)): model, lookup, varname = lookup_variable value = kwargs.get(varname, None) if value is None: continue if isinstance(model, string_types): model_class = apps.get_model(*model.split(".")) else: model_class = model if model_class is None: raise ValueError( "The given argument '%s' is not a valid model." % model) if (inspect.isclass(model_class) and not issubclass(model_class, Model)): raise ValueError( 'The argument %s needs to be a model.' % model) obj = get_object_or_404(model_class, **{lookup: value}) params.append(obj) check = get_check(request.user, perm) granted = False if check is not None: granted = check(*params) if granted or request.user.has_perm(perm): return view_func(request, *args, **kwargs) if redirect_to_login: path = urlquote(request.get_full_path()) tup = login_url, redirect_field_name, path return HttpResponseRedirect('%s?%s=%s' % tup) return permission_denied(request) return wraps(view_func)(decorated) return decorate
def permission_required(perm, *lookup_variables, **kwargs)
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary.
1.992293
1.996948
0.997669
kwargs['redirect_to_login'] = False return permission_required(perm, *args, **kwargs)
def permission_required_or_403(perm, *args, **kwargs)
Decorator that wraps the permission_required decorator and returns a permission denied (403) page instead of redirecting to the login URL.
4.621486
4.640318
0.995942
return PermissionsForObjectNode.handle_token(parser, token, approved=True, name='"permissions"')
def get_permissions(parser, token)
Retrieves all permissions associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permissions obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permissions obj as "my_permissions" %} {% get_permissions obj for request.user as "my_permissions" %}
20.030876
49.505268
0.404621
return PermissionsForObjectNode.handle_token(parser, token, approved=False, name='"permission_requests"')
def get_permission_requests(parser, token)
Retrieves all permissions requests associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permission_requests obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permission_requests obj as "my_permissions" %} {% get_permission_requests obj for request.user as "my_permissions" %}
15.985905
35.705959
0.44771
return PermissionForObjectNode.handle_token(parser, token, approved=True, name='"permission"')
def get_permission(parser, token)
Performs a permission check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission "poll_permission.change_poll" for request.user and poll as "is_allowed" %} {% get_permission "poll_permission.change_poll" for request.user and poll,second_poll as "is_allowed" %} {% if is_allowed %} I've got ze power to change ze pollllllzzz. Muahahaa. {% else %} Meh. No power for meeeee. {% endif %}
17.220686
54.660404
0.315049
return PermissionForObjectNode.handle_token( parser, token, approved=False, name='"permission_request"')
def get_permission_request(parser, token)
Performs a permission request check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission_request "poll_permission.change_poll" for request.user and poll as "asked_for_permissio" %} {% get_permission_request "poll_permission.change_poll" for request.user and poll,second_poll as "asked_for_permissio" %} {% if asked_for_permissio %} Dude, you already asked for permission! {% else %} Oh, please fill out this 20 page form and sign here. {% endif %}
13.586755
33.48201
0.405793
user = context['request'].user if user.is_authenticated(): if (user.has_perm('authority.delete_foreign_permissions') or user.pk == perm.creator.pk): return base_link(context, perm, 'authority-delete-permission') return {'url': None}
def permission_delete_link(context, perm)
Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions.
5.587586
5.165943
1.08162
user = context['request'].user if user.is_authenticated(): link_kwargs = base_link(context, perm, 'authority-delete-permission-request') if user.has_perm('authority.delete_permission'): link_kwargs['is_requestor'] = False return link_kwargs if not perm.approved and perm.user == user: link_kwargs['is_requestor'] = True return link_kwargs return {'url': None}
def permission_request_delete_link(context, perm)
Renders a html link to the delete view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions.
4.670935
4.617736
1.01152
user = context['request'].user if user.is_authenticated(): if user.has_perm('authority.approve_permission_requests'): return base_link(context, perm, 'authority-approve-permission-request') return {'url': None}
def permission_request_approve_link(context, perm)
Renders a html link to the approve view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions.
4.918925
4.959754
0.991768
if var is None: return var if var[0] in ('"', "'") and var[-1] == var[0]: return var[1:-1] else: return template.Variable(var).resolve(context)
def resolve(self, var, context)
Resolves a variable out of context if it's not in quotes
2.826693
2.38121
1.187082
return self.get_for_model(obj).select_related( 'user', 'group', 'creator').filter(group=group, codename=perm, approved=approved)
def group_permissions(self, group, perm, obj, approved=True)
Get objects that have Group perm permission on
6.003654
6.476279
0.927022
user_perms = self.user_permissions(user, perm, obj, check_groups=False) if not user_perms.filter(object_id=obj.id): return perms = self.user_permissions(user, perm, obj).filter(object_id=obj.id) perms.delete()
def delete_user_permissions(self, user, perm, obj, check_groups=False)
Remove granular permission perm from user on an object instance
2.63099
2.678565
0.982238
parsed = self['parsed_whois'] flat = OrderedDict() for key in ('domain', 'created_date', 'updated_date', 'expired_date', 'statuses', 'name_servers'): value = parsed[key] flat[key] = ' | '.join(value) if type(value) in (list, tuple) else value registrar = parsed.get('registrar', {}) for key in ('name', 'abuse_contact_phone', 'abuse_contact_email', 'iana_id', 'url', 'whois_server'): flat['registrar_{0}'.format(key)] = registrar[key] for contact_type in ('registrant', 'admin', 'tech', 'billing'): contact = parsed.get('contacts', {}).get(contact_type, {}) for key in ('name', 'email', 'org', 'street', 'city', 'state', 'postal', 'country', 'phone', 'fax'): value = contact[key] flat['{0}_{1}'.format(contact_type, key)] = ' '.join(value) if type(value) in (list, tuple) else value return flat
def flattened(self)
Returns a flattened version of the parsed whois data
2.657484
2.440865
1.088747
if template_name is None: template_name = ('403.html', 'authority/403.html') context = { 'request_path': request.path, } if extra_context: context.update(extra_context) return HttpResponseForbidden(loader.render_to_string( template_name=template_name, context=context, request=request, ))
def permission_denied(request, template_name=None, extra_context=None)
Default 403 handler. Templates: `403.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/')
2.162158
2.324774
0.930051
self.approved = True self.creator = creator self.save()
def approve(self, creator)
Approve granular permission request setting a Permission entry as approved=True for a specific action from an user on an object instance.
4.407917
4.531353
0.97276
import imp from django.conf import settings for app in settings.INSTALLED_APPS: try: __import__(app) app_path = sys.modules[app].__path__ except AttributeError: continue try: imp.find_module('permissions', app_path) except ImportError: continue __import__("%s.permissions" % app) app_path = sys.modules["%s.permissions" % app] LOADING = False
def autodiscover_modules()
Goes and imports the permissions submodule of every app in INSTALLED_APPS to make sure the permission set classes are registered correctly.
2.703971
2.567912
1.052984
if not self.user: return {}, {} group_pks = set(self.user.groups.values_list( 'pk', flat=True, )) perms = Permission.objects.filter( Q(user__pk=self.user.pk) | Q(group__pk__in=group_pks), ) user_permissions = {} group_permissions = {} for perm in perms: if perm.user_id == self.user.pk: user_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True # If the user has the permission do for something, but perm.user != # self.user then by definition that permission came from the # group. else: group_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True return user_permissions, group_permissions
def _get_user_cached_perms(self)
Set up both the user and group caches.
2.935623
2.795118
1.050268
if not self.group: return {} perms = Permission.objects.filter( group=self.group, ) group_permissions = {} for perm in perms: group_permissions[( perm.object_id, perm.content_type_id, perm.codename, perm.approved, )] = True return group_permissions
def _get_group_cached_perms(self)
Set group cache.
3.154974
2.969315
1.062526
perm_cache, group_perm_cache = self._get_user_cached_perms() self.user._authority_perm_cache = perm_cache self.user._authority_group_perm_cache = group_perm_cache self.user._authority_perm_cache_filled = True
def _prime_user_perm_caches(self)
Prime both the user and group caches and put them on the ``self.user``. In addition add a cache filled flag on ``self.user``.
3.262973
2.477539
1.317022
perm_cache = self._get_group_cached_perms() self.group._authority_perm_cache = perm_cache self.group._authority_perm_cache_filled = True
def _prime_group_perm_caches(self)
Prime the group cache and put them on the ``self.group``. In addition add a cache filled flag on ``self.group``.
6.080556
3.796058
1.601808
# Check to see if the cache has been primed. if not self.user: return {} cache_filled = getattr( self.user, '_authority_perm_cache_filled', False, ) if cache_filled: # Don't really like the name for this, but this matches how Django # does it. return self.user._authority_perm_cache # Prime the cache. self._prime_user_perm_caches() return self.user._authority_perm_cache
def _user_perm_cache(self)
cached_permissions will generate the cache in a lazy fashion.
5.000915
4.507305
1.109513
# Check to see if the cache has been primed. if not self.group: return {} cache_filled = getattr( self.group, '_authority_perm_cache_filled', False, ) if cache_filled: # Don't really like the name for this, but this matches how Django # does it. return self.group._authority_perm_cache # Prime the cache. self._prime_group_perm_caches() return self.group._authority_perm_cache
def _group_perm_cache(self)
cached_permissions will generate the cache in a lazy fashion.
5.107403
4.600014
1.110302
# Check to see if the cache has been primed. if not self.user: return {} cache_filled = getattr( self.user, '_authority_perm_cache_filled', False, ) if cache_filled: return self.user._authority_group_perm_cache # Prime the cache. self._prime_user_perm_caches() return self.user._authority_group_perm_cache
def _user_group_perm_cache(self)
cached_permissions will generate the cache in a lazy fashion.
3.940998
3.546483
1.111241
if self.user: self.user._authority_perm_cache_filled = False if self.group: self.group._authority_perm_cache_filled = False
def invalidate_permissions_cache(self)
In the event that the Permission table is changed during the use of a permission the Permission cache will need to be invalidated and regenerated. By calling this method the invalidation will occur, and the next time the cached_permissions is used the cache will be re-primed.
4.436833
4.763333
0.931456
if not self.group: return False if self.use_smart_cache: content_type_pk = Permission.objects.get_content_type(obj).pk def _group_has_perms(cached_perms): # Check to see if the permission is in the cache. return cached_perms.get(( obj.pk, content_type_pk, perm, approved, )) # Check to see if the permission is in the cache. return _group_has_perms(self._group_perm_cache) # Actually hit the DB, no smart cache used. return Permission.objects.group_permissions( self.group, perm, obj, approved, ).filter( object_id=obj.pk, ).exists()
def has_group_perms(self, perm, obj, approved)
Check if group has the permission for the given object
4.063348
4.046212
1.004235
if self.user: if self.has_user_perms(perm, obj, approved, check_groups): return True if self.group: return self.has_group_perms(perm, obj, approved) return False
def has_perm(self, perm, obj, check_groups=True, approved=True)
Check if user has the permission for the given object
2.665045
2.708359
0.984007
return self.has_perm(perm, obj, check_groups, False)
def requested_perm(self, perm, obj, check_groups=True)
Check if user requested a permission for the given object
4.802845
4.771919
1.006481
result = [] if not content_object: content_objects = (self.model,) elif not isinstance(content_object, (list, tuple)): content_objects = (content_object,) else: content_objects = content_object if not check: checks = self.generic_checks + getattr(self, 'checks', []) elif not isinstance(check, (list, tuple)): checks = (check,) else: checks = check for content_object in content_objects: # raise an exception before adding any permission # i think Django does not rollback by default if not isinstance(content_object, (Model, ModelBase)): raise NotAModel(content_object) elif isinstance(content_object, Model) and not content_object.pk: raise UnsavedModelInstance(content_object) content_type = ContentType.objects.get_for_model(content_object) for check in checks: if isinstance(content_object, Model): # make an authority per object permission codename = self.get_codename( check, content_object, generic, ) try: perm = Permission.objects.get( user=self.user, codename=codename, approved=True, content_type=content_type, object_id=content_object.pk, ) except Permission.DoesNotExist: perm = Permission.objects.create( user=self.user, content_object=content_object, codename=codename, approved=True, ) result.append(perm) elif isinstance(content_object, ModelBase): # make a Django permission codename = self.get_django_codename( check, content_object, generic, without_left=True, ) try: perm = DjangoPermission.objects.get(codename=codename) except DjangoPermission.DoesNotExist: name = check if '_' in name: name = name[0:name.find('_')] perm = DjangoPermission( name=name, codename=codename, content_type=content_type, ) perm.save() self.user.user_permissions.add(perm) result.append(perm) return result
def assign(self, check=None, content_object=None, generic=False)
Assign a permission to a user. To assign permission for all checks: let check=None. To assign permission for all objects: let content_object=None. If generic is True then "check" will be suffixed with _modelname.
2.409981
2.384049
1.010878
return '|'.join(items) if type(items) in (list, tuple, set) else items
def delimited(items, character='|')
Returns a character delimited version of the provided list as a Python string
4.591768
4.543694
1.01058
self.limits_set = True for product in self.account_information(): self.limits[product['id']] = {'interval': timedelta(seconds=60 / float(product['per_minute_limit']))}
def _rate_limit(self)
Pulls in and enforces the latest rate limits for the specified user
11.084034
9.250568
1.1982
if product != 'account-information' and self.rate_limit and not self.limits_set and not self.limits: self._rate_limit() uri = '/'.join(('{0}://api.domaintools.com'.format('https' if self.https else 'http'), path.lstrip('/'))) parameters = self.default_parameters.copy() parameters['api_username'] = self.username if self.https: parameters['api_key'] = self.key else: parameters['timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') parameters['signature'] = hmac(self.key.encode('utf8'), ''.join([self.username, parameters['timestamp'], path]).encode('utf8'), digestmod=sha1).hexdigest() parameters.update(dict((key, str(value).lower() if value in (True, False) else value) for key, value in kwargs.items() if value is not None)) return cls(self, product, uri, **parameters)
def _results(self, product, path, cls=Results, **kwargs)
Returns _results for the specified API path with the specified **kwargs parameters
3.733629
3.641837
1.025205
return self._results('mark-alert', '/v1/mark-alert', query=delimited(query), exclude=delimited(exclude), domain_status=domain_status, days_back=days_back, items_path=('alerts', ), **kwargs)
def brand_monitor(self, query, exclude=[], domain_status=None, days_back=None, **kwargs)
Pass in one or more terms as a list or separated by the pipe character ( | )
8.345089
7.933167
1.051924
return self._results('domain-search', '/v2/domain-search', query=delimited(query, ' '), exclude_query=delimited(exclude_query, ' '), max_length=max_length, min_length=min_length, has_hyphen=has_hyphen, has_number=has_number, active_only=active_only, deleted_only=deleted_only, anchor_left=anchor_left, anchor_right=anchor_right, page=page, items_path=('results', ), **kwargs)
def domain_search(self, query, exclude_query=[], max_length=25, min_length=2, has_hyphen=True, has_number=True, active_only=False, deleted_only=False, anchor_left=False, anchor_right=False, page=1, **kwargs)
Each term in the query string must be at least three characters long. Pass in a list or use spaces to separate multiple terms.
2.363158
2.347993
1.006459
return self._results('domain-suggestions', '/v1/domain-suggestions', query=delimited(query, ' '), items_path=('suggestions', ), **kwargs)
def domain_suggestions(self, query, **kwargs)
Passed in name must be at least two characters long. Use a list or spaces to separate multiple terms.
14.958274
14.633011
1.022228
return self._results('hosting-history', '/v1/{0}/hosting-history'.format(query), cls=GroupedIterable, **kwargs)
def hosting_history(self, query, **kwargs)
Returns the hosting history from the given domain name
15.300931
17.458099
0.876437
return self._results('ip-monitor', '/v1/ip-monitor', query=query, days_back=days_back, page=page, items_path=('alerts', ), **kwargs)
def ip_monitor(self, query, days_back=0, page=1, **kwargs)
Pass in the IP Address you wish to query ( i.e. 199.30.228.112 ).
6.70945
6.510137
1.030616
return self._results('ip-registrant-monitor', '/v1/ip-registrant-monitor', query=query, days_back=days_back, search_type=search_type, server=server, country=country, org=org, page=page, include_total_count=include_total_count, **kwargs)
def ip_registrant_monitor(self, query, days_back=0, search_type="all", server=None, country=None, org=None, page=1, include_total_count=False, **kwargs)
Query based on free text query terms
2.078388
2.076198
1.001055
return self._results('name-server-monitor', '/v1/name-server-monitor', query=query, days_back=days_back, page=page, items_path=('alerts', ), **kwargs)
def name_server_monitor(self, query, days_back=0, page=1, **kwargs)
Pass in the hostname of the Name Server you wish to query ( i.e. dynect.net ).
6.193737
5.890042
1.051561
return self._results('parsed-whois', '/v1/{0}/whois/parsed'.format(query), cls=ParsedWhois, **kwargs)
def parsed_whois(self, query, **kwargs)
Pass in a domain name
8.607859
8.744533
0.98437
return self._results('registrant-alert', '/v1/registrant-alert', query=delimited(query), exclude=delimited(exclude), days_back=days_back, limit=limit, items_path=('alerts', ), **kwargs)
def registrant_monitor(self, query, exclude=[], days_back=0, limit=None, **kwargs)
One or more terms as a Python list or separated by the pipe character ( | ).
7.684865
7.296769
1.053187
return self._results('reputation', '/v1/reputation', domain=query, include_reasons=include_reasons, cls=Reputation, **kwargs)
def reputation(self, query, include_reasons=False, **kwargs)
Pass in a domain name to see its reputation score
6.845622
5.473807
1.250614
return self._results('reverse-ip', '/v1/{0}/reverse-ip'.format(domain), limit=limit, **kwargs)
def reverse_ip(self, domain=None, limit=None, **kwargs)
Pass in a domain name.
6.018848
5.572904
1.08002
return self._results('reverse-ip', '/v1/{0}/host-domains'.format(ip), limit=limit, **kwargs)
def host_domains(self, ip=None, limit=None, **kwargs)
Pass in an IP address.
8.411223
7.769381
1.082612
if (ip and query) or not (ip or query): raise ValueError('Query or IP Address (but not both) must be defined') return self._results('reverse-ip-whois', '/v1/reverse-ip-whois', query=query, ip=ip, country=country, server=server, include_total_count=include_total_count, page=page, items_path=('records', ), **kwargs)
def reverse_ip_whois(self, query=None, ip=None, country=None, server=None, include_total_count=False, page=1, **kwargs)
Pass in an IP address or a list of free text query terms.
3.988384
3.864511
1.032054
return self._results('reverse-name-server', '/v1/{0}/name-server-domains'.format(query), items_path=('primary_domains', ), limit=limit, **kwargs)
def reverse_name_server(self, query, limit=None, **kwargs)
Pass in a domain name or a name server.
12.768602
12.191342
1.04735
return self._results('reverse-whois', '/v1/reverse-whois', terms=delimited(query), exclude=delimited(exclude), scope=scope, mode=mode, **kwargs)
def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs)
List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ).
6.97172
6.318407
1.103398
return self._results('whois-history', '/v1/{0}/whois/history'.format(query), items_path=('history', ), **kwargs)
def whois_history(self, query, **kwargs)
Pass in a domain name.
9.657083
9.256229
1.043306
return self._results('phisheye', '/v1/phisheye', query=query, days_back=days_back, items_path=('domains', ), **kwargs)
def phisheye(self, query, days_back=None, **kwargs)
Returns domain results for the specified term for today or the specified number of days_back. Terms must be setup for monitoring via the web interface: https://research.domaintools.com/phisheye. NOTE: Properties of a domain are only provided if we have been able to obtain them. Many domains will have incomplete data because that information isn't available in their Whois records, or they don't have DNS results for a name server or IP address.
7.753328
6.616404
1.171834
return self._results('phisheye_term_list', '/v1/phisheye/term-list', include_inactive=include_inactive, items_path=('terms', ), **kwargs)
def phisheye_term_list(self, include_inactive=False, **kwargs)
Provides a list of terms that are set up for this account. This call is not charged against your API usage limit. NOTE: The terms must be configured in the PhishEye web interface: https://research.domaintools.com/phisheye. There is no API call to set up the terms.
5.636481
5.952983
0.946833
if ((not domain and not ip and not email and not nameserver and not registrar and not registrant and not registrant_org and not kwargs)): raise ValueError('At least one search term must be specified') return self._results('iris', '/v1/iris', domain=domain, ip=ip, email=email, nameserver=nameserver, registrar=registrar, registrant=registrant, registrant_org=registrant_org, items_path=('results', ), **kwargs)
def iris(self, domain=None, ip=None, email=None, nameserver=None, registrar=None, registrant=None, registrant_org=None, **kwargs)
Performs a search for the provided search terms ANDed together, returning the pivot engine row data for the resulting domains.
2.636079
2.615583
1.007836
return self._results('risk', '/v1/risk', items_path=('components', ), domain=domain, cls=Reputation, **kwargs)
def risk(self, domain, **kwargs)
Returns back the risk score for a given domain
23.650227
22.66658
1.043396
return self._results('risk-evidence', '/v1/risk/evidence/', items_path=('components', ), domain=domain, **kwargs)
def risk_evidence(self, domain, **kwargs)
Returns back the detailed risk evidence associated with a given domain
17.413773
15.815706
1.101043
if not domains: raise ValueError('One or more domains to enrich must be provided') domains = ','.join(domains) data_updated_after = kwargs.get('data_updated_after', None) if hasattr(data_updated_after, 'strftime'): data_updated_after = data_updated_after.strftime('%Y-%M-%d') return self._results('iris-enrich', '/v1/iris-enrich/', domain=domains, data_updated_after=data_updated_after, items_path=('results', ), **kwargs)
def iris_enrich(self, *domains, **kwargs)
Returns back enriched data related to the specified domains using our Iris Enrich service each domain should be passed in as an un-named argument to the method: iris_enrich('domaintools.com', 'google.com') api.iris_enrich(*DOMAIN_LIST)['results_count'] Returns the number of results api.iris_enrich(*DOMAIN_LIST)['missing_domains'] Returns any domains that we were unable to retrieve enrichment data for api.iris_enrich(*DOMAIN_LIST)['limit_exceeded'] Returns True if you've exceeded your API usage for enrichment in api.iris_enrich(*DOMAIN_LIST): # Enables looping over all returned enriched domains for example: enrich_domains = ['google.com', 'amazon.com'] assert api.iris_enrich(*enrich_domains)['missing_domains'] == []
3.603078
3.715137
0.969837
if not (kwargs or domains): raise ValueError('Need to define investigation using kwarg filters or domains') if type(domains) in (list, tuple): domains = ','.join(domains) if hasattr(data_updated_after, 'strftime'): data_updated_after = data_updated_after.strftime('%Y-%M-%d') if hasattr(expiration_date, 'strftime'): expiration_date = expiration_date.strftime('%Y-%M-%d') if hasattr(create_date, 'strftime'): create_date = create_date.strftime('%Y-%M-%d') if type(active) == bool: active = str(active).lower() return self._results('iris-investigate', '/v1/iris-investigate/', domain=domains, data_updated_after=data_updated_after, expiration_date=expiration_date, create_date=create_date, items_path=('results', ), **kwargs)
def iris_investigate(self, domains=None, data_updated_after=None, expiration_date=None, create_date=None, active=None, **kwargs)
Returns back a list of domains based on the provided filters. The following filters are available beyond what is parameterized as kwargs: - ip: Search for domains having this IP. - email: Search for domains with this email in their data. - email_domain: Search for domains where the email address uses this domain. - nameserver_host: Search for domains with this nameserver. - nameserver_domain: Search for domains with a nameserver that has this domain. - nameserver_ip: Search for domains with a nameserver on this IP. - registrar: Search for domains with this registrar. - registrant: Search for domains with this registrant name. - registrant_org: Search for domains with this registrant organization. - mailserver_host: Search for domains with this mailserver. - mailserver_domain: Search for domains with a mailserver that has this domain. - mailserver_ip: Search for domains with a mailserver on this IP. - redirect_domain: Search for domains which redirect to this domain. - ssl_hash: Search for domains which have an SSL certificate with this hash. - ssl_subject: Search for domains which have an SSL certificate with this subject string. - ssl_email: Search for domains which have an SSL certificate with this email in it. - ssl_org: Search for domains which have an SSL certificate with this organization in it. - google_analytics: Search for domains which have this Google Analytics code. - adsense: Search for domains which have this AdSense code. - tld: Filter by TLD. Must be combined with another parameter. You can loop over results of your investigation as if it was a native Python list: for result in api.iris_investigate(ip='199.30.228.112'): # Enables looping over all related results api.iris_investigate(QUERY)['results_count'] Returns the number of results returned with this request api.iris_investigate(QUERY)['total_count'] Returns the number of results available within Iris api.iris_investigate(QUERY)['missing_domains'] Returns any domains that we were unable to find api.iris_investigate(QUERY)['limit_exceeded'] Returns True if you've exceeded your API usage api.iris_investigate(QUERY)['position'] Returns the position key that can be used to retrieve the next page: next_page = api.iris_investigate(QUERY, position=api.iris_investigate(QUERY)['position']) for enrichment in api.iris_enrich(i): # Enables looping over all returned enriched domains
2.654257
2.767452
0.959098
url = 'https://finance.yahoo.com/quote/%s/history' % (self.ticker) r = requests.get(url) txt = r.content cookie = r.cookies['B'] pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}') for line in txt.splitlines(): m = pattern.match(line.decode("utf-8")) if m is not None: crumb = m.groupdict()['crumb'] crumb = crumb.replace(u'\\u002F', '/') return cookie, crumb
def init(self)
Returns a tuple pair of cookie and crumb used in the request
3.05137
2.690872
1.133971
if self.interval not in ["1d", "1wk", "1mo"]: raise ValueError("Incorrect interval: valid intervals are 1d, 1wk, 1mo") url = self.api_url % (self.ticker, self.start, self.end, self.interval, events, self.crumb) data = requests.get(url, cookies={'B':self.cookie}) content = StringIO(data.content.decode("utf-8")) return pd.read_csv(content, sep=',')
def getData(self, events)
Returns a list of historical data from Yahoo Finance
4.002709
3.324314
1.204071
if self.disk_mounter == 'auto': methods = [] def add_method_if_exists(method): if (method == 'avfs' and _util.command_exists('avfsd')) or \ _util.command_exists(method): methods.append(method) if self.read_write: add_method_if_exists('xmount') else: if disk_type == 'encase': add_method_if_exists('ewfmount') elif disk_type == 'vmdk': add_method_if_exists('vmware-mount') add_method_if_exists('affuse') elif disk_type == 'dd': add_method_if_exists('affuse') elif disk_type == 'compressed': add_method_if_exists('avfs') elif disk_type == 'qcow2': add_method_if_exists('qemu-nbd') elif disk_type == 'vdi': add_method_if_exists('qemu-nbd') add_method_if_exists('xmount') else: methods = [self.disk_mounter] return methods
def _get_mount_methods(self, disk_type)
Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount methods.
2.847806
2.911565
0.978102
self._paths['avfs'] = tempfile.mkdtemp(prefix='image_mounter_avfs_') # start by calling the mountavfs command to initialize avfs _util.check_call_(['avfsd', self._paths['avfs'], '-o', 'allow_other'], stdout=subprocess.PIPE) # no multifile support for avfs avfspath = self._paths['avfs'] + '/' + os.path.abspath(self.paths[0]) + '#' targetraw = os.path.join(self.mountpoint, 'avfs') os.symlink(avfspath, targetraw) logger.debug("Symlinked {} with {}".format(avfspath, targetraw)) raw_path = self.get_raw_path() logger.debug("Raw path to avfs is {}".format(raw_path)) if raw_path is None: raise MountpointEmptyError()
def _mount_avfs(self)
Mounts the AVFS filesystem.
5.046511
4.985053
1.012328