_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q28100 | IvyUtils.do_resolve | train | def do_resolve(cls, executor, extra_args, ivyxml, jvm_options, workdir_report_paths_by_conf,
confs, ivy_resolution_cache_dir, ivy_cache_classpath_filename, resolve_hash_name,
workunit_factory, workunit_name):
"""Execute Ivy with the given ivy.xml and copies all relevant files into ... | python | {
"resource": ""
} |
q28101 | IvyUtils._hardlink_cachepath | train | def _hardlink_cachepath(cls, ivy_repository_cache_dir, inpath, hardlink_dir, outpath):
"""hardlinks all paths listed in inpath that are under ivy_repository_cache_dir into hardlink_dir.
If there is an existing hardlink for a file under inpath, it is used rather than creating
a new hardlink. Preserves all o... | python | {
"resource": ""
} |
q28102 | IvyUtils.xml_report_path | train | def xml_report_path(cls, resolution_cache_dir, resolve_hash_name, conf):
"""The path to the xml report ivy creates after a retrieve.
:API: public
:param string cache_dir: The path of the ivy cache dir used for resolves.
:param string resolve_hash_name: Hash from the Cache key | python | {
"resource": ""
} |
q28103 | IvyUtils.parse_xml_report | train | def parse_xml_report(cls, conf, path):
"""Parse the ivy xml report corresponding to the name passed to ivy.
:API: public
:param string conf: the ivy conf name (e.g. "default")
:param string path: The path to the ivy report file.
:returns: The info in the xml report.
:rtype: :class:`IvyInfo`
... | python | {
"resource": ""
} |
q28104 | IvyUtils.generate_fetch_ivy | train | def generate_fetch_ivy(cls, jars, ivyxml, confs, resolve_hash_name):
"""Generates an ivy xml with all jars marked as intransitive using the all conflict manager."""
org = IvyUtils.INTERNAL_ORG_NAME
name = resolve_hash_name
extra_configurations = [conf for conf in confs if conf and conf != 'default']
... | python | {
"resource": ""
} |
q28105 | IvyUtils.calculate_classpath | train | def calculate_classpath(cls, targets):
"""Creates a consistent classpath and list of excludes for the passed targets.
It also modifies the JarDependency objects' excludes to contain all the jars excluded by
provides.
:param iterable targets: List of targets to collect JarDependencies and excludes from... | python | {
"resource": ""
} |
q28106 | MirroredTargetOptionMixin.get_scalar_mirrored_target_option | train | def get_scalar_mirrored_target_option(self, option_name, target):
"""Get the attribute `field_name` from `target` if set, else from this subsystem's options."""
mirrored_option_declaration | python | {
"resource": ""
} |
q28107 | Subsystem.scoped | train | def scoped(cls, optionable, removal_version=None, removal_hint=None):
"""Returns a dependency on this subsystem, scoped to `optionable`.
:param removal_version: An optional deprecation version for this scoped Subsystem dependency.
:param removal_hint: An optional hint to accompany a deprecation removal_ver... | python | {
"resource": ""
} |
q28108 | Subsystem.scoped_instance | train | def scoped_instance(cls, optionable):
"""Returns an instance of this subsystem for exclusive use by the given `optionable`.
:API: public
:param optionable: An optionable type or instance to scope this subsystem under.
:type: :class:`pants.option.optionable.Optionable`
:returns: The scoped subsyste... | python | {
"resource": ""
} |
q28109 | _ServiceState.await_paused | train | def await_paused(self, timeout=None):
"""Blocks until the service is in the Paused state, then returns True.
If a timeout is specified, the method may return False to indicate a timeout: with no timeout
it will always (eventually) return True.
Raises if the service is not currently in the Pausing stat... | python | {
"resource": ""
} |
q28110 | _ServiceState.maybe_pause | train | def maybe_pause(self, timeout=None):
"""Called by the service to indicate that it is pausable.
If the service calls this method while the state is `Pausing`, the state will transition
to `Paused`, and the service will block here until it is marked `Running` or `Terminating`.
If the state is not curren... | python | {
"resource": ""
} |
q28111 | _ServiceState.mark_pausing | train | def mark_pausing(self):
"""Requests that the service move to the Paused state, without waiting for it to do so.
Raises if the service is not currently in the Running | python | {
"resource": ""
} |
q28112 | _ServiceState.mark_running | train | def mark_running(self):
"""Moves the service to the Running state.
Raises if the service | python | {
"resource": ""
} |
q28113 | Struct.kwargs | train | def kwargs(self):
"""Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass.
This excludes fields like `extends`, `merges`, and `abstract`, which are consumed by
| python | {
"resource": ""
} |
q28114 | Struct.type_alias | train | def type_alias(self):
"""Return the type alias this target was constructed via.
For a target read from a BUILD file, this will be target alias, like 'java_library'.
For a target constructed in memory, this will be the simple class name, like 'JavaLibrary'.
The end result is that the type alias should ... | python | {
"resource": ""
} |
q28115 | compile_file | train | def compile_file(source, globals_=None):
"""Compile by saving to file and importing that.
Compiling the AST/source code this way ensures that the source code is
readable by e.g. `pdb` or `inspect`.
Args:
source: The code to compile, either as a string or as an AST.
globals_: A dictionary of variables ... | python | {
"resource": ""
} |
q28116 | compile_function | train | def compile_function(node, globals_=None):
"""Convert an AST or string into a function with inspectable source.
This function uses `compile_file` internally, but instead of returning the
entire module it will return the function only.
Args:
node: A `FunctionDef` node or a `Module` node which contains at l... | python | {
"resource": ""
} |
q28117 | autodiff_ast | train | def autodiff_ast(func, wrt, motion, mode, preserve_result, check_dims, verbose):
"""Perform AD on a single function and return the AST.
Args:
See `grad`.
Returns:
node: The AST of a module containing the adjoint and primal function
definitions.
required: A list of non-built in functions that... | python | {
"resource": ""
} |
q28118 | autodiff_tree | train | def autodiff_tree(func, wrt, motion, mode, preserve_result, check_dims,
verbose):
"""Perform AD on all functions in a call tree.
This function walks the call tree and differentiates each function in it. It
also ensures that the global namespaces that each function in the call tree
was in are ... | python | {
"resource": ""
} |
q28119 | vjp | train | def vjp(func,
wrt=(0,),
optimized=True,
check_dims=True,
preserve_result=False,
verbose=0):
"""Convenience function to produce vector-Jacobian products.
See `autodiff` for function arguments.
Uses reverse-mode joint-motion autodiff to produce the VJP.
"""
return autodi... | python | {
"resource": ""
} |
q28120 | autodiff | train | def autodiff(func,
wrt=(0,),
optimized=True,
motion='joint',
mode='reverse',
preserve_result=False,
check_dims=True,
input_derivative=INPUT_DERIVATIVE.Required,
verbose=0):
"""Build the vector-Jacobian or Jacobian-... | python | {
"resource": ""
} |
q28121 | _create_joint | train | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | python | {
"resource": ""
} |
q28122 | _create_forward | train | def _create_forward(out_node):
"""Create a user-friendly forward function.
Ensures that a single value instead of a tuple is returned if the user asked
for the gradient with respect to only one | python | {
"resource": ""
} |
q28123 | tangent | train | def tangent(f):
"""A decorator which removes the `with insert_grad_of` statement.
This allows the function to be called as usual.
Args:
f: A function
Returns:
A function with any `with insert_grad_of` context managers removed.
"""
| python | {
"resource": ""
} |
q28124 | forward | train | def forward(node, analysis):
"""Perform a given analysis on all functions within an AST."""
if not isinstance(analysis, Forward):
raise TypeError('not | python | {
"resource": ""
} |
q28125 | CFG.backlink | train | def backlink(node):
"""Given a CFG with outgoing links, create incoming links."""
seen = set()
to_see = [node]
| python | {
"resource": ""
} |
q28126 | CFG.set_head | train | def set_head(self, node):
"""Link this node to the current leaves."""
for head in self.head:
| python | {
"resource": ""
} |
q28127 | CFG.build_cfg | train | def build_cfg(cls, node):
"""Build a CFG for a function.
Args:
node: A function definition the body of which to analyze.
Returns:
A CFG object.
Raises:
TypeError: If the input is not a function definition.
"""
if not isinstance(node, gast.FunctionDef):
raise TypeError(... | python | {
"resource": ""
} |
q28128 | optimize | train | def optimize(node):
"""Perform a series of optimization passes.
This function performs a series of optimizations (dead code elimination,
constant folding, variable folding) on the given AST.
It optimizes the code repeatedly until reaching a fixed point. The fixed
point is determine roughly by checking whethe... | python | {
"resource": ""
} |
q28129 | dead_code_elimination | train | def dead_code_elimination(node):
"""Perform a simple form of dead code elimination on a Python AST.
This method performs reaching definitions analysis on all function
definitions. It then looks for the definition of variables that are not used
elsewhere and removes those definitions.
This function takes int... | python | {
"resource": ""
} |
q28130 | read_counts | train | def read_counts(node):
"""Check how many times a variable definition was used.
Args:
node: An AST to analyze.
Returns:
A dictionary from assignment nodes to the number of times the assigned to
| python | {
"resource": ""
} |
q28131 | assignment_propagation | train | def assignment_propagation(node):
"""Perform assignment propagation.
Assignment propagation is not a compiler optimization as much as a
readability optimization. If a variable name is used only once, it gets
renamed when possible e.g. `y = x; z = y` will become `z = x`.
Args:
node: The AST to optimize.
... | python | {
"resource": ""
} |
q28132 | matmul_adjoint_x | train | def matmul_adjoint_x(dz, x, y, transpose_a, transpose_b):
"""Implementation of dtfmatmul wrt x, separate for readability."""
if not transpose_a and not transpose_b:
return tf.matmul(dz, y, transpose_b=True)
elif not transpose_a and transpose_b:
return tf.matmul(dz, y)
| python | {
"resource": ""
} |
q28133 | matmul_adjoint_y | train | def matmul_adjoint_y(dz, x, y, transpose_a, transpose_b):
"""Implementation of dtfmatmul, separate for readability."""
if not transpose_a and not transpose_b:
return tf.matmul(x, dz, transpose_a=True)
elif not transpose_a and transpose_b:
return tf.matmul(dz, x, transpose_a=True)
| python | {
"resource": ""
} |
q28134 | primal_name | train | def primal_name(func, wrt):
"""Name for the primal of a function."""
if not isinstance(func, types.FunctionType):
raise TypeError(func)
varnames | python | {
"resource": ""
} |
q28135 | Namer.build | train | def build(cls, node):
"""Construct a namer object for a given function scope."""
if not | python | {
"resource": ""
} |
q28136 | Namer.valid | train | def valid(self, name):
"""Ensure a variable name is valid.
Note: Assumes variable names are ASCII, which isn't necessarily true in
Python 3.
Args:
name: A proposed variable name.
Returns:
A valid version of the name. | python | {
"resource": ""
} |
q28137 | Namer.trim | train | def trim(self, name):
"""When the name is too long, use the LHS or a random string instead."""
if len(name) > self.MAX_LENGTH and self.target:
name = self.TEMP_VAR.format(self._name(self.target))
if len(name) > self.MAX_LENGTH:
while True: | python | {
"resource": ""
} |
q28138 | Namer.unique | train | def unique(self, name):
"""Make a variable name unique by appending a number if needed."""
# Make sure the name is valid
name = self.valid(name)
# Make sure it's not too long
name = self.trim(name)
# Now make sure it's unique
unique_name = name
i = 2
| python | {
"resource": ""
} |
q28139 | array_size | train | def array_size(x, axis):
"""Calculate the size of `x` along `axis` dimensions only."""
axis_shape = x.shape if axis is None | python | {
"resource": ""
} |
q28140 | create_unbroadcast_axis | train | def create_unbroadcast_axis(shape, broadcast_shape):
"""Creates the reduction axis for unbroadcasting.
Args:
shape: A list. The shape after the broadcast operation.
broadcast_shape: A list. The original shape the array being unbroadcast
had.
Returns:
A list. The axes along which the array needs... | python | {
"resource": ""
} |
q28141 | unreduce_array | train | def unreduce_array(array, shape, axis, keepdims):
"""Reverse summing over a dimension, NumPy implementation.
Args:
array: The array that was reduced.
shape: The original shape of the array before reduction.
axis: The axis or axes that were summed.
keepdims: Whether these axes were kept as singleton... | python | {
"resource": ""
} |
q28142 | astype | train | def astype(array, y):
"""A functional form of the `astype` method.
Args:
array: The array or number to cast.
y: An array or number, as the input, whose type should be that of array.
Returns:
An array or number | python | {
"resource": ""
} |
q28143 | init_grad | train | def init_grad(obj, allow_lazy_initializer=False):
"""Initialize the gradient for an object.
Args:
obj: The object to initialize the gradient for, can be either a number,
array, tuple, list, or dictionary.
allow_lazy_initializer: Whether to allow using the ZeroGradient wrapper,
for efficiency.
... | python | {
"resource": ""
} |
q28144 | register_add_grad | train | def register_add_grad(left_type, right_type, add_grad_function):
"""Register a new gradient adder supporting the given types.
Gradient adders are used to add (in the sense of arithmetic addition)
intermediate adjoint and tangent variables.
TODO: Link to the document explaining the overall terminology and mecha... | python | {
"resource": ""
} |
q28145 | add_grad | train | def add_grad(left, right):
"""Recursively add the gradient of two objects.
Args:
left: The left value to add. Can be either an array, a number, list or
dictionary.
right: The right value. Must be of the same type (recursively) as the left.
Returns:
The sum of the two gradients, which will of... | python | {
"resource": ""
} |
q28146 | register_shape_checker | train | def register_shape_checker(left_type, right_type, shape_checker_function):
"""Register a new shape checking function supporting given types.
Shape checkers are primarily used to make sure that the seed derivatives
passed into generated autodiff functions match their corresponding
primal values.
Args:
le... | python | {
"resource": ""
} |
q28147 | shapes_match | train | def shapes_match(a, b):
"""Recursively check if shapes of object `a` and `b` match.
Will walk lists, tuples and dicts.
Args:
a: object of type (numpy.ndarray,tf.Tensor,list,tuple,dict)
to check for matching shapes against `b`.
b: object to check for matching shape against `a`.
Returns:
A ... | python | {
"resource": ""
} |
q28148 | pop_stack | train | def pop_stack(stack, op_id):
"""Proxy of pop, where we know we're popping a stack off of a stack.
We know that we don't need to differentiate through this.
See pop() for more.
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimi... | python | {
"resource": ""
} |
q28149 | push_stack | train | def push_stack(stack, substack, op_id):
"""Proxy of push, where we know we're pushing a stack onto a stack.
Used when differentiating call trees,where sub-functions get their own stack.
See push() for more.
Args:
stack: The stack object, which must support appending values.
substack: The stack to appe... | python | {
"resource": ""
} |
q28150 | grad_dot | train | def grad_dot(dy, x1, x2):
"""Gradient of NumPy dot product w.r.t. to the left hand side.
Args:
dy: The gradient with respect to the output.
x1: The left hand side of the `numpy.dot` function.
x2: The right hand side
Returns:
The gradient with respect to `x1` i.e. `x2.dot(dy.T)` with all the
... | python | {
"resource": ""
} |
q28151 | trace_grad | train | def trace_grad(fn, args):
"""Trace a function, and return a VJP and the function's output."""
from | python | {
"resource": ""
} |
q28152 | get_module_functions | train | def get_module_functions(modules):
"""Finds functions that do not have implemented derivatives.
Args:
modules: A list of Python modules. Functions contained in these modules
will be checked for membership in 'implemented', and if not found,
will be added to an 'unimplemented' set
implemente... | python | {
"resource": ""
} |
q28153 | validate | train | def validate(node, source):
"""Call this function to validate an AST."""
# TODO: leaving strict checking off to support insert_grad_of
| python | {
"resource": ""
} |
q28154 | get_name | train | def get_name(node):
"""Get the name of a variable.
Args:
node: A `Name`, `Subscript` or `Attribute` node.
Returns:
The name of the variable e.g. `'x'` for `x`, `x.i` and `x[i]`.
"""
if isinstance(node, gast.Name):
| python | {
"resource": ""
} |
q28155 | get_updated | train | def get_updated(node):
"""Return the variable names created or mutated by this statement.
This function considers assign statements, augmented assign statements, and
the targets of for loops, as well as function arguments.
For example, `x[0] = 2` will return `x`, `x, y = 3, 4` will return `x` and
`y`, `for ... | python | {
"resource": ""
} |
q28156 | copy_node | train | def copy_node(node):
"""Copy a node but keep its annotations intact."""
if not isinstance(node, gast.AST):
return [copy_node(n) for n in node]
new_node = | python | {
"resource": ""
} |
q28157 | is_insert_grad_of_statement | train | def is_insert_grad_of_statement(node):
"""Check whether a context manager calls `insert_grad_of`.
Args:
node: The context manager node.
Returns:
Whether or not this node contains `insert_grad_of` calls.
Raises:
ValueError: If the `insert_grad_of` calls are mixed with other calls.
"""
tangent_... | python | {
"resource": ""
} |
q28158 | add_comment | train | def add_comment(node, text, location='above'):
"""Add a comment to the given node.
If the `SourceWithCommentGenerator` class is used these comments will be
output as part of the source code.
Note that a node can only contain one comment. Subsequent calls to
`add_comment` will ovverride the existing comments... | python | {
"resource": ""
} |
q28159 | remove_repeated_comments | train | def remove_repeated_comments(node):
"""Remove comments that repeat themselves.
Multiple statements might be annotated with the same comment. This way if one
of the statements is deleted during optimization passes, the comment won't be
lost. This pass removes sequences of identical comments, leaving only the
... | python | {
"resource": ""
} |
q28160 | create_grad | train | def create_grad(node, namer, tangent=False):
"""Given a variable, create a variable for the gradient.
Args:
node: A node to create a gradient for, can be a normal variable (`x`) or a
subscript (`x[i]`).
namer: The namer object which will determine the name to use for the
gradient.
tange... | python | {
"resource": ""
} |
q28161 | create_temp_grad | train | def create_temp_grad(node, namer, tangent=False):
"""Create a variable to store partial gradients.
Args:
node: See `create_grad`.
namer: See `create_grad`.
tangent: See `create_grad`.
Returns:
node: See `create_grad`. Returns a node representing the partial gradient.
Note that this is al... | python | {
"resource": ""
} |
q28162 | create_temp | train | def create_temp(node, namer):
"""Create a temporary variable.
Args:
node: Create a temporary variable to store this variable in.
namer: A naming object that guarantees the names are unique.
Returns:
node: See `create_grad`. Returns a temporary variable, which is always a
simple variable anno... | python | {
"resource": ""
} |
q28163 | forward_ad | train | def forward_ad(node, wrt, preserve_result=False, check_dims=True):
"""Perform forward-mode AD on an AST.
This function analyses the AST to determine which variables are active and
proceeds by taking the naive derivative. Before returning the primal and
adjoint it annotates push and pop statements as such.
A... | python | {
"resource": ""
} |
q28164 | to_source | train | def to_source(node, indentation=' ' * 4):
"""Return source code of a given AST."""
if isinstance(node, gast.AST):
node = gast.gast_to_ast(node)
generator = SourceWithCommentGenerator(indentation, False,
| python | {
"resource": ""
} |
q28165 | parse_function | train | def parse_function(fn):
"""Get the source of a function and return its AST."""
try:
return parse_string(inspect.getsource(fn))
except (IOError, OSError) as e:
raise ValueError(
| python | {
"resource": ""
} |
q28166 | quote | train | def quote(src_string, return_expr=False):
"""Go from source code to AST nodes.
This function returns a tree without enclosing `Module` or `Expr` nodes.
Args:
src_string: The source code to parse.
return_expr: Whether or not to return a containing expression. This can be
set to `True` if the resu... | python | {
"resource": ""
} |
q28167 | get_push_pop | train | def get_push_pop():
"""Create pop and push nodes that are linked.
Returns:
A push and pop node which have `push_func` and `pop_func` annotations
respectively, identifying them as such. They also have a `pop` and
`push` annotation respectively, which links the push node to the pop
node a... | python | {
"resource": ""
} |
q28168 | get_push_pop_stack | train | def get_push_pop_stack():
"""Create pop and push nodes for substacks that are linked.
Returns:
A push and pop node which have `push_func` and `pop_func` annotations
respectively, identifying them as such. They also have a `pop` and
`push` annotation respectively, which links the push node to th... | python | {
"resource": ""
} |
q28169 | reverse_ad | train | def reverse_ad(node, wrt, preserve_result, check_dims):
"""Perform reverse-mode AD on an AST.
This function analyses the AST to determine which variables are active and
proceeds by taking the naive derivative. Before returning the primal and
adjoint it annotates push and pop statements as such.
Args:
no... | python | {
"resource": ""
} |
q28170 | store_state | train | def store_state(node, reaching, defined, stack):
"""Push the final state of the primal onto the stack for the adjoint.
Python's scoping rules make it possible for variables to not be defined in
certain blocks based on the control flow path taken at runtime. In order to
make sure we don't try to push non-existi... | python | {
"resource": ""
} |
q28171 | split | train | def split(node, stack):
"""Carry over the state from the primal to the adjoint.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
stack: The stack node to use for storing and restoring state.
Returns:
func: A `Module` node with two function de... | python | {
"resource": ""
} |
q28172 | joint | train | def joint(node):
"""Merge the bodies of primal and adjoint into a single function.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
func: A `Module` node with a single function definition containing the
combined primal and adjoin... | python | {
"resource": ""
} |
q28173 | _fix | train | def _fix(node):
"""Fix the naive construction of the adjont.
See `fixes.py` for details.
This function also returns the result of reaching definitions analysis so
that `split` mode can use this to carry over the state from primal to
adjoint.
Args:
node: A module with the primal and adjoint function d... | python | {
"resource": ""
} |
q28174 | ReverseAD.is_active | train | def is_active(self, node):
"""Checks whether a statement is active.
An assignment is active when its right hand side contains active
variables.
Args:
node: an instance of gast.Assign
Returns:
Whether the statement is active.
"""
# Special case: If the right hand side is a pop ... | python | {
"resource": ""
} |
q28175 | ReverseAD.visit_statements | train | def visit_statements(self, nodes):
"""Generate the adjoint of a series of statements."""
primals, adjoints = [], collections.deque()
for node in nodes:
primal, adjoint = self.visit(node)
if not isinstance(primal, list):
primal = [primal]
if not isinstance(adjoint, list):
ad... | python | {
"resource": ""
} |
q28176 | ReverseAD.primal_and_adjoint_for_tracing | train | def primal_and_adjoint_for_tracing(self, node):
"""Build the primal and adjoint of a traceable function.
Args:
node: ast.Call node of a function we wish to trace, instead of transform
Returns:
primal: new ast.Assign node to replace the original primal call
adjoint: new ast.Assign node us... | python | {
"resource": ""
} |
q28177 | TreeTransformer.prepend | train | def prepend(self, node):
"""Prepend a statement to the current statement.
Note that multiple calls to prepend will result in the last statement to be
prepended to end up at the top.
Args:
node: The statement to prepend.
Raises:
ValueError: If | python | {
"resource": ""
} |
q28178 | TreeTransformer.append | train | def append(self, node):
"""Append a statement to the current statement.
Note that multiple calls to append will result in the last statement to be
appended to end up at the bottom.
Args:
node: The statement to append.
Raises:
ValueError: If | python | {
"resource": ""
} |
q28179 | TreeTransformer.insert_top | train | def insert_top(self, node):
"""Insert statements at the top of the function body.
Note that multiple calls to `insert_top` will result in the statements
being prepended in that order; this is different behavior from `prepend`.
Args:
node: The statement to prepend.
Raises:
| python | {
"resource": ""
} |
q28180 | TreeTransformer.prepend_block | train | def prepend_block(self, node, reverse=False):
"""Prepend a statement to the current block.
Args:
node: The statement to prepend.
reverse: When called multiple times, this flag determines whether the
statement should be prepended or appended to the already inserted
statements.
... | python | {
"resource": ""
} |
q28181 | TreeTransformer.append_block | train | def append_block(self, node, reverse=False):
"""Append a statement to the current block.
Args:
node: The statement to prepend.
reverse: When called multiple times, this flag determines whether the
statement should be prepended or appended to the already inserted
statements.
... | python | {
"resource": ""
} |
q28182 | TreeTransformer.visit_statements | train | def visit_statements(self, nodes):
"""Visit a series of nodes in a node body.
This function is factored out so that it can be called recursively on
statements that are appended or prepended. This allows e.g. a nested
expression to prepend a statement, and that statement can prepend a
statement agai... | python | {
"resource": ""
} |
q28183 | resolve_calls | train | def resolve_calls(func):
"""Parse a function into an AST with function calls resolved.
Since the calls are resolved using the global and local namespace of the
function it means that procedural parameters (i.e. functions passed as
arguments) won't be resolved.
Similarly, functions defined inside of the func... | python | {
"resource": ""
} |
q28184 | find_stacks | train | def find_stacks(node, strict=False):
"""Find pushes and pops to the stack and annotate them as such.
Args:
node: An AST node that might contain stack pushes and pops.
strict: A boolean indicating whether to stringently test whether each
push and pop are matched. This is not always possible when tak... | python | {
"resource": ""
} |
q28185 | unused | train | def unused(node):
"""Find unused definitions that can be remove.
This runs reaching definitions analysis followed by a walk over the AST to
find all variable definitions that are not used later on.
Args:
node: The AST of e.g. a function body to find unused variable definitions.
Returns:
unused: Aft... | python | {
"resource": ""
} |
q28186 | Unused.unused | train | def unused(self):
"""Calculate which AST nodes are unused.
Note that we have to take special care in the case of
x,y = f(z) where x is used later, but y is not."""
unused = self.definitions - self.used
# Filter (variable_name,node) pairs that should be removed, | python | {
"resource": ""
} |
q28187 | package_config | train | def package_config():
"""Use pkg-config to get library build parameters and tesseract version."""
p = subprocess.Popen(['pkg-config', '--exists', '--atleast-version={}'.format(_TESSERACT_MIN_VERSION),
'--print-errors', 'tesseract'],
stderr=subprocess.PIPE)
... | python | {
"resource": ""
} |
q28188 | get_tesseract_version | train | def get_tesseract_version():
"""Try to extract version from tesseract otherwise default min version."""
config = {'libraries': ['tesseract', 'lept']}
try:
p = subprocess.Popen(['tesseract', '-v'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout_version, version = p.communicate()
... | python | {
"resource": ""
} |
q28189 | get_build_args | train | def get_build_args():
"""Return proper build parameters."""
try:
build_args = package_config()
except Exception as e:
if isinstance(e, OSError):
if e.errno != errno.ENOENT:
_LOGGER.warn('Failed to run pkg-config: {}'.format(e))
else:
_LOGGER.wa... | python | {
"resource": ""
} |
q28190 | MultiqcModule.parse_star_report | train | def parse_star_report (self, raw_data):
""" Parse the final STAR log file. """
regexes = {
'total_reads': r"Number of input reads \|\s+(\d+)",
'avg_input_read_length': r"Average input read length \|\s+([\d\.]+)",
'uniquely_mapped': ... | python | {
"resource": ""
} |
q28191 | MultiqcModule.parse_star_genecount_report | train | def parse_star_genecount_report(self, f):
""" Parse a STAR gene counts output file """
# Three numeric columns: unstranded, stranded/first-strand, stranded/second-strand
keys = [ 'N_unmapped', 'N_multimapping', 'N_noFeature', 'N_ambiguous' ]
unstranded = { 'N_genes': 0 }
first_st... | python | {
"resource": ""
} |
q28192 | MultiqcModule.star_stats_table | train | def star_stats_table(self):
""" Take the parsed stats from the STAR report and add them to the
basic stats table at the top of the report """
headers = OrderedDict()
headers['uniquely_mapped_percent'] = {
'title': '% Aligned',
'description': '% Uniquely mapped re... | python | {
"resource": ""
} |
q28193 | MultiqcModule.star_genecount_chart | train | def star_genecount_chart (self):
""" Make a plot for the ReadsPerGene output """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['N_genes'] = { 'color': '#2f7ed8', 'name': 'Overlapping Genes' }
keys['N_noFeature'] = { 'color': '#0d233... | python | {
"resource": ""
} |
q28194 | MultiqcModule.mirtrace_length_plot | train | def mirtrace_length_plot(self):
""" Generate the miRTrace Read Length Distribution"""
data = dict()
for s_name in self.length_data:
try:
data[s_name] = {int(d): int(self.length_data[s_name][d]) for d in self.length_data[s_name]}
except KeyError:
... | python | {
"resource": ""
} |
q28195 | MultiqcModule.mirtrace_rna_categories | train | def mirtrace_rna_categories(self):
""" Generate the miRTrace RNA Categories"""
# Specify the order of the different possible categories
keys = OrderedDict()
keys['reads_mirna'] = { 'color': '#33a02c', 'name': 'miRNA' }
keys['reads_rrna'] = { 'color': '#ff7f00', 'n... | python | {
"resource": ""
} |
q28196 | MultiqcModule.mirtrace_contamination_check | train | def mirtrace_contamination_check(self):
""" Generate the miRTrace Contamination Check"""
# A library of 24 colors. Should be enough for this plot
color_lib = ['rgb(166,206,227)', 'rgb(31,120,180)', 'rgb(178,223,138)', 'rgb(51,160,44)', 'rgb(251,154,153)', 'rgb(227,26,28)', 'rgb(253,191,111)', '... | python | {
"resource": ""
} |
q28197 | MultiqcModule.mirtrace_complexity_plot | train | def mirtrace_complexity_plot(self):
""" Generate the miRTrace miRNA Complexity Plot"""
data = dict()
for s_name in self.complexity_data:
try:
data[s_name] = {int(self.complexity_data[s_name][d]) : int(d) for d in self.complexity_data[s_name]}
except KeyEr... | python | {
"resource": ""
} |
q28198 | StatsReportMixin.bcftools_stats_genstats_headers | train | def bcftools_stats_genstats_headers(self):
""" Add key statistics to the General Stats table """
stats_headers = OrderedDict()
stats_headers['number_of_records'] = {
'title': 'Vars',
'description': 'Variations total',
'min': 0, 'format': '{:,.0f}',
}
... | python | {
"resource": ""
} |
q28199 | MultiqcModule.parse_hicup_logs | train | def parse_hicup_logs(self, f):
""" Parse a HiCUP summary report """
if not f['fn'].endswith('.txt'):
return None
header = []
lines = f['f'].splitlines()
for l in lines:
s = l.split("\t")
if len(header) == 0:
if s[0] != 'File':
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.