code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Crafts a navigator or from a hal-json link dict. If the link is relative, the returned navigator will have a uri that relative to this navigator's uri. If the link passed in is templated, a PartialNavigator will be returned instead. ''' # resolve relative uri...
def _navigator_or_thunk(self, link)
Crafts a navigator or from a hal-json link dict. If the link is relative, the returned navigator will have a uri that relative to this navigator's uri. If the link passed in is templated, a PartialNavigator will be returned instead.
8.300696
3.2775
2.532631
'''Whether this navigator can parse the given content-type. Checks that the content_type matches one of the types specified in the 'Accept' header of the request, if supplied. If not supplied, matches against the default''' content_type, content_subtype, content_param = utils.par...
def _can_parse(self, content_type)
Whether this navigator can parse the given content-type. Checks that the content_type matches one of the types specified in the 'Accept' header of the request, if supplied. If not supplied, matches against the default
5.327737
3.235476
1.646662
'''Parses the content of a response doc into the correct format for .state. ''' try: return json.loads(text) except ValueError: raise exc.UnexpectedlyNotJSON( "The resource at {.uri} wasn't valid JSON", self)
def _parse_content(self, text)
Parses the content of a response doc into the correct format for .state.
15.980621
6.355948
2.514278
'''Update the self link of this navigator''' self.self.props.update(link) # Set the self.type to the content_type of the returned document self.self.props['type'] = headers.get( 'Content-Type', self.DEFAULT_CONTENT_TYPE) self.self.props
def _update_self_link(self, link, headers)
Update the self link of this navigator
6.736219
5.739923
1.173573
'''Takes a response object and ingests state, links, embedded documents and updates the self link of this navigator to correspond. This will only work if the response is valid JSON ''' self.response = response if self._can_parse(response.headers['Content-Type']): ...
def _ingest_response(self, response)
Takes a response object and ingests state, links, embedded documents and updates the self link of this navigator to correspond. This will only work if the response is valid JSON
5.252935
3.472888
1.512555
'''Create the appropriate navigator from an api response''' method = response.request.method # TODO: refactor once hooks in place if method in (POST, PUT, PATCH, DELETE) \ and response.status_code in ( http_client.CREATED, http_client.FOUND, ...
def _create_navigator(self, response, raise_exc=True)
Create the appropriate navigator from an api response
4.355125
4.181996
1.041399
'''Fetches HTTP response using the passed http method. Raises HALNavigatorError if response is in the 400-500 range.''' headers = headers or {} if body and 'Content-Type' not in headers: headers.update({'Content-Type': 'application/json'}) response = self._core.sessio...
def _request(self, method, body=None, raise_exc=True, headers=None, files=None)
Fetches HTTP response using the passed http method. Raises HALNavigatorError if response is in the 400-500 range.
3.690988
2.480703
1.48788
'''Performs a GET request to the uri of this navigator''' self._request(GET, raise_exc=raise_exc) # ingests response self.fetched = True return self.state.copy()
def fetch(self, raise_exc=True)
Performs a GET request to the uri of this navigator
14.627954
8.393315
1.74281
'''Performs an HTTP POST to the server, to create a subordinate resource. Returns a new HALNavigator representing that resource. `body` may either be a string or a dictionary representing json `headers` are additional headers to send in the request ''' return sel...
def create(self, body=None, raise_exc=True, headers=None, **kwargs)
Performs an HTTP POST to the server, to create a subordinate resource. Returns a new HALNavigator representing that resource. `body` may either be a string or a dictionary representing json `headers` are additional headers to send in the request
10.041157
2.181289
4.603312
'''Performs an HTTP DELETE to the server, to delete resource(s). `headers` are additional headers to send in the request''' return self._request(DELETE, None, raise_exc, headers, files)
def delete(self, raise_exc=True, headers=None, files=None)
Performs an HTTP DELETE to the server, to delete resource(s). `headers` are additional headers to send in the request
8.04488
3.617893
2.223637
'''Performs an HTTP PUT to the server. This is an idempotent call that will create the resource this navigator is pointing to, or will update it if it already exists. `body` may either be a string or a dictionary representing json `headers` are additional headers to send in the ...
def upsert(self, body, raise_exc=True, headers=False, files=None)
Performs an HTTP PUT to the server. This is an idempotent call that will create the resource this navigator is pointing to, or will update it if it already exists. `body` may either be a string or a dictionary representing json `headers` are additional headers to send in the request
8.230716
1.992884
4.130052
'''Performs an HTTP PATCH to the server. This is a non-idempotent call that may update all or a portion of the resource this navigator is pointing to. The format of the patch body is up to implementations. `body` may either be a string or a dictionary representing json `...
def patch(self, body, raise_exc=True, headers=False, files=None)
Performs an HTTP PATCH to the server. This is a non-idempotent call that may update all or a portion of the resource this navigator is pointing to. The format of the patch body is up to implementations. `body` may either be a string or a dictionary representing json `headers` ar...
8.775696
1.775771
4.941908
'''Try to parse as HAL, but on failure use an empty dict''' try: return super(OrphanHALNavigator, self)._parse_content(text) except exc.UnexpectedlyNotJSON: return {}
def _parse_content(self, text)
Try to parse as HAL, but on failure use an empty dict
21.001959
8.527283
2.462913
mx = X.max(axis=axis) if (X.ndim > 1): mx = np.atleast_2d(mx).T if axis == 1 else np.atleast_2d(mx) return np.log(np.exp(X - mx).sum(axis=axis)) + np.ravel(mx)
def logsumexp(X, axis=0)
Log-sum-exp trick for matrix X for summation along a specified axis. This performs the following operation in a stable fashion, .. math:: \log \sum^K_{k=1} \exp\{x_k\} Parameters ---------- X: ndarray 2D array of shape (N, D) to apply the log-sum-exp trick. axis: ...
2.905347
3.034869
0.957322
if axis == 1: return np.exp(X - logsumexp(X, axis=1)[:, np.newaxis]) elif axis == 0: return np.exp(X - logsumexp(X, axis=0)) else: raise ValueError("This only works on 2D arrays for now.")
def softmax(X, axis=0)
Pass X through a softmax function in a numerically stable way using the log-sum-exp trick. This transformation is: .. math:: \\frac{\exp\{X_k\}}{\sum^K_{j=1} \exp\{X_j\}} and is appliedx to each row/column, `k`, of X. Parameters ---------- X: ndarray 2D array of ...
2.395483
2.568076
0.932793
if np.isscalar(X): return logsumexp(np.vstack((np.zeros(1), [X])).T, axis=1)[0] N = X.shape[0] if X.ndim == 1: return logsumexp(np.vstack((np.zeros(N), X)).T, axis=1) elif X.ndim == 2: sftX = np.empty(X.shape, dtype=float) for d in range(X.shape[1]): s...
def softplus(X)
Pass X through a soft-plus function, , in a numerically stable way (using the log-sum-exp trick). The softplus transformation is: .. math:: \log(1 + \exp\{X\}) Parameters ---------- X: ndarray shape (N,) array or shape (N, D) array of da...
2.365205
2.384708
0.991822
n, length = str(n), len(str(n)) if length >= 13 and length <= 16: if n[0] == '4': return True return False
def is_visa(n)
Checks if credit card number fits the visa format.
3.525006
3.139916
1.122643
n, length = str(n), len(str(n)) form = ['026', '508', '844', '913', '917'] if length == 16: if n[0] == '4': if ''.join(n[1:4]) in form or ''.join(n[1:6]) == '17500': return True return False
def is_visa_electron(n)
Checks if credit card number fits the visa electron format.
4.254964
3.871524
1.099041
n, length = str(n), len(str(n)) if length >= 16 and length <= 19: if ''.join(n[:2]) in strings_between(51, 56): return True return False
def is_mastercard(n)
Checks if credit card number fits the mastercard format.
5.465575
4.965428
1.100726
n, length = str(n), len(str(n)) if length == 15: if n[0] == '3' and (n[1] == '4' or n[1] == '7'): return True return False
def is_amex(n)
Checks if credit card number fits the american express format.
2.561734
2.331958
1.098533
n, length = str(n), len(str(n)) if length == 16: if n[0] == '6': if ''.join(n[1:4]) == '011' or n[1] == '5': return True elif n[1] == '4' and n[2] in strings_between(4, 10): return True elif ''.join(n[1:6]) in strings_between(2212...
def is_discover(n)
Checks if credit card number fits the discover card format.
3.97065
3.426778
1.158712
formats = [] if is_visa(n): formats.append('visa') if is_visa_electron(n): formats.append('visa electron') if is_mastercard(n): formats.append('mastercard') if is_amex(n): formats.append('amex') if is_maestro(n): formats.append('maestro') if is_d...
def get_format(n)
Gets a list of the formats a credit card number fits.
1.959739
1.660218
1.180411
@wraps(fn) def new_fn(*args): args_flat, shapes = flatten(args) result = fn(args_flat) return unflatten(result, shapes=shapes) return new_fn
def flatten_args(fn)
Examples -------- >>> @flatten_args ... def f(x): ... return 2*x >>> x, y, z = f(np.array([1., 2.]), 3., np.array([[1., 2.],[.5, .9]])) >>> x array([ 2., 4.]) >>> y 6.0 >>> z array([[ 2. , 4. ], [ 1. , 1.8]])
3.147413
4.272213
0.736717
@wraps(fn) def new_fn(*args): return fn(np.asarray(args)) return new_fn
def unvectorize_args(fn)
See Also -------- revrand.utils.decorators.vectorize_args Examples -------- The Rosenbrock function is commonly used as a performance test problem for optimization algorithms. It and its derivatives are included in `scipy.optimize` and is implemented as expected by the family of opti...
3.170681
5.064963
0.626003
name, ext = os.path.splitext(filename) slugified = get_slugified_name(name) return slugified + ext
def slugify_filename(filename)
Slugify filename
3.030111
3.048717
0.993897
valid_extensions = ['.jpeg', '.jpg', '.gif', '.png'] _, extension = os.path.splitext(file_path) return extension.lower() in valid_extensions
def is_valid_image_extension(file_path)
is_valid_image_extension.
2.315163
2.244078
1.031677
if self.prefix is not None: return '.'.join([self.prefix, self.member]) return self.member
def full_name(self)
Return full name of member
6.014235
4.51501
1.332053
assert cls.signature_pattern is not None pattern = re.compile(cls.signature_pattern, re.VERBOSE) match = pattern.match(signature) if match: groups = match.groupdict() arguments = None if 'arguments' in groups and groups['arguments'] is not Non...
def parse_signature(cls, signature)
Parse signature declartion string Uses :py:attr:`signature_pattern` to parse out pieces of constraint signatures. Pattern should provide the following named groups: prefix Object prefix, such as a namespace member Object member name ...
2.843144
2.515908
1.130067
try: sig = self.parse_signature(sig.strip()) except ValueError: self.env.warn(self.env.docname, 'Parsing signature failed: "{}"'.format(sig), self.lineno) raise prefix = self.env.ref_context.get('dn...
def handle_signature(self, sig, signode)
Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is assuming that the .NET languages this will support will be in a common format, such as:: Namespace.Class.method(argument, argument, ...) The namespace and cla...
3.620512
3.436172
1.053647
full_name = name[0] target_name = '{0}-{1}'.format(self.short_name, full_name) if target_name not in self.state.document.ids: signode['names'].append(target_name) signode['ids'].append(target_name) signode['first'] = not self.names self.st...
def add_target_and_index(self, name, sig, signode)
Add objects to the domain list of objects This uses the directive short name along with the full object name to create objects and nodes that are type and name unique.
2.80432
2.773775
1.011012
(name, _) = name_obj msg = '{name} ({obj_type})' parts = { 'name': name, 'prefix': prefix, 'obj_type': self.long_name, } try: (obj_ns, obj_name) = name.rsplit('.', 1) parts['name'] = obj_name parts['...
def get_index_text(self, prefix, name_obj)
Produce index text by directive attributes
3.221376
3.21009
1.003516
nodes = super(DotNetObjectNested, self).run() if 'hidden' in self.options: for node in nodes: if isinstance(node, addnodes.desc): for (m, child) in enumerate(node.children): if isinstance(child, addnodes.desc_signature): ...
def run(self)
If element is considered hidden, drop the desc_signature node The default handling of signatures by :py:cls:`ObjectDescription` returns a list of nodes with the signature nodes. We are going to remove them if this is a hidden declaration.
5.665674
3.96019
1.430657
super(DotNetObjectNested, self).before_content() if self.names: (_, prefix) = self.names.pop() try: self.env.ref_context['dn:prefixes'].append(prefix) except (AttributeError, KeyError): self.env.ref_context['dn:prefixes'] = [pr...
def before_content(self)
Build up prefix history for nested elements The following keys are used in :py:attr:`self.env.ref_context`: dn:prefixes Stores the prefix history. With each nested element, we add the prefix to a list of prefixes. When we exit that object's nesting l...
4.852618
3.279977
1.479467
result = super(DotNetXRefRole, self).process_link(env, refnode, has_explicit_title, title, target) (title, target) = result if not has_explicit_title: # If the...
def process_link(self, env, refnode, has_explicit_title, title, target)
This handles some special cases for reference links in .NET First, the standard Sphinx reference syntax of ``:ref:`Title<Link>```, where a reference to ``Link`` is created with title ``Title``, causes problems for the generic .NET syntax of ``:dn:cls:`FooBar<T>```. So, here we assume th...
3.116563
3.213368
0.969874
# Skip parens if name[-2:] == '()': name = name[:-2] if not name: return [] object_types = list(self.object_types) if obj_type is not None: object_types = self.objtypes_for_role(obj_type) objects = self.data['objects'] ...
def find_obj(self, env, prefix, name, obj_type, searchorder=0)
Find object reference :param env: Build environment :param prefix: Object prefix :param name: Object name :param obj_type: Object type :param searchorder: Search for exact match
2.943956
3.115138
0.945048
prefix = node.get('dn:prefix') results = [] match = self.find_obj(env, prefix, target, None, 1) if match is not None: (name, obj) = match results.append(('dn:' + self.role_for_objtype(obj[1]), make_refnode(builder, fromdocname...
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode)
Look for any references, without object type This always searches in "refspecific" mode
5.760654
5.870229
0.981334
return Image.new(self.mode, (width, height))
def create(self, width, height)
Create an image of type. Parameters ---------- width: `int` Image width. height: `int` Image height. Returns ------- `PIL.Image.Image`
5.413553
8.393838
0.644944
if self.channel_mode is None: return self.create(width, height) return Image.new(self.channel_mode, (width, height))
def create_channel(self, width, height)
Create a channel. Parameters ---------- width: `int` Image width. height: `int` Image height. Returns ------- `PIL.Image.Image`
4.208997
4.816668
0.87384
if not imgs: raise ValueError('empty channel list') if len(imgs) == 1: return imgs[0] return Image.merge(self.mode, imgs)
def merge(self, imgs)
Merge image channels. Parameters ---------- imgs : `list` of `PIL.Image.Image` Returns ------- `PIL.Image.Image` Raises ------ ValueError If image channel list is empty.
3.263982
3.03756
1.074541
# Try cholesky for speed try: lower = False L = cholesky(A, lower=lower) if any(L.diagonal() < CHOLTHRESH): raise LinAlgError("Unstable cholesky factor detected") X = cho_solve((L, lower), b) logdet = cho_log_det(L) # Failed cholesky, use svd to do t...
def solve_posdef(A, b)
Solve the system :math:`A X = b` for :math:`X` where :math:`A` is a positive semi-definite matrix. This first tries cholesky, and if numerically unstable with solve using a truncated SVD (see solve_posdef_svd). The log-determinant of :math:`A` is also returned since it requires minimal overhead. ...
4.178245
4.049872
1.031698
# Test shapes for efficient computations n = U.shape[0] assert(b.shape[0] == n) m = b.shape[1] if np.ndim(b) > 1 else 1 # Auto clamp SVD based on threshold sclamp = np.maximum(s, s_tol) # Inversion factors ss = 1. / np.sqrt(sclamp) U2 = U * ss[np.newaxis, :] V2 = ss[:, np....
def svd_solve(U, s, V, b, s_tol=1e-15)
Solve the system :math:`A X = b` for :math:`X`. Here :math:`A` is a positive semi-definite matrix using the singular value decomposition. This truncates the SVD so only dimensions corresponding to non-negative and sufficiently large singular values are used. Parameters ---------- U: ndarray ...
4.956575
4.959196
0.999472
# dot is a sum product over the last axis of a and the second-to-last of b. # Transpose - can specify axes, default transposes a[0] and a[1] hmm n_vectors, n_Y = Y.shape matching = (n_vectors, 2, int(n_Y / 2)) H = np.array([[1, 1], [1, -1]]) / 2. # Julia uses 2 and not sqrt(2)? steps = int...
def hadamard(Y, ordering=True)
*Very fast* Hadamard transform for single vector at a time. Parameters ---------- Y: ndarray the n*2^k data to be 1d hadamard transformed ordering: bool, optional reorder from Walsh to sequence Returns ------- H: ndarray hadamard transformed data. Examples ...
6.2653
6.629707
0.945034
result_start, result_end = False, False parent_start = start.getparent() parent_end = end.getparent() if parent_start.tag == "{%s}p" % namespaces['text']: # more than one child in the containing paragraph ? # we keep the boundary result_start = len(parent_start.getchildren(...
def detect_keep_boundary(start, end, namespaces)
a helper to inspect a link and see if we should keep the link boundary
2.39712
2.345604
1.021962
old_ = start.getparent() if keep_start_boundary: new_.append(copy(start)) else: if start.tail: # copy the existing tail as text new_.text = start.tail # get all siblings for node in start.itersiblings(): if node is not end: new_.appe...
def move_siblings( start, end, new_, keep_start_boundary=False, keep_end_boundary=False )
a helper function that will replace a start/end node pair by a new containing element, effectively moving all in-between siblings This is particularly helpful to replace for /for loops in tables with the content resulting from the iteration This function call returns None. The parent xml tree is modifi...
4.674004
4.343803
1.076016
return Transformer( '//list[namespace-uri()="%s"]' % namespaces.get( 'text' ) ).attr( '{0}id'.format(XML_NS), lambda *args: "list{0}".format(uuid4().hex) )
def get_list_transformer(namespaces)
this function returns a transformer to find all list elements and recompute their xml:id. Because if we duplicate lists we create invalid XML. Each list must have its own xml:id This is important if you want to be able to reopen the produced document wih an XML parser. LibreOffice will fix those ...
10.087874
7.81081
1.291527
# create needed namespaces self.namespaces = dict( text="urn:text", draw="urn:draw", table="urn:table", office="urn:office", xlink="urn:xlink", svg="urn:svg", manifest="urn:manifest", ) # copy n...
def __prepare_namespaces(self)
create proper namespaces for our document
5.554889
5.021341
1.106256
res = [] # TODO: Check if instructions can be stored in other content_trees for e in get_instructions(self.content_trees[0], self.namespaces): childs = e.getchildren() if childs: res.extend([c.text for c in childs]) else: ...
def get_user_instructions(self)
Public method to help report engine to find all instructions
5.784508
5.531688
1.045704
instructions = self.get_user_instructions() user_variables = self.get_user_variables() # For now we just want for loops instructions = [i for i in instructions if i.startswith('for') or i == '/for'] # Now we call the decoder to get variable mapp...
def get_user_instructions_mapping(self)
Public method to get the mapping of all variables defined in the template
5.359599
5.295092
1.012182
# OLD open office version if link.text is not None and link.text.strip(): if not link.text == py3o_base: msg = "url and text do not match in '%s'" % link.text raise TemplateException(msg) # new open office version elif len(link): ...
def handle_link(self, link, py3o_base, closing_link)
transform a py3o link into a proper Genshi statement rebase a py3o link at a proper place in the tree to be ready for Genshi replacement
3.284731
3.19256
1.02887
# TODO: Check if some user fields are stored in other content_trees return [ e.get('{%s}name' % e.nsmap.get('text'))[5:] for e in get_user_fields(self.content_trees[0], self.namespaces) ]
def get_user_variables(self)
a public method to help report engines to introspect a template and find what data it needs and how it will be used returns a list of user variable names without starting 'py3o.
11.968996
13.959764
0.857392
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]" for content_tree in self.content_trees: for userfield in content_tree.xpath( field_expr, namespaces=self.namespaces ): parent = userfield.getparent()...
def __prepare_usertexts(self)
Replace user-type text fields that start with "py3o." with genshi instructions.
3.529258
3.290761
1.072475
image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]" for content_tree in self.content_trees: # Find draw:frame tags. for draw_frame in content_tree.xpath( image_expr, namespaces=self.namespaces ): # ...
def __replace_image_links(self)
Replace links of placeholder images (the name of which starts with "py3o.") to point to a file saved the "Pictures" directory of the archive.
4.482227
4.040236
1.109397
xpath_expr = "//manifest:manifest[1]" for content_tree in self.content_trees: # Find manifest:manifest tags. manifest_e = content_tree.xpath( xpath_expr, namespaces=self.namespaces ) if not manifest_e: ...
def __add_images_to_manifest(self)
Add entries for py3o images into the manifest file.
3.901595
3.379946
1.154336
# TODO: find a way to make this localization aware... # because ATM it formats texts using French style numbers... # best way would be to let the user inject its own vars... # but this would not work on fusion servers... # so we must find a way to localize this a bit... ...
def render_tree(self, data)
prepare the flows without saving to file this method has been decoupled from render_flow to allow better unit testing
8.530546
8.513021
1.002059
self.render_tree(data) # then reconstruct a new ODT document with the generated content for status in self.__save_output(): yield status
def render_flow(self, data)
render the OpenDocument with the user data @param data: the input stream of user data. This should be a dictionary mapping, keys being the values accessible to your report. @type data: dictionary
29.351959
28.808296
1.018872
f = open(path, 'rb') self.set_image_data(identifier, f.read()) f.close()
def set_image_path(self, identifier, path)
Set data for an image mentioned in the template. @param identifier: Identifier of the image; refer to the image in the template by setting "py3o.[identifier]" as the name of that image. @type identifier: string @param path: Image path on the file system @type path: string
3.161066
3.099099
1.019995
out = zipfile.ZipFile(self.outputfilename, 'w') for info_zip in self.infile.infolist(): if info_zip.filename in self.templated_files: # Template file - we have edited these. # get a temp file streamout = open(get_secure_filename(), ...
def __save_output(self)
Saves the output into a native OOo document format.
5.882608
5.666243
1.038185
arg1 = parent.add_subparsers(dest='command') arg2 = arg1.add_parser('create') arg2.add_argument('-P', '--progress', action='store_true', help='show progress bar') arg2.add_argument('-s', '--settings', type=FileType('r'), default=No...
def create_arg_parser(parent)
Create command subparsers. Parameters ---------- parent : `argparse.ArgumentParser` Command parser.
1.74423
1.759251
0.991462
with infiles(fnames, progress) as fnames: for fname in fnames: with open(fname, 'r') as fp: if progress: fp.seek(0, SEEK_END) total = fp.tell() title = truncate(fname, BAR_DESC_SIZE - 1, False) p...
def read(fnames, markov, progress)
Read data files and update a generator. Parameters ---------- fnames : `list` of `str` File paths. markov : `markovchain.base.MarkovBase` Generator to update. progress : `bool` Show progress bar.
2.844308
2.970904
0.957388
if args.type == SQLITE: if args.output is not None and path.exists(args.output): remove(args.output) storage = SqliteStorage(db=args.output, settings=args.settings) else: storage = JsonStorage(settings=args.settings) markov = MarkovText.from_storage(storage) read...
def cmd_create(args)
Create a generator. Parameters ---------- args : `argparse.Namespace` Command arguments.
4.423716
4.981786
0.887978
#args.output = None markov = load(MarkovText, args.state, args) read(args.input, markov, args.progress) if args.output is None: if args.type == SQLITE: save(markov, None, args) elif args.type == JSON: name, ext = path.splitext(args.state) tmp = n...
def cmd_update(args)
Update a generator. Parameters ---------- args : `argparse.Namespace` Command arguments.
4.283416
4.736995
0.904248
if args.start: if args.end or args.reply: raise ValueError('multiple input arguments') args.reply_to = args.start args.reply_mode = ReplyMode.END elif args.end: if args.reply: raise ValueError('multiple input arguments') args.reply_to = args....
def cmd_generate(args)
Generate text. Parameters ---------- args : `argparse.Namespace` Command arguments.
3.529715
3.538575
0.997496
parser = ArgumentParser() parser.add_argument('-v', '--version', action='version', version=CLI_VERSION) parsers = parser.add_subparsers(dest='dtype') text.create_arg_parser(parsers.add_parser('text')) if image is not None: image.create_arg_parser(parsers.add_pa...
def main(args=None)
CLI main function. Parameters ---------- args : `list` of `str`, optional CLI arguments (default: `sys.argv`).
2.894618
2.9852
0.969656
digits = digits_of(unchecked) checksum = sum(even_digits(unchecked)) + sum([ sum(digits_of(2 * d)) for d in odd_digits(unchecked)]) return 9 * checksum % 10
def get_check_digit(unchecked)
returns the check digit of the card number.
6.296248
6.054644
1.039904
n = str(number) if not n.isdigit(): return False return int(n[-1]) == get_check_digit(n[:-1])
def is_valid(number)
determines whether the card number is valid.
3.986162
3.6138
1.103039
if not isinstance(length, int) or length < 2: raise TypeError('length must be a positive integer greater than 1.') # first digit cannot be 0 digits = [random.randint(1, 9)] for i in range(length-2): digits.append(random.randint(0, 9)) digits.append(get_check_digit(''.join(map(...
def generate(length)
Generates random and valid card number which is returned as a string.
2.765553
2.666023
1.037333
backend = getattr(settings, 'SIMDITOR_IMAGE_BACKEND', None) if backend == 'pillow': from simditor.image import pillow_backend as backend else: from simditor.image import dummy_backend as backend return backend
def get_backend()
Get backend.
3.683135
3.74747
0.982833
data = super().save() data['reverse'] = self.reverse data['line_sentences'] = self.line_sentences return data
def save(self)
Convert to JSON. Returns ------- `dict` JSON data.
7.114514
8.511439
0.835877
x0 = 0 y0 = 0 x1 = width - 1 y1 = height - 1 while x0 < x1 and y0 < y1: for x in range(x0, x1): yield x, y0 for y in range(y0, y1): yield x1, y for x in range(x1, x0, -1): yield x, y1 ...
def _rspiral(width, height)
Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points.
1.484495
1.518162
0.977824
if width == 1: for y in range(height - 1, -1, -1): yield 0, y return if height == 1: for x in range(width - 1, -1, -1): yield x, 0 return if width <= height: x0 = width // 2 if widt...
def _spiral(width, height)
Spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points.
1.667725
1.648008
1.011964
if block_idx == 0: return y, x if block_idx == 1: return x, y + block_size if block_idx == 2: return x + block_size, y + block_size if block_idx == 3: x, y = block_size - 1 - y, block_size - 1 - x return x + block_size,...
def get_point_in_block(cls, x, y, block_idx, block_size)
Get point coordinates in next block. Parameters ---------- x : `int` X coordinate in current block. y : `int` Y coordinate in current block. block_index : `int` Current block index in next block. block_size : `int` Current ...
2.056269
2.086664
0.985434
x, y = cls.POSITION[idx % 4] idx //= 4 block_size = 2 while block_size < size: block_idx = idx % 4 x, y = cls.get_point_in_block(x, y, block_idx, block_size) idx //= 4 block_size *= 2 return x, y
def get_point(cls, idx, size)
Get curve point coordinates by index. Parameters ---------- idx : `int` Point index. size : `int` Curve size. Returns ------- (`int`, `int`) Point coordinates.
2.861796
3.624058
0.789666
data = super().save() data['block_size'] = list(self.block_size) data['block_sentences'] = self.block_sentences data['traverse_image'] = self.traverse_image.save() data['traverse_block'] = self.traverse_block.save() return data
def save(self)
Convert to JSON. Returns ------- `dict` JSON data.
4.318169
4.464755
0.967168
# First we go through all attrs from the ForList and add respective # keys on the dict. for a in forlist.attrs: a_list = a.split('.') if len(a_list) == 1: res = data_dict[a_list[0]] return res if a_list[0] in data_dict...
def __recur_to_dict(forlist, data_dict, res)
Recursive function that fills up the dictionary
3.178294
3.194916
0.994797
res = {} # The first level is a little bit special # Manage global variables for a in global_vars: a_list = a.split('.') tmp = res for i in a_list[:-1]: if not i in tmp: tmp[i] = {} tmp = tm...
def to_dict(for_lists, global_vars, data_dict)
Construct a dict object from a list of ForList object :param for_lists: list of for_list :param global_vars: list of global vars to add :param data_dict: data from an orm-like object (with dot notation) :return: a dict representation of the ForList objects
3.009342
2.961209
1.016255
django_logout(request) return HttpResponseRedirect(request.build_absolute_uri(redirect_url))
def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL)
Nothing hilariously hidden here, logs a user out. Strip this out if your application already has hooks to handle this.
3.428138
4.494884
0.762676
# Instantiate Twython with the first leg of our trip. twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) # Request an authorization url to send the user to... callback_url = request.build_absolute_uri(reverse('twython_django_oauth.views.thanks')) auth_props = twitter.get_authenti...
def begin_auth(request)
The view function that initiates the entire handshake. For the most part, this is 100% drag and drop.
5.540839
5.6822
0.975122
# Now that we've got the magic tokens back from Twitter, we need to exchange # for permanent ones and store them... oauth_token = request.session['request_token']['oauth_token'] oauth_token_secret = request.session['request_token']['oauth_token_secret'] twitter = Twython(settings.TWITTER_KEY, s...
def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL)
A user gets redirected here after hitting Twitter and authorizing your app to use their data. This is the view that stores the tokens you want for querying data. Pay attention to this.
3.391284
3.396618
0.99843
user = request.user.twitterprofile twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, user.oauth_token, user.oauth_secret) user_tweets = twitter.get_home_timeline() return render_to_response('tweets.html', {'tweets': user_tweets})
def user_timeline(request)
An example view with Twython/OAuth hooks/calls to fetch data about the user in question.
2.713275
2.570686
1.055467
#if self.parser is None: # raise ValueError('no parser') imgs = self.imgtype.convert(data) for channel, data in zip(self.imgtype.channels, imgs): key = dataset + channel data = self.scanner(data, part) if isinstance(self.parser, LevelParser...
def data(self, data, part=False, dataset='')
Parameters ---------- data : `PIL.Image` Image to parse. part : `bool`, optional True if data is partial (default: `False`). dataset : `str`, optional Dataset key prefix (default: '').
4.337786
4.187559
1.035875
size = width * height if size > 0 and start: yield state_to_pixel(start) size -= 1 while size > 0: prev_size = size pixels = self.generate(state_size, start, dataset) pixels = islice(pixels, 0, size) for pixel in...
def _imgdata(self, width, height, state_size=None, start='', dataset='')
Generate image pixels. Parameters ---------- width : `int` Image width. height : `int` Image height. state_size : `int` or `None`, optional State size to use for generation (default: `None`). start : `str`, optional Initial...
3.665436
3.771254
0.971941
for pixel, (x1, y1) in zip(data, tr): img.putpixel((x + x1, y + y1), pixel) return img
def _write_imgdata(img, data, tr, x=0, y=0)
Write image data. Parameters ---------- img : `PIL.Image.Image` Image. data : `iterable` of `int` Image data. tr : `markovchain.image.traversal.Traversal` Image traversal. x : `int` X offset. y : `int` Y...
3.04861
3.804703
0.801274
ret = start_image for level, state_size in enumerate(state_sizes, start_level + 1): key = dataset + level_dataset(level) if start_image is not None: scale = self.scanner.level_scale[level - 1] width *= scale height *= scale...
def _channel(self, width, height, state_sizes, start_level, start_image, dataset)
Generate a channel. Parameters ---------- width : `int` Image width. height : `int` Image height. state_sizes : `list` of (`int` or `None`) Level state sizes. start_level : `int` Initial level. start_image : `PIL.Im...
3.892172
3.776725
1.030568
flatvalue = np.ravel(parameter.rvs(random_state=random_state)) flatbounds = [parameter.bounds for _ in range(np.prod(parameter.shape, dtype=int))] return flatvalue, flatbounds
def ravel(parameter, random_state=None)
Flatten a ``Parameter``. Parameters ---------- parameter: Parameter A ``Parameter`` object Returns ------- flatvalue: ndarray a flattened array of shape ``(prod(parameter.shape),)`` flatbounds: list a list of bound tuples of length ``prod(parameter.shape)``
5.381614
4.226242
1.27338
vals, bounds = zip(*tup) stackvalue = np.hstack(vals) stackbounds = list(chain(*bounds)) return stackvalue, stackbounds
def hstack(tup)
Horizontally stack a sequence of value bounds pairs. Parameters ---------- tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds
5.674488
7.302839
0.777025
if self.lower: if np.any(value < self.lower): return False if self.upper: if np.any(value > self.upper): return False return True
def check(self, value)
Check a value falls within a bound. Parameters ---------- value : scalar or ndarray value to test Returns ------- bool: If all values fall within bounds Example ------- >>> bnd = Bound(1, 2) >>> bnd.check(1.5) ...
2.708733
2.868039
0.944455
if not self.lower and not self.upper: return value return np.clip(value, self.lower, self.upper)
def clip(self, value)
Clip a value to a bound. Parameters ---------- value : scalar or ndarray value to clip Returns ------- scalar or ndarray : of the same shape as value, bit with each element clipped to fall within the specified bounds Example ...
3.594119
4.6562
0.7719
r # No sampling distibution if self.dist is None: return self.value # Unconstrained samples rs = check_random_state(random_state) samples = self.dist.rvs(size=self.shape, random_state=rs) # Bound the samples samples = self.bounds.clip(samples...
def rvs(self, random_state=None)
r""" Draw a random value from this Parameter's distribution. If ``value`` was not initialised with a ``scipy.stats`` object, then the scalar/ndarray value is returned. Parameters ---------- random_state : None, int or RandomState, optional random seed ...
5.232059
4.94393
1.058279
dirpath = posixpath.split(path)[0] dirs = dirpath.split('/') if not dirs or dirs == ['']: return [] def get_tree_for_dir(tree, dirname): for name, mode, id in tree.iteritems(): if name == dirname: obj = self.repository...
def _get_missing_trees(self, path, root_tree)
Creates missing ``Tree`` objects for the given path. :param path: path given as a string. It may be a path to a file node (i.e. ``foo/bar/baz.txt``) or directory path - in that case it must end with slash (i.e. ``foo/bar/``). :param root_tree: ``dulwich.objects.Tree`` object from wh...
4.005862
3.79517
1.055516
if isinstance(x, list): return x if not isinstance(x, dict): try: return list(x) except TypeError: pass return [x]
def to_list(x)
Convert a value to a list. Parameters ---------- x Value. Returns ------- `list` Examples -------- >>> to_list(0) [0] >>> to_list({'x': 0}) [{'x': 0}] >>> to_list(x ** 2 for x in range(3)) [0, 1, 4] >>> x = [1, 2, 3] >>> to_list(x) [1, 2, 3]...
2.629425
3.59752
0.730899
if isinstance(xs, list) and len(xs) == length: return xs if length <= 0: return [] try: xs = list(islice(xs, 0, length)) if not xs: raise ValueError('empty input') except TypeError: xs = [xs] if len(xs) < length: if copy: ...
def fill(xs, length, copy=False)
Convert a value to a list of specified length. If the input is too short, fill it with its last element. Parameters ---------- xs Input list or value. length : `int` Output list length. copy : `bool`, optional Deep copy the last element to fill the list (default: False)...
2.404716
2.655829
0.905449
if isinstance(val, str): val = val.upper() try: return getattr(cls, val) except AttributeError: raise ValueError('{0}.{1}'.format(cls, val)) return cls(val)
def int_enum(cls, val)
Get int enum value. Parameters ---------- cls : `type` Int enum class. val : `int` or `str` Name or value. Returns ------- `IntEnum` Raises ------ ValueError
3.068054
4.33258
0.708135
if obj is None: return default_factory() if isinstance(obj, dict): return cls.load(obj) return obj
def load(obj, cls, default_factory)
Create or load an object if necessary. Parameters ---------- obj : `object` or `dict` or `None` cls : `type` default_factory : `function` Returns ------- `object`
3.044791
3.894653
0.781787
if maxlen <= 3: raise ValueError('maxlen <= 3') if len(string) <= maxlen: return string if end: return string[:maxlen - 3] + '...' return '...' + string[3 - maxlen:]
def truncate(string, maxlen, end=True)
Truncate a string. Parameters ---------- string : `str` String to truncate. maxlen : `int` Maximum string length. end : `boolean`, optional Remove characters from the end (default: `True`). Raises ------ ValueError If `maxlen` <= 3. Returns ----...
2.777364
3.886473
0.714623
for cls2 in args: cls.classes[cls2.__name__] = cls2
def add_class(cls, *args)
Add classes to the group. Parameters ---------- *args : `type` Classes to add.
5.551296
9.783151
0.567434
for cls2 in args: try: del cls.classes[cls2.__name__] except KeyError: pass
def remove_class(cls, *args)
Remove classes from the group. Parameters ---------- *args : `type` Classes to remove.
3.992964
6.097671
0.654834
ret = cls.classes[data['__class__']] data_cls = data['__class__'] del data['__class__'] try: ret = ret(**data) finally: data['__class__'] = data_cls return ret
def load(cls, data)
Create an object from JSON data. Parameters ---------- data : `dict` JSON data. Returns ---------- `object` Created object. Raises ------ KeyError If `data` does not have the '__class__' key or the...
3.865338
4.239444
0.911756
self.oauth_client = oauth1.Client(consumer_key, consumer_secret)
def set_oauth_client(self, consumer_key, consumer_secret)
Sets the oauth_client attribute
3.317451
3.05055
1.087492
headers = { 'Content-type': 'application/json', } # Note: we don't pass body to sign() since it's only for bodies that # are form-urlencoded. Similarly, we don't care about the body that # sign() returns. uri, signed_headers, signed_body = self.oauth_...
def prepare_request(self, method, url, body='')
Prepare the request body and headers :returns: headers of the signed request
4.253381
4.513536
0.942361
try: body = response.json() if body and 'reason' in body: return body['reason'] except ValueError: pass return response.content
def _get_error_reason(response)
Extract error reason from the response. It might be either the 'reason' or the entire response
3.295412
3.20741
1.027437