code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
declared_symbols = self.declared_symbols return set( s for s in self.referenced_symbols if s not in declared_symbols)
def global_symbols(self)
These are symbols that have been referenced, but not declared within this scope or any parent scopes.
8.897951
5.320036
1.672536
result = set() for child in self.children: result |= ( child.global_symbols | child.global_symbols_in_children) return result
def global_symbols_in_children(self)
This is based on all children referenced symbols that have not been declared. The intended use case is to ban the symbols from being used as remapped symbol values.
4.286072
3.626099
1.182006
if self._closed: raise ValueError('scope is already marked as closed') # By letting parent know which symbols this scope has leaked, it # will let them reserve all lowest identifiers first. if self.parent: for symbol, c in self.leaked_referenced_symbols...
def close(self)
Mark the scope as closed, i.e. all symbols have been declared, and no further declarations should be done.
13.914095
9.73686
1.429012
# In practice, and as a possible optimisation, the parent's # remapped symbols table can be merged into this instance, but # this bloats memory use and cause unspecified reservations that # may not be applicable this or any child scope. So for clarity # and purity of r...
def _reserved_symbols(self)
Helper property for the build_remap_symbols method. This property first resolves _all_ local references from parents, skipping all locally declared symbols as the goal is to generate a local mapping for them, but in a way not to shadow over any already declared symbols from parents, and...
21.723598
17.589643
1.235022
if not children_only: replacement = name_generator(skip=(self._reserved_symbols)) for symbol, c in reversed(sorted( self.referenced_symbols.items(), key=itemgetter(1, 0))): if symbol not in self.local_declared_symbols: con...
def build_remap_symbols(self, name_generator, children_only=True)
This builds the replacement table for all the defined symbols for all the children, and this scope, if the children_only argument is False.
4.66072
4.633737
1.005823
if cls is None: cls = type(self) nested_scope = cls(node, self) self.children.append(nested_scope) return nested_scope
def nest(self, node, cls=None)
Create a new nested scope that is within this instance, binding the provided node to it.
3.8119
2.693962
1.414979
if symbol != self.catch_symbol: self.parent.declare(symbol)
def declare(self, symbol)
Nothing gets declared here - it's the parents problem, except for the case where the symbol is the one we have here.
12.365655
7.240736
1.70779
if symbol == self.catch_symbol: self.catch_symbol_usage += count else: self.parent.reference(symbol, count)
def reference(self, symbol, count=1)
However, if referenced, ensure that the counter is applied to the catch symbol.
6.983999
4.543645
1.537092
replacement = name_generator(skip=(self._reserved_symbols)) self.remapped_symbols[self.catch_symbol] = next(replacement) # also to continue down the children. for child in self.children: child.build_remap_symbols(name_generator, False)
def build_remap_symbols(self, name_generator, children_only=None)
The children_only flag is inapplicable, but this is included as the Scope class is defined like so. Here this simply just place the catch symbol with the next replacement available.
9.79731
6.774981
1.446101
# the identifier node itself will be mapped to the current scope # for the resolve to work # This should probably WARN about the node object being already # assigned to an existing scope that isn't current_scope. self.identifiers[node] = self.current_scope self....
def register_reference(self, dispatcher, node)
Register this identifier to the current scope, and mark it as referenced in the current scope.
13.867248
11.76165
1.179022
# as opposed to the previous one, only add the value of the # identifier itself to the scope so that it becomes reserved. self.current_scope.reference(node.identifier.value)
def shadow_reference(self, dispatcher, node)
Only simply make a reference to the value in the current scope, specifically for the FuncBase type.
16.595066
13.39175
1.239201
scope = self.identifiers.get(node) if not scope: return node.value return scope.resolve(node.value)
def resolve(self, dispatcher, node)
For the given node, resolve it into the scope it was declared at, and if one was found, return its value.
6.153675
4.166018
1.477112
deferrable_handlers = { Declare: self.declare, Resolve: self.register_reference, } layout_handlers = { PushScope: self.push_scope, PopScope: self.pop_scope, PushCatch: self.push_catch, # should really be different,...
def walk(self, dispatcher, node)
Walk through the node with a custom dispatcher for extraction of details that are required.
7.767738
8.05125
0.964787
self.global_scope.close() name_generator = NameGenerator(skip=self.reserved_keywords) self.global_scope.build_remap_symbols( name_generator, children_only=not self.obfuscate_globals, )
def finalize(self)
Finalize the run - build the name generator and use it to build the remap symbol tables.
12.406886
7.336478
1.691123
self.walk(dispatcher, node) self.finalize() return node
def prewalk_hook(self, dispatcher, node)
This is for the Unparser to use as a prewalk hook.
8.918234
8.831592
1.00981
"take out the trash" src_dir = easy.options.setdefault("docs", {}).get('src_dir', None) if src_dir is None: src_dir = 'src' if easy.path('src').exists() else '.' with easy.pushd(src_dir): for pkg in set(easy.options.setup.packages) | set(("tests",)): for filename in glob.glo...
def clean()
take out the trash
8.014012
7.160873
1.119139
setattr(self.generate_info, which + '_low', low) setattr(self.generate_info, which + '_high', high) setattr(self.generate_info, 'num_' + which, num) setattr(self.generate_info, which + 'val_name', name) if scale not in ['lin', 'log']: raise ValueError('{} sc...
def _set_grid_info(self, which, low, high, num, scale, name)
Set the grid values for x or y. Create information for the grid of x and y values. Args: which (str): `x` or `y`. low/high (float): Lowest/highest value for the axis. num (int): Number of points on axis. scale (str): Scale of the axis. Choices are 'log' ...
2.589427
2.616919
0.989495
self._set_grid_info('y', y_low, y_high, num_y, yscale, yval_name) return
def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name)
Set the grid values for y. Create information for the grid of y values. Args: num_y (int): Number of points on axis. y_low/y_high (float): Lowest/highest value for the axis. yscale (str): Scale of the axis. Choices are 'log' or 'lin'. yval_name (str): Na...
2.256835
2.958338
0.762872
self._set_grid_info('x', x_low, x_high, num_x, xscale, xval_name) return
def set_x_grid_info(self, x_low, x_high, num_x, xscale, xval_name)
Set the grid values for x. Create information for the grid of x values. Args: num_x (int): Number of points on axis. x_low/x_high (float): Lowest/highest value for the axis. xscale (str): Scale of the axis. Choices are 'log' or 'lin'. xval_name (str): Na...
2.194251
2.947698
0.744395
if is_wd_background: self.sensitivity_input.wd_noise = name self.sensitivity_input.wd_noise_type_in = noise_type else: if 'sensitivity_curves' not in self.sensitivity_input.__dict__: self.sensitivity_input.sensitivity_curves = [] ...
def add_noise_curve(self, name, noise_type='ASD', is_wd_background=False)
Add a noise curve for generation. This will add a noise curve for an SNR calculation by appending to the sensitivity_curves list within the sensitivity_input dictionary. The name of the noise curve prior to the file extension will appear as its label in the final output dataset. Theref...
2.168728
2.059631
1.052969
if isinstance(wd_noise, bool): wd_noise = str(wd_noise) if wd_noise.lower() == 'yes' or wd_noise.lower() == 'true': wd_noise = 'True' elif wd_noise.lower() == 'no' or wd_noise.lower() == 'false': wd_noise = 'False' elif wd_noise.lower() == 'b...
def set_wd_noise(self, wd_noise)
Add White Dwarf Background Noise This adds the White Dwarf (WD) Background noise. This can either do calculations with, without, or with and without WD noise. Args: wd_noise (bool or str, optional): Add or remove WD background noise. First option is to have only cal...
2.223499
2.018182
1.101733
self.parallel_input.num_processors = num_processors self.parallel_input.num_splits = num_splits self.parallel_input.verbose = verbose return
def set_generation_type(self, num_processors=-1, num_splits=1000, verbose=-1)
Change generation type. Choose weather to generate the data in parallel or on a single processor. Args: num_processors (int or None, optional): Number of parallel processors to use. If ``num_processors==-1``, this will use multiprocessing module and use avai...
2.528843
2.966748
0.852396
if isinstance(sig_type, str): sig_type = [sig_type] self.snr_input.signal_type = sig_type return
def set_signal_type(self, sig_type)
Set the signal type of interest. Sets the signal type for which the SNR is calculated. This means inspiral, merger, and/or ringdown. Args: sig_type (str or list of str): Signal type desired by user. Choices are `ins`, `mrg`, `rd`, `all` for circular waveforms create...
4.761167
4.465307
1.066257
output_dict = {} output_dict['general'] = self._iterate_through_class(self.general.__dict__) output_dict['generate_info'] = self._iterate_through_class(self.generate_info.__dict__) output_dict['sensitivity_input'] = (self._iterate_through_class( self.sensitivity_inpu...
def return_dict(self)
Output dictionary for :mod:`gwsnrcalc.generate_contour_data` input. Iterates through the entire MainContainer class turning its contents into dictionary form. This dictionary becomes the input for :mod:`gwsnrcalc.generate_contour_data`. If `print_input` attribute is True, the entire di...
2.522111
2.25961
1.116171
return ''.join(chunk.text for chunk in pretty_printer(indent_str)(ast))
def pretty_print(ast, indent_str=' ')
Simple pretty print function; returns a string rendering of an input AST of an ES5 Program. arguments ast The AST to pretty print indent_str The string used for indentations. Defaults to two spaces.
11.495609
14.906932
0.771159
active_rules = [rules.minify(drop_semi=drop_semi)] if obfuscate: active_rules.append(rules.obfuscate( obfuscate_globals=obfuscate_globals, shadow_funcname=shadow_funcname, reserved_keywords=(Lexer.keywords_dict.keys()) )) return Unparser(rules=active...
def minify_printer( obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False)
Construct a minimum printer. Arguments obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to False. obfuscate_globals Also do the same to identifiers nested on the global scope; do ...
3.981164
4.82126
0.825752
return ''.join(chunk.text for chunk in minify_printer( obfuscate, obfuscate_globals, shadow_funcname, drop_semi)(ast))
def minify_print( ast, obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False)
Simple minify print function; returns a string rendering of an input AST of an ES5 program Arguments ast The AST to minify print obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to Fa...
4.49527
7.487853
0.600342
# shift in the sign to least significant bit raw = (-i << 1) + 1 if i < 0 else i << 1 if raw < VLQ_MULTI_CHAR: # short-circuit simple case as it doesn't need continuation return INT_B64[raw] result = [] while raw: # assume continue result.append(raw & VLQ_BASE_...
def encode_vlq(i)
Encode integer `i` into a VLQ encoded string.
7.426054
7.235415
1.026348
ints = [] i = 0 shift = 0 for c in s: raw = B64_INT[c] cont = VLQ_CONT & raw i = ((VLQ_BASE_MASK & raw) << shift) | i shift += VLQ_SHIFT if not cont: sign = -1 if 1 & i else 1 ints.append((i >> 1) * sign) i = 0 ...
def decode_vlqs(s)
Decode str `s` into a list of integers.
5.158751
5.07551
1.016401
# Ensure SECRET_KEY is set. SECRET_KEY = app.config.get('SECRET_KEY') if SECRET_KEY is None: app.config['SECRET_KEY'] = 'CHANGE_ME' warnings.warn( 'Set configuration variable SECRET_KEY with random string', UserWarning)
def init_app(self, app)
Initialize Flask application.
3.933791
4.064664
0.967802
# Fails when "json" is missing and "simplejson" is not installed either try: import json # pylint: disable=F0401 return json except ImportError: try: import simplejson # pylint: disable=F0401 return simplejson except ImportError as exc: ...
def require_json()
Load the best available json library on demand.
4.676759
3.964906
1.179538
primes = self.primes nextPrime = primes[-1]+1 while(len(primes)<N): maximum = nextPrime * nextPrime prime = 1 for i in primes: if i > maximum: break if nextPrime % i == 0: prime =...
def _findNextPrime(self, N)
Generate the first N primes
2.837697
2.679108
1.059195
easy.error("ERROR: '%s' is not a virtualenv" % (sys.executable,)) sys.exit(1) for bindir in ("bin", "Scripts"): bindir = os.path.join(sys.prefix, bindir) if os.path.exists(bindir): if name: bin_ext = os.path.splitext(sys.executable)[1] if sys.platform == ...
def venv_bin(name=None): # pylint: disable=inconsistent-return-statements if not hasattr(sys, "real_prefix")
Get the directory for virtualenv stubs, or a full executable path if C{name} is provided.
2.848687
2.874485
0.991025
args = '" "'.join(i.replace('"', r'\"') for i in args) easy.sh('"%s" "%s"' % (venv_bin(cmd), args))
def vsh(cmd, *args, **kw)
Execute a command installed into the active virtualenv.
8.110308
7.620341
1.064297
tools = getattr(easy.options, "tools", {}) for dependency in iterutil.flatten(dependencies): dependency = tools.get(dependency, dependency) try: pkg_resources.require(dependency) except pkg_resources.DistributionNotFound: vsh("pip", "install", "-q", dependenc...
def install_tools(dependencies)
Install a required tool before using it, if it's missing. Note that C{dependencies} can be a distutils requirement, or a simple name from the C{tools} task configuration, or a (nested) list of such requirements.
5.578749
5.091338
1.095733
def entangle(task): "Decorator wrapper." if not isinstance(task, tasks.Task): task = tasks.Task(task) def tool_task(*args, **kw): "Install requirements, then call original task." install_tools(dependencies) return task_body(*args, **kw) ...
def task_requires(*dependencies)
A task decorator that ensures a distutils dependency (or a list thereof) is met before that task is executed.
6.315063
6.531354
0.966884
packages = set(easy.options.setup.packages) for pkg in list(packages): packages -= set(p for p in packages if str(p).startswith(pkg + '.')) return list(sorted(packages))
def toplevel_packages()
Get package list, without sub-packages.
7.122168
6.220012
1.145041
# Find the image size and midpoint of the image imagesize = self.image.get_size() imagemidp = (int(imagesize[0] * 0.5), int(imagesize[1] * 0.5)) # if a midpoint arguement is passed, set the pos to the top left pixel # such that the position passed in is in the middle o...
def set_position(self, position, midpoint=False, surface=None)
This method allows the button to be moved manually and keep the click on functionality. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: position - This is the x, y position of the top left corner of the button. (defining po...
3.710831
3.331143
1.113981
if mid: imagesize = self.image.get_size() imagemidp = (int(imagesize[0] * 0.5), int(imagesize[1] * 0.5)) if mid == 'x': offset = (offset[0] - imagemidp[0], offset[1]) if mid == 'y': offset = (offset[0], offset[1] - imagemi...
def set_offset(self, offset, mid=None)
This method will allow the menu to be placed anywhere in the open window instead of just the upper left corner. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: offset - This is the x,y tuple of the position that you want to move the...
2.083625
1.876031
1.110656
widget_status_list = [] for i in self.widgetlist: widget_status_list += [[i.name, i.status]] return widget_status_list
def widget_status(self)
This method will return the status of all of the widgets in the widget list
3.867322
3.213847
1.203331
# If a music file was passed, start playing it on repeat if self.music is not None: pygame.mixer.music.play(-1) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit...
def update(self, screen, clock)
Event handling loop for the menu
2.782248
2.74251
1.01449
# Initialize the screen class BaseScreen.__init__(self, self.size, self.background) # Determine the mid position of the given screen size and the # y button height xmid = self.size[0]//2 # Create the header text Linesoftext(text, (xmid, 40), xmid=True, ...
def Screens(self, text, prog, screen, clock)
Prog = 0 for first page, 1 for middle pages, 2 for last page
4.80612
4.667387
1.029724
commerce_id = os.getenv('TBK_COMMERCE_ID') commerce_key = os.getenv('TBK_COMMERCE_KEY') commerce_testing = os.getenv('TBK_COMMERCE_TESTING') == 'True' if not commerce_testing: if commerce_id is None: raise ValueError("create_commerce needs TBK_COMMER...
def create_commerce()
Creates commerce from environment variables ``TBK_COMMERCE_ID``, ``TBK_COMMERCE_KEY`` or for testing purposes ``TBK_COMMERCE_TESTING``.
2.240247
1.802587
1.242796
''' Returns a string with the ``TBK_CONFIG.dat``. :param confirmation_url: URL where callback is made. ''' config = ( "IDCOMERCIO = {commerce_id}\n" "MEDCOM = 1\n" "TBK_KEY_ID = 101\n" "PARAMVERIFCOM = 1\n" "URLCGICOM =...
def get_config_tbk(self, confirmation_url)
Returns a string with the ``TBK_CONFIG.dat``. :param confirmation_url: URL where callback is made.
4.571678
4.111921
1.111811
def indentation_rule(): inst = Indentator(indent_str) return {'layout_handlers': { Indent: inst.layout_handler_indent, Dedent: inst.layout_handler_dedent, Newline: inst.layout_handler_newline, OptionalNewline: inst.layout_handler_newline_optional...
def indent(indent_str=None)
An example indentation ruleset.
4.828501
4.517648
1.068808
if 'lang' not in request.GET: return False return not any(request.path.endswith(url) for url in self.exempt_urls)
def _is_lang_change(self, request)
Return True if the lang param is present and URL isn't exempt.
4.999022
3.093721
1.61586
if match.startswith('--'): names.append(match[2:]) elif match.startswith('-'): names.append(match[1:]) elif positional: # positional has already been filled names.append(match) else: # first p...
def add(self, *matches, **kw): # kw=default=None, boolean=False '''Add an argument; this is optional, and mostly useful for setting up aliases or setting boolean=True Apparently `def add(self, *matches, default=None, boolean=False):` is invalid syntax in Python. Not only is this absolutely ridiculous,...
Add an argument; this is optional, and mostly useful for setting up aliases or setting boolean=True Apparently `def add(self, *matches, default=None, boolean=False):` is invalid syntax in Python. Not only is this absolutely ridiculous, but the alternative `def add(self, default=None, boolean=False, *matches):`...
5.042037
4.155815
1.213249
lineno = next(parser.stream).lineno if parser.stream.skip_if('name:short'): parser.stream.skip(1) short = parser.parse_expression() else: short = nodes.Const(False) result = self.call_method('_commit_hash', [short], [], lineno=lineno) ...
def parse(self, parser)
Main method to render data into the template.
4.244158
4.057348
1.046043
for item in nested: if hasattr(item, "next") or isinstance(item, containers): for subitem in flatten(item): yield subitem else: yield item
def flatten(nested, containers=(list, tuple))
Flatten a nested list by yielding its scalar items.
2.829898
2.496463
1.133563
current['processors'] = tuple( [p for p in current['processors'] if p not in exclude] ) + tuple(append) return current['processors']
def get_template_context_processors(exclude=(), append=(), current={'processors': TEMPLATE_CONTEXT_PROCESSORS})
Returns TEMPLATE_CONTEXT_PROCESSORS without the processors listed in exclude and with the processors listed in append. The use of a mutable dict is intentional, in order to preserve the state of the TEMPLATE_CONTEXT_PROCESSORS tuple across multiple settings files.
2.769262
4.04255
0.685028
current['middleware'] = tuple( [m for m in current['middleware'] if m not in exclude] ) + tuple(append) return current['middleware']
def get_middleware(exclude=(), append=(), current={'middleware': MIDDLEWARE_CLASSES})
Returns MIDDLEWARE_CLASSES without the middlewares listed in exclude and with the middlewares listed in append. The use of a mutable dict is intentional, in order to preserve the state of the MIDDLEWARE_CLASSES tuple across multiple settings files.
3.027761
3.938437
0.768772
current['apps'] = tuple( [a for a in current['apps'] if a not in exclude] ) + tuple(append) return current['apps']
def get_apps(exclude=(), append=(), current={'apps': INSTALLED_APPS})
Returns INSTALLED_APPS without the apps listed in exclude and with the apps listed in append. The use of a mutable dict is intentional, in order to preserve the state of the INSTALLED_APPS tuple across multiple settings files.
3.052629
3.977111
0.767549
if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis] else: _Mt = Mt LMt = vei_CoR_veX(_Mt, R=self.Lr(), C=self.Lc()) DLMt = self.D()[:, :, sp.newaxis] * LMt RV = vei_CoR_veX(DLMt, R=self.Lr().T, C=self.Lc().T) if len(Mt.shape)==2: RV = RV[:, :,...
def solve_t(self, Mt)
Mt is dim_r x dim_c x d tensor
5.199656
4.859138
1.070078
atom_ids = {} for a in mol.atoms: components = [] components.append(a.number) components.append(len(a.oatoms)) components.append(a.hcount) components.append(a.charge) components.append(a.mass) if len(a.rings) > 0: components.append(1) ...
def invariants(mol)
Generate initial atom identifiers using atomic invariants
3.678217
3.343575
1.100085
atom_ids = invariants(mol) fp = {} for i in atom_ids.values(): fp[i] = fp.get(i, 0) + 1 neighborhoods = [] atom_neighborhoods = [ len(mol.bonds) * bitarray('0') for a in mol.atoms] dead_atoms = len(mol.atoms) * bitarray('0') for layer in xrange(1, radius+1): round_id...
def ecfp(mol, radius=2)
Compute the Extended-Connectivity fingerprint for a molecule. :param mol: molecule object parsed from SMILES string :param radius: The number of iterations to perform. Defaults to 2 which is equivilent to ECFP4. :rtype: dictionary representing the molecular fingprint (atom identifiers and their counts)...
2.957532
2.925395
1.010986
scheme, location, path, query, _ = urlparse.urlsplit(self.url) assert scheme in ("http", "https"), "Unsupported scheme %r" % scheme content_type, body = self._encode_multipart_formdata() handle = getattr(httplib, scheme.upper() + "Connection")(location) if self.mock_htt...
def send(self)
Post fields and files to an HTTP server as multipart/form-data. Return the server's response.
3.55983
3.488597
1.020419
def get_content_type(filename): "Helper to get MIME type." return mimetypes.guess_type(filename)[0] or 'application/octet-stream' boundary = '----------ThIs_Is_tHe_b0uNdaRY_%d$' % (time.time()) logical_lines = [] for name, value in self.fields: ...
def _encode_multipart_formdata(self)
Encode POST body. Return (content_type, body) ready for httplib.HTTP instance
2.102205
2.094153
1.003845
def perturbed_mst(X, num_perturbations=20, metric='euclidean', jitter=None): '''Builds a graph as the union of several MSTs on perturbed data. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 8 jitter refers to the scale of the gaussian noise added for each perturbation. When jitter is None, it def...
Builds a graph as the union of several MSTs on perturbed data. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 8 jitter refers to the scale of the gaussian noise added for each perturbation. When jitter is None, it defaults to the 5th percentile interpoint distance. Note that metric cannot be 'pre...
null
null
null
def disjoint_mst(X, num_spanning_trees=3, metric='euclidean'): '''Builds a graph as the union of several spanning trees, each time removing any edges present in previously-built trees. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 9.''' D = pairwise_distances(X, metric=metric) if metric == 'p...
Builds a graph as the union of several spanning trees, each time removing any edges present in previously-built trees. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 9.
null
null
null
'''Re-weight according to a specified kernel function. kernel : str, {none, binary, rbf} none -> no reweighting binary -> all edges are given weight 1 rbf -> applies a gaussian function to edge weights ''' if kernel == 'none': return self if kernel == 'binary': if ...
def kernelize(self, kernel)
Re-weight according to a specified kernel function. kernel : str, {none, binary, rbf} none -> no reweighting binary -> all edges are given weight 1 rbf -> applies a gaussian function to edge weights
4.566447
2.371465
1.925581
'''Re-weight such that the sum of each vertex's edge weights is 1. The resulting weighted graph is suitable for locally linear embedding. reg : amount of regularization to keep the problem well-posed ''' new_weights = [] for i, adj in enumerate(self.adj_list()): C = X[adj] - X[i] G =...
def barycenter_edge_weights(self, X, copy=True, reg=1e-3)
Re-weight such that the sum of each vertex's edge weights is 1. The resulting weighted graph is suitable for locally linear embedding. reg : amount of regularization to keep the problem well-posed
4.315942
2.626497
1.643231
'''Generates connected components as subgraphs. When ordered=True, subgraphs are ordered by number of vertices. ''' num_ccs, labels = self.connected_components(directed=directed) # check the trivial case first if num_ccs == 1: yield self raise StopIteration if ordered: # so...
def connected_subgraphs(self, directed=True, ordered=False)
Generates connected components as subgraphs. When ordered=True, subgraphs are ordered by number of vertices.
4.683497
3.970996
1.179426
'''Returns the (undirected) minimum spanning tree subgraph.''' dist = self.matrix('dense', copy=True) dist[dist==0] = np.inf np.fill_diagonal(dist, 0) mst = ssc.minimum_spanning_tree(dist) return self.__class__.from_adj_matrix(mst + mst.T)
def minimum_spanning_subtree(self)
Returns the (undirected) minimum spanning tree subgraph.
5.208564
4.357459
1.195321
'''Returns a subgraph containing only vertices within a given geodesic radius of start_idx.''' adj = self.matrix('dense', 'csr', 'csc') dist = ssc.dijkstra(adj, directed=directed, indices=start_idx, unweighted=(not weighted), limit=radius) mask = np.isfinite(dist) sub_...
def neighborhood_subgraph(self, start_idx, radius=1, weighted=True, directed=True, return_mask=False)
Returns a subgraph containing only vertices within a given geodesic radius of start_idx.
4.868433
3.822197
1.273726
'''Remove short-circuit edges using the Isograph algorithm. min_weight : float, optional Minimum weight of edges to consider removing. Defaults to max(MST). From "Isograph: Neighbourhood Graph Construction Based On Geodesic Distance For Semi-Supervised Learning" by Ghazvininejad et al., ...
def isograph(self, min_weight=None)
Remove short-circuit edges using the Isograph algorithm. min_weight : float, optional Minimum weight of edges to consider removing. Defaults to max(MST). From "Isograph: Neighbourhood Graph Construction Based On Geodesic Distance For Semi-Supervised Learning" by Ghazvininejad et al., 2011. ...
4.947894
2.684979
1.842805
'''Circular graph tearing. spanning_tree: one of {'mst', 'spt'} cycle_len_thresh: int, length of longest allowable cycle spt_idx: int, start vertex for shortest_path_subtree, random if None From "How to project 'circular' manifolds using geodesic distances?" by Lee & Verleysen, ESANN 2004. ...
def circle_tear(self, spanning_tree='mst', cycle_len_thresh=5, spt_idx=None, copy=True)
Circular graph tearing. spanning_tree: one of {'mst', 'spt'} cycle_len_thresh: int, length of longest allowable cycle spt_idx: int, start vertex for shortest_path_subtree, random if None From "How to project 'circular' manifolds using geodesic distances?" by Lee & Verleysen, ESANN 2004. See...
5.432029
2.476015
2.19386
'''CycleCut algorithm: removes bottleneck edges. Paper DOI: 10.1.1.225.5335 ''' symmetric = not directed adj = self.kernelize('binary').matrix('csr', 'dense', copy=True) if symmetric: adj = adj + adj.T removed_edges = [] while True: c = _atomic_cycle(adj, cycle_len_thresh, d...
def cycle_cut(self, cycle_len_thresh=12, directed=False, copy=True)
CycleCut algorithm: removes bottleneck edges. Paper DOI: 10.1.1.225.5335
5.855729
4.493173
1.30325
buf = bytearray(seed_str, encoding="utf8") variants = [] for _ in range(runs): fuzzed = fuzzer(buf, fuzz_factor) variants.append(''.join([chr(b) for b in fuzzed])) logger().info('Fuzzed strings: {}'.format(variants)) return variants
def fuzz_string(seed_str, runs=100, fuzz_factor=50)
A random fuzzer for a simulated text viewer application. It takes a string as seed and generates <runs> variant of it. :param seed_str: the string to use as seed for fuzzing. :param runs: number of fuzzed variants to supply. :param fuzz_factor: degree of fuzzing = 1 / fuzz_factor. :return: list of...
3.31574
3.468022
0.95609
buf = deepcopy(buffer) num_writes = number_of_bytes_to_modify(len(buf), fuzz_factor) for _ in range(num_writes): random_byte = random.randrange(256) random_position = random.randrange(len(buf)) buf[random_position] = random_byte return buf
def fuzzer(buffer, fuzz_factor=101)
Fuzz given buffer. Take a buffer of bytes, create a copy, and replace some bytes with random values. Number of bytes to modify depends on fuzz_factor. This code is taken from Charlie Miller's fuzzer code. :param buffer: the data to fuzz. :type buffer: byte array :param fuzz_factor: degree of f...
2.660628
2.668342
0.997109
return random.randrange(math.ceil((float(buf_len) / fuzz_factor))) + 1
def number_of_bytes_to_modify(buf_len, fuzz_factor)
Calculate number of bytes to modify. :param buf_len: len of data buffer to fuzz. :param fuzz_factor: degree of fuzzing. :return: number of bytes to change.
4.961056
8.007759
0.619531
buf = bytearray(open(os.path.abspath(data_file), 'rb').read()) fuzzed = fuzzer(buf, self.fuzz_factor) try: _, fuzz_output = mkstemp(prefix='fuzzed_') open(fuzz_output, 'wb').write(fuzzed) finally: pass return fuzz_output
def _fuzz_data_file(self, data_file)
Generate fuzzed variant of given file. :param data_file: path to file to fuzz. :type data_file: str :return: path to fuzzed file. :rtype: str
4.000339
4.122973
0.970256
app_name = os.path.basename(app_) args = [app_] args.extend(self.args[app_]) args.append(file_) process = subprocess.Popen(args) time.sleep(1) status = {True: Status.SUCCESS, False: Status.FAILED} crashed = process.poll() result = status[...
def _execute(self, app_, file_)
Run app with file as input. :param app_: application to run. :param file_: file to run app with. :return: success True, else False :rtype: bool
4.414454
4.547609
0.97072
args = {} apps = [] for app_str in app_list: parts = app_str.split("&") app_path = parts[0].strip() apps.append(app_path) if len(parts) > 1: args[app_path] = [arg.strip() for arg in parts[1].split()] else: ...
def __parse_app_list(app_list)
Parse list of apps for arguments. :param app_list: list of apps with optional arguments. :return: list of apps and assigned argument dict. :rtype: [String], {String: [String]}
2.44205
2.447543
0.997756
pi = np.pi chroma = np.arange(12) # Define each row of the transform matrix fifth_x = r_fifth*(np.sin((7*pi/6) * chroma)) fifth_y = r_fifth*(np.cos((7*pi/6) * chroma)) minor_third_x = r_minor_thirds*(np.sin(3*pi/2 * chroma)) minor_third_y = r_minor_thirds*(np.cos(3*pi/2 * chroma)) ...
def _make_tonnetz_matrix()
Return the tonnetz projection matrix.
2.315015
2.224589
1.040649
if np.sum(np.abs(chromagram)) == 0.: # The input is an empty chord, return zero. return np.zeros(6) _tonnetz = np.dot(__TONNETZ_MATRIX, chromagram) one_norm = np.sum(np.abs(_tonnetz)) # Non-zero value _tonnetz = _tonnetz / float(one_norm) # Normalize tonnetz vector return...
def _to_tonnetz(chromagram)
Project a chromagram on the tonnetz. Returned value is normalized to prevent numerical instabilities.
5.185884
5.083192
1.020202
[a_tonnetz, b_tonnetz] = [_to_tonnetz(x) for x in [a, b]] return np.linalg.norm(b_tonnetz - a_tonnetz)
def distance(a, b)
Compute tonnetz-distance between two chromagrams. ---- >>> C = np.zeros(12) >>> C[0] = 1 >>> D = np.zeros(12) >>> D[2] = 1 >>> G = np.zeros(12) >>> G[7] = 1 The distance is zero on equivalent chords >>> distance(C, C) == 0 True The distance is symetric >>> distance...
3.275999
4.212948
0.777603
print(COLORS.fail, error.message, COLORS.end) print(COLORS.fail, error.errors, COLORS.end)
def fail_print(error)
Print an error in red text. Parameters error (HTTPError) Error object to print.
4.787887
5.860559
0.816968
with open(filename, 'r') as storage_file: storage = safe_load(storage_file) # depending on OAuth 2.0 grant_type, these values may not exist client_secret = storage.get('client_secret') refresh_token = storage.get('refresh_token') credentials = { 'access_token': storage['access...
def import_oauth2_credentials(filename=STORAGE_FILENAME)
Import OAuth 2.0 session credentials from storage file. Parameters filename (str) Name of storage file. Returns credentials (dict) All your app credentials and information imported from the configuration file.
2.25681
2.418139
0.933284
oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'), access_token=credentials.get('access_token'), expires_in_seconds=credentials.get('expires_in_seconds'), scopes=credentials.get('scopes'), grant_type=credentials.get('grant_type'), client...
def create_lyft_client(credentials)
Create an LyftRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (LyftRidesClient) An authorized LyftRidesClient to access API resources.
2.281998
2.185452
1.044177
data = manager.request_host_status(config_file) is_running = data['started'] # Managed hosts run as persistent processes, so it may already be running if is_running: host_status = json.loads(data['host']['output']) logfile = data['host']['logfile'] else: data = manage...
def spawn_managed_host(config_file, manager, connect_on_start=True)
Spawns a managed host, if it is not already running
3.861563
3.737756
1.033123
if isinstance(s, six.integer_types): s = str(s) elif not isinstance(s, six.string_types): raise ValueError(s) original = s if s[-1:] == 'L': s = s[:-1] sign = {'-': -1, '=': 0, '+': 1}.get(s[0], None) if sign is not None: s = s[1:] ts = 0 for unit...
def parse_input(s)
Parse the given input and intelligently transform it into an absolute, non-naive, timezone-aware datetime object for the UTC timezone. The input can be specified as a millisecond-precision UTC timestamp (or delta against Epoch), with or without a terminating 'L'. Alternatively, the input can be specifi...
3.951029
3.496426
1.130019
s = '' if d >= 0 else '-' d = abs(d) for unit in _SORTED_UNITS: span = __timedelta_millis(unit[1]) if d >= span: count = int(d // span) s += '{0}{1}'.format(count, unit[0]) d -= count * span if d or not s: s += str(d) return s
def render_delta(d)
Render the given delta (in milliseconds) as a human-readable delta.
4.441595
3.98892
1.113483
local = date.astimezone(tz) ts = __date_to_millisecond_ts(date) return fmt.format( ts=ts, utc=date.strftime(_DATE_FORMAT), millis=ts % 1000, utc_tz=date.strftime(_TZ_FORMAT), local=local.strftime(_DATE_FORMAT), local_tz=local.strft...
def render_date(date, tz=pytz.utc, fmt=_FULL_OUTPUT_FORMAT)
Format the given date for output. The local time render of the given date is done using the given timezone.
3.533367
3.670052
0.962757
'''Parse a list of arguments, returning a dict See BooleanParser.parse for `args`-related documentation. If `complete` is True and there are values in `args` that don't have corresponding arguments, or there are required arguments that don't have args, then raise an error. ''' ...
def parse(self, complete=True, args=None)
Parse a list of arguments, returning a dict See BooleanParser.parse for `args`-related documentation. If `complete` is True and there are values in `args` that don't have corresponding arguments, or there are required arguments that don't have args, then raise an error.
7.05186
5.658501
1.246242
params = sp.randn(self.getNumberParams()) self.setParams(params)
def setRandomParams(self)
set random hyperparameters
8.302488
8.671654
0.957428
params = self.getParams() self.setParams(params+pertSize*sp.randn(params.shape[0]))
def perturbParams(self, pertSize=1e-3)
slightly perturbs the values of the parameters
4.146812
3.943847
1.051464
params = self.getParams() e = sp.zeros_like(params); e[i] = 1 self.setParams(params-h*e) C_L = self.K() self.setParams(params+h*e) C_R = self.K() self.setParams(params) RV = (C_R-C_L)/(2*h) return RV
def Kgrad_param_num(self,i,h=1e-4)
check discrepancies between numerical and analytical gradients
3.053917
2.973756
1.026956
wave = phenomdwave(*binary_args) out_vals = {} for key in noise_interpolants: hn_vals = noise_interpolants[key](wave.freqs) snr_out = csnr(wave.freqs, wave.hc, hn_vals, wave.fmrg, wave.fpeak, prefactor=prefactor) if len(signal_type) == 1: o...
def parallel_snr_func(num, binary_args, phenomdwave, signal_type, noise_interpolants, prefactor, verbose)
SNR calulation with PhenomDWaveforms Generate PhenomDWaveforms and calculate their SNR against sensitivity curves. Args: num (int): Process number. If only a single process, num=0. binary_args (tuple): Binary arguments for :meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__...
3.684897
3.513833
1.048683
wave = eccwave(*binary_args) out_vals = {} for key in noise_interpolants: hn_vals = noise_interpolants[key](wave.freqs) integrand = 1./wave.freqs * (wave.hc**2/hn_vals**2) snr_squared_out = np.trapz(integrand, x=wave.freqs) if 'modes' in signal_type: out_v...
def parallel_ecc_snr_func(num, binary_args, eccwave, signal_type, noise_interpolants, prefactor, verbose)
SNR calulation with eccentric waveforms Generate PhenomDWaveforms and calculate their SNR against sensitivity curves. Args: num (int): Process number. If only a single process, num=0. binary_args (tuple): Binary arguments for :meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__cal...
3.893652
3.668837
1.061277
squeeze = False max_length = 0 for arg in args: try: length = len(arg) if length > max_length: max_length = length except TypeError: pass if max_length == 0: squeeze = True kwargs['length'] = max_length snr_main...
def snr(*args, **kwargs)
Compute the SNR of binaries. snr is a function that takes binary parameters and sensitivity curves as inputs, and returns snr for chosen phases. Warning: All binary parameters must be either scalar, len-1 arrays, or arrays of the same length. All of these can be used at once. However, you cannot i...
2.782547
3.006795
0.92542
def smilin(smiles, transforms=[figueras.sssr, aromaticity.aromatize]): builder = BuildMol() tokenize(smiles, builder) mol = builder.mol for transform in transforms: mol = transform(mol) ## implicit hcount doesn't make any sense anymore... for atom in mol.atoms:...
(smiles)->molecule Convert a smiles string into a molecule representation
null
null
null
'''Parse a list of arguments, returning a dict. Flags are only boolean if they are not followed by a non-flag argument. All positional arguments not associable with a flag will be added to the return dictionary's `['_']` field. ''' opts = dict() if args is None: ...
def parse(self, args=None)
Parse a list of arguments, returning a dict. Flags are only boolean if they are not followed by a non-flag argument. All positional arguments not associable with a flag will be added to the return dictionary's `['_']` field.
8.134234
5.579027
1.458002
if X2==None: X2 = X1 assert X1.shape[1]==X2.shape[1], 'dimensions do not match' n = X1.shape[0] m = X2.shape[0] d = X1.shape[1] # (X1 - X2)**2 = X1**2 + X2**2 - 2X1X2 X1sq = sp.reshape((X1**2).sum(1),n,1) X2sq = sp.reshape((X2**2).sum(1),m,1) K = sp.tile((X1*X1).sum(1)...
def sq_dist(X1,X2=None)
computes a matrix of all pariwise squared distances
2.108158
2.131984
0.988824
# this bond must be a double bond if self.bondtype != 2: raise FrownsError("To set double bond order, center bond must be double!") assert dboval in [DX_CHI_CIS, DX_CHI_TRANS, DX_CHI_NO_DBO], "bad dboval value" self.dbo.append(bond1, bond2, dboval)
def setdbo(self, bond1, bond2, dboval)
Set the double bond orientation for bond1 and bond2 based on this bond
9.114342
8.827617
1.03248
raise "Deprecated" self.symbol, self.bondtype, bondorder, self.equiv_class = \ BONDLOOKUP[symbol] if self.bondtype == 4: self.aromatic = 1 else: self.aromatic = 0
def set_symbol(self, symbol)
(symbol, bondorder) -> set the bondsymbol of the molecule
8.687968
7.279298
1.193517
handle = atom.handle if handle == self.atoms[0].handle: return self.atoms[1] elif handle == self.atoms[1].handle: return self.atoms[0] return None
def xatom(self, atom)
(atom)->return the atom at the other end of this bond or None if atom is not part of this bond
3.250324
2.969867
1.094434
if labels is None: labels = [('Seg#%03d' % idx) for idx in range(1, len(boundaries))] times = [beat_intervals[beat, 0] for beat in boundaries[:-1]] times.append(beat_intervals[-1, -1]) with open(outfile, 'w') as f: for idx, (start, end, lab) in enumerate(zip(times[:-1], ...
def save_segments(outfile, boundaries, beat_intervals, labels=None)
Save detected segments to a .lab file. :parameters: - outfile : str Path to output file - boundaries : list of int Beat indices of detected segment boundaries - beat_intervals : np.ndarray [shape=(n, 2)] Intervals of beats - labels : None or li...
2.481758
2.520254
0.984725
prefixer = get_url_prefix() if prefixer: prefix = prefix or '/' url = django_reverse(viewname, urlconf, args, kwargs, prefix) if prefixer: url = prefixer.fix(url) # Ensure any unicode characters in the URL are escaped. return iri_to_uri(url)
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None)
Wraps Django's reverse to prepend the correct locale.
4.458954
4.195021
1.062916
path = path_.lstrip('/') # Use partitition instead of split since it always returns 3 parts first, _, rest = path.partition('/') lang = first.lower() if lang in settings.LANGUAGE_URL_MAP: return settings.LANGUAGE_URL_MAP[lang], rest else: supported = find_supported(first) ...
def split_path(path_)
Split the requested path into (locale, path). locale will be empty if it isn't found.
5.224788
5.105201
1.023425
if 'lang' in self.request.GET: lang = self.request.GET['lang'].lower() if lang in settings.LANGUAGE_URL_MAP: return settings.LANGUAGE_URL_MAP[lang] if self.request.META.get('HTTP_ACCEPT_LANGUAGE'): best = self.get_best_language( ...
def get_language(self)
Return a locale code we support on the site using the user's Accept-Language header to determine which is best. This mostly follows the RFCs but read bug 439568 for details.
2.305298
2.128231
1.083199