text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def find_mirteFile(name, extra_path=None): """ Resolves <name> to a path. Uses <extra_path> """ extra_path = () if extra_path is None else extra_path for bp in chain(extra_path, sys.path): pb = os.path.join(bp, name) p = pb + FILE_SUFFIX if os.path.exists(p): return os.p...
[ "def", "find_mirteFile", "(", "name", ",", "extra_path", "=", "None", ")", ":", "extra_path", "=", "(", ")", "if", "extra_path", "is", "None", "else", "extra_path", "for", "bp", "in", "chain", "(", "extra_path", ",", "sys", ".", "path", ")", ":", "pb",...
41
0.001988
def enable(name, **kwargs): ''' Enable the named service to start at boot. flags : None Set optional flags to run the service with. service.flags can be used to change the default flags. CLI Example: .. code-block:: bash salt '*' service.enable <service name> salt '*...
[ "def", "enable", "(", "name", ",", "*", "*", "kwargs", ")", ":", "stat_cmd", "=", "'{0} set {1} status on'", ".", "format", "(", "_cmd", "(", ")", ",", "name", ")", "stat_retcode", "=", "__salt__", "[", "'cmd.retcode'", "]", "(", "stat_cmd", ")", "flag_r...
30.333333
0.001183
def env(mounts): """ Compute the environment of the change root for the user. Args: mounts: The mountpoints of the current user. Return: paths ld_libs """ f_mounts = [m.strip("/") for m in mounts] root = local.path("/") ld_libs = [root / m / "lib" for m in f_mo...
[ "def", "env", "(", "mounts", ")", ":", "f_mounts", "=", "[", "m", ".", "strip", "(", "\"/\"", ")", "for", "m", "in", "mounts", "]", "root", "=", "local", ".", "path", "(", "\"/\"", ")", "ld_libs", "=", "[", "root", "/", "m", "/", "\"lib\"", "fo...
25.857143
0.001776
def overlaps(self,tx2): """Return True if overlapping """ total = 0 for e1 in self.exons: for e2 in tx2.exons: if e1.overlap_size(e2) > 0: return True return False
[ "def", "overlaps", "(", "self", ",", "tx2", ")", ":", "total", "=", "0", "for", "e1", "in", "self", ".", "exons", ":", "for", "e2", "in", "tx2", ".", "exons", ":", "if", "e1", ".", "overlap_size", "(", "e2", ")", ">", "0", ":", "return", "True"...
23.75
0.020305
def report_view(self, request, key, period): """ Processes the reporting action. """ if not self.has_change_permission(request, None): raise PermissionDenied reporters = self.get_reporters() try: reporter = reporters[key] except KeyError:...
[ "def", "report_view", "(", "self", ",", "request", ",", "key", ",", "period", ")", ":", "if", "not", "self", ".", "has_change_permission", "(", "request", ",", "None", ")", ":", "raise", "PermissionDenied", "reporters", "=", "self", ".", "get_reporters", "...
37
0.008105
def guess_bonds(r_array, type_array, threshold=0.1, maxradius=0.3, radii_dict=None): '''Detect bonds given the coordinates (r_array) and types of the atoms involved (type_array), based on their covalent radii. To fine-tune the detection, it is possible to set a **threshold** and a maximum search ...
[ "def", "guess_bonds", "(", "r_array", ",", "type_array", ",", "threshold", "=", "0.1", ",", "maxradius", "=", "0.3", ",", "radii_dict", "=", "None", ")", ":", "if", "radii_dict", "is", "None", ":", "covalent_radii", "=", "cdb", ".", "get", "(", "'data'",...
32.8125
0.012026
def values(self, predicate=None): """ Returns a list clone of the values contained in this map or values of the entries which are filtered with the predicate if provided. **Warning: The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and ...
[ "def", "values", "(", "self", ",", "predicate", "=", "None", ")", ":", "if", "predicate", ":", "predicate_data", "=", "self", ".", "_to_data", "(", "predicate", ")", "return", "self", ".", "_encode_invoke", "(", "map_values_with_predicate_codec", ",", "predica...
44.684211
0.009227
def _route(self, action, method): """ Given an action method, generates a route for it. """ # First thing, determine the path for the method path = method._wsgi_path methods = None if path is None: map_rule = self.wsgi_method_map.get(method.__name__) ...
[ "def", "_route", "(", "self", ",", "action", ",", "method", ")", ":", "# First thing, determine the path for the method", "path", "=", "method", ".", "_wsgi_path", "methods", "=", "None", "if", "path", "is", "None", ":", "map_rule", "=", "self", ".", "wsgi_met...
36.948718
0.001352
def multi_buffering(layer, radii, callback=None): """Buffer a vector layer using many buffers (for volcanoes or rivers). This processing algorithm will keep the original attribute table and will add a new one for the hazard class name according to safe.definitions.fields.hazard_value_field. radii ...
[ "def", "multi_buffering", "(", "layer", ",", "radii", ",", "callback", "=", "None", ")", ":", "# Layer output", "output_layer_name", "=", "buffer_steps", "[", "'output_layer_name'", "]", "processing_step", "=", "buffer_steps", "[", "'step_name'", "]", "input_crs", ...
31.858491
0.000287
def chk_edges_nodes(edges, nodes, name): """Check that user specified edges have a node which exists.""" edge_nodes = set(e for es in edges for e in es) missing_nodes = edge_nodes.difference(nodes) assert not missing_nodes, "MISSING: {GOs}\n{NM} EDGES MISSING {N} NODES (OF {T})".format( ...
[ "def", "chk_edges_nodes", "(", "edges", ",", "nodes", ",", "name", ")", ":", "edge_nodes", "=", "set", "(", "e", "for", "es", "in", "edges", "for", "e", "in", "es", ")", "missing_nodes", "=", "edge_nodes", ".", "difference", "(", "nodes", ")", "assert"...
65.833333
0.01
def builtin(self, keyword): """Parse the pseudo-function application subgrammar.""" # The match includes the lparen token, so the keyword is just the first # token in the match, not the whole thing. keyword_start = self.tokens.matched.first.start keyword_end = self.tokens.matched...
[ "def", "builtin", "(", "self", ",", "keyword", ")", ":", "# The match includes the lparen token, so the keyword is just the first", "# token in the match, not the whole thing.", "keyword_start", "=", "self", ".", "tokens", ".", "matched", ".", "first", ".", "start", "keywor...
43.928571
0.001591
def iterfiles(self): """Yield all WinFile object. """ try: for path in self.order: yield self.files[path] except: for winfile in self.files.values(): yield winfile
[ "def", "iterfiles", "(", "self", ")", ":", "try", ":", "for", "path", "in", "self", ".", "order", ":", "yield", "self", ".", "files", "[", "path", "]", "except", ":", "for", "winfile", "in", "self", ".", "files", ".", "values", "(", ")", ":", "yi...
27
0.011952
def blocks(seq, size=None, hop=None, padval=0.): """ General iterable blockenizer. Generator that gets ``size`` elements from ``seq``, and outputs them in a collections.deque (mutable circular queue) sequence container. Next output starts ``hop`` elements after the first element in last output block. Last ...
[ "def", "blocks", "(", "seq", ",", "size", "=", "None", ",", "hop", "=", "None", ",", "padval", "=", "0.", ")", ":", "# Initialization", "res", "=", "deque", "(", "maxlen", "=", "size", ")", "# Circular queue", "idx", "=", "0", "last_idx", "=", "size"...
26.357143
0.018289
def _compute_gradients(self, loss_fn, x, unused_optim_state): """Compute a new value of `x` to minimize `loss_fn`. Args: loss_fn: a callable that takes `x`, a batch of images, and returns a batch of loss values. `x` will be optimized to minimize `loss_fn(x)`. x: A list o...
[ "def", "_compute_gradients", "(", "self", ",", "loss_fn", ",", "x", ",", "unused_optim_state", ")", ":", "# Assumes `x` is a list,", "# and contains a tensor representing a batch of images", "assert", "len", "(", "x", ")", "==", "1", "and", "isinstance", "(", "x", "...
41.36
0.000945
def setup_cachedir(cachedir, mmap_mode=None, bytes_limit=None): """ This function injects a joblib.Memory object in the cache() function (in a thread-specific slot of its 'memories' attribute). """ if not hasattr(cache, 'memories'): cache.memories = {} memory = joblib.Memory( locati...
[ "def", "setup_cachedir", "(", "cachedir", ",", "mmap_mode", "=", "None", ",", "bytes_limit", "=", "None", ")", ":", "if", "not", "hasattr", "(", "cache", ",", "'memories'", ")", ":", "cache", ".", "memories", "=", "{", "}", "memory", "=", "joblib", "."...
33.928571
0.002049
def use_colorscheme(self, name='default'): """ Apply new colorscheme. (By name.) """ try: self.current_style = get_editor_style_by_name(name) except pygments.util.ClassNotFound: pass
[ "def", "use_colorscheme", "(", "self", ",", "name", "=", "'default'", ")", ":", "try", ":", "self", ".", "current_style", "=", "get_editor_style_by_name", "(", "name", ")", "except", "pygments", ".", "util", ".", "ClassNotFound", ":", "pass" ]
29.875
0.00813
def chunk_from_mem(self, ptr): """ Given a pointer to a user payload, return the chunk associated with that payload. :param ptr: a pointer to the base of a user payload in the heap :returns: the associated heap chunk """ raise NotImplementedError("%s not implemented for ...
[ "def", "chunk_from_mem", "(", "self", ",", "ptr", ")", ":", "raise", "NotImplementedError", "(", "\"%s not implemented for %s\"", "%", "(", "self", ".", "chunk_from_mem", ".", "__func__", ".", "__name__", ",", "self", ".", "__class__", ".", "__name__", ")", ")...
49.777778
0.010965
def get_config_value(self, k, i): """Gets the ith config value for k. e.g. get_config_value('x', 1)""" if(not isinstance(self.store[k], list)): return self.store[k] else: return self.store[k][i]
[ "def", "get_config_value", "(", "self", ",", "k", ",", "i", ")", ":", "if", "(", "not", "isinstance", "(", "self", ".", "store", "[", "k", "]", ",", "list", ")", ")", ":", "return", "self", ".", "store", "[", "k", "]", "else", ":", "return", "s...
39.666667
0.00823
def build_wxsfile_header_section(root, spec): """ Adds the xml file node which define the package meta-data. """ # Create the needed DOM nodes and add them at the correct position in the tree. factory = Document() Product = factory.createElement( 'Product' ) Package = factory.createElement( 'Pac...
[ "def", "build_wxsfile_header_section", "(", "root", ",", "spec", ")", ":", "# Create the needed DOM nodes and add them at the correct position in the tree.", "factory", "=", "Document", "(", ")", "Product", "=", "factory", ".", "createElement", "(", "'Product'", ")", "Pac...
43.8
0.020421
def laplacian(script, iterations=1, boundary=True, cotangent_weight=True, selected=False): """ Laplacian smooth of the mesh: for each vertex it calculates the average position with nearest vertex Args: script: the FilterScript object or script filename to write the fil...
[ "def", "laplacian", "(", "script", ",", "iterations", "=", "1", ",", "boundary", "=", "True", ",", "cotangent_weight", "=", "True", ",", "selected", "=", "False", ")", ":", "filter_xml", "=", "''", ".", "join", "(", "[", "' <filter name=\"Laplacian Smooth\"...
39.057692
0.00048
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
[ "def", "table_top_abs", "(", "self", ")", ":", "table_height", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "self", ".", "table_full_size", "[", "2", "]", "]", ")", "return", "string_to_array", "(", "self", ".", "floor", ".", "get", "(", ...
53
0.009302
def requirements(work_dir, hive_root, with_requirements, with_dockerfile, active_module, active_module_file): """编译全新依赖文件""" import sys sys.path.insert(0, hive_root) hive_root = os.path.abspath(os.path.expanduser(hive_root)) work_dir = work_dir or os.path.join( os.environ....
[ "def", "requirements", "(", "work_dir", ",", "hive_root", ",", "with_requirements", ",", "with_dockerfile", ",", "active_module", ",", "active_module_file", ")", ":", "import", "sys", "sys", ".", "path", ".", "insert", "(", "0", ",", "hive_root", ")", "hive_ro...
30.036649
0.000337
def from_structure(cls, original, filter_residues): """ Loads structure as a protein, exposing protein-specific methods. """ P = cls(original.id) P.full_id = original.full_id for child in original.child_dict.values(): copycat = deepcopy(child)...
[ "def", "from_structure", "(", "cls", ",", "original", ",", "filter_residues", ")", ":", "P", "=", "cls", "(", "original", ".", "id", ")", "P", ".", "full_id", "=", "original", ".", "full_id", "for", "child", "in", "original", ".", "child_dict", ".", "v...
33.84375
0.008079
def data(self, data): """Store a copy of the data.""" self._data = {det: d.copy() for (det, d) in data.items()}
[ "def", "data", "(", "self", ",", "data", ")", ":", "self", ".", "_data", "=", "{", "det", ":", "d", ".", "copy", "(", ")", "for", "(", "det", ",", "d", ")", "in", "data", ".", "items", "(", ")", "}" ]
41.666667
0.015748
def set_editor(self, editor): """ Sets the associated editor, when the editor's offset calculator mode emit the signal pic_infos_available, the table is automatically refreshed. You can also refresh manually by calling :meth:`update_pic_infos`. """ if self._edito...
[ "def", "set_editor", "(", "self", ",", "editor", ")", ":", "if", "self", ".", "_editor", "is", "not", "None", ":", "try", ":", "self", ".", "_editor", ".", "offset_calculator", ".", "pic_infos_available", ".", "disconnect", "(", "self", ".", "_update", "...
39.952381
0.002328
def get_checkouts(self, **params): """https://developers.coinbase.com/api/v2#list-checkouts""" response = self._get('v2', 'checkouts', params=params) return self._make_api_object(response, Checkout)
[ "def", "get_checkouts", "(", "self", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "_get", "(", "'v2'", ",", "'checkouts'", ",", "params", "=", "params", ")", "return", "self", ".", "_make_api_object", "(", "response", ",", "Checkout",...
54.75
0.009009
def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces ...
[ "def", "replace_route", "(", "route_table_id", "=", "None", ",", "destination_cidr_block", "=", "None", ",", "route_table_name", "=", "None", ",", "gateway_id", "=", "None", ",", "instance_id", "=", "None", ",", "interface_id", "=", "None", ",", "region", "=",...
42.489796
0.002347
def send(self, msg, timeout=None): """Transmit a message to the CAN bus. :param can.Message msg: A message object. :param float timeout: Wait up to this many seconds for the transmit queue to be ready. If not given, the call may fail immediately. :raises can.Can...
[ "def", "send", "(", "self", ",", "msg", ",", "timeout", "=", "None", ")", ":", "log", ".", "debug", "(", "\"We've been asked to write a message to the bus\"", ")", "logger_tx", "=", "log", ".", "getChild", "(", "\"tx\"", ")", "logger_tx", ".", "debug", "(", ...
34.555556
0.001564
def build_raw_request_message(self, request, args, is_completed=False): """build protocol level message based on request and args. request object contains meta information about outgoing request. args are the currently chunk data from argstreams is_completed tells the flags of the messa...
[ "def", "build_raw_request_message", "(", "self", ",", "request", ",", "args", ",", "is_completed", "=", "False", ")", ":", "request", ".", "flags", "=", "FlagsType", ".", "none", "if", "is_completed", "else", "FlagsType", ".", "fragment", "# TODO decide what nee...
39.710526
0.001294
async def _trigger_event(self, event, *args, **kwargs): """Invoke an event handler.""" run_async = kwargs.pop('run_async', False) ret = None if event in self.handlers: if asyncio.iscoroutinefunction(self.handlers[event]) is True: if run_async: ...
[ "async", "def", "_trigger_event", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "run_async", "=", "kwargs", ".", "pop", "(", "'run_async'", ",", "False", ")", "ret", "=", "None", "if", "event", "in", "self", ".", "...
43.888889
0.002477
def execute(self, input_data): ''' Execute the VTQuery worker ''' md5 = input_data['meta']['md5'] response = requests.get('http://www.virustotal.com/vtapi/v2/file/report', params={'apikey':self.apikey,'resource':md5, 'allinfo':1}) # Make sure we got a js...
[ "def", "execute", "(", "self", ",", "input_data", ")", ":", "md5", "=", "input_data", "[", "'meta'", "]", "[", "'md5'", "]", "response", "=", "requests", ".", "get", "(", "'http://www.virustotal.com/vtapi/v2/file/report'", ",", "params", "=", "{", "'apikey'", ...
37.5
0.012232
def block_header_index( cls, path, block_header ): """ Given a block's serialized header, go and find out what its block ID is (if it is present at all). Return the >= 0 index on success Return -1 if not found. NOTE: this is slow """ with open( path, "rb...
[ "def", "block_header_index", "(", "cls", ",", "path", ",", "block_header", ")", ":", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "f", ":", "chain_raw", "=", "f", ".", "read", "(", ")", "for", "blk", "in", "xrange", "(", "0", ",", "len", ...
31.833333
0.013559
def preston_bin(data, max_num): """ Bins data on base 2 using Preston's method Parameters ---------- data : array-like Data to be binned max_num : float The maximum upper value of the data Returns ------- tuple (binned_data, bin_edges) Notes ----- ...
[ "def", "preston_bin", "(", "data", ",", "max_num", ")", ":", "log_ub", "=", "np", ".", "ceil", "(", "np", ".", "log2", "(", "max_num", ")", ")", "# Make an exclusive lower bound in keeping with Preston", "if", "log_ub", "==", "0", ":", "boundaries", "=", "np...
24.8
0.000705
def get(self, urls=None, **overrides): """Sets the acceptable HTTP method to a GET""" if urls is not None: overrides['urls'] = urls return self.where(accept='GET', **overrides)
[ "def", "get", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'GET'", ",", "*"...
41.6
0.009434
def results_class_wise_metrics(self): """Class-wise metrics Returns ------- dict results in a dictionary format """ results = {} for tag_id, tag_label in enumerate(self.tag_label_list): if tag_label not in results: result...
[ "def", "results_class_wise_metrics", "(", "self", ")", ":", "results", "=", "{", "}", "for", "tag_id", ",", "tag_label", "in", "enumerate", "(", "self", ".", "tag_label_list", ")", ":", "if", "tag_label", "not", "in", "results", ":", "results", "[", "tag_l...
29.818182
0.001476
def _get_calculatable_methods_dict(inputs, methods): ''' Given an iterable of input variable names and a methods dictionary, returns the subset of that methods dictionary that can be calculated and which doesn't calculate something we already have. Additionally it may only contain one method for any...
[ "def", "_get_calculatable_methods_dict", "(", "inputs", ",", "methods", ")", ":", "# Initialize a return dictionary", "calculatable_methods", "=", "{", "}", "# Iterate through each potential method output", "for", "var", "in", "methods", ".", "keys", "(", ")", ":", "# S...
46.058824
0.000625
def _init_caches(self): from .xcollections import ( StringStore, FunctionStore, CharacterMapping, UniversalMapping ) from .cache import ( Cache, NodeContentsCache, InitializedCache, EntitylessCache, ...
[ "def", "_init_caches", "(", "self", ")", ":", "from", ".", "xcollections", "import", "(", "StringStore", ",", "FunctionStore", ",", "CharacterMapping", ",", "UniversalMapping", ")", "from", ".", "cache", "import", "(", "Cache", ",", "NodeContentsCache", ",", "...
46.779221
0.001359
def get_asset_mdata(): """Return default mdata map for Asset""" return { 'copyright_registration': { 'element_label': { 'text': 'copyright registration', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), ...
[ "def", "get_asset_mdata", "(", ")", ":", "return", "{", "'copyright_registration'", ":", "{", "'element_label'", ":", "{", "'text'", ":", "'copyright registration'", ",", "'languageTypeId'", ":", "str", "(", "DEFAULT_LANGUAGE_TYPE", ")", ",", "'scriptTypeId'", ":", ...
37.879747
0.000081
def _setup(self): """ Generates _reverse_map from _map """ ValueMap._setup(self) cls = self.__class__ if cls._map is not None: cls._size = max(self._map.keys()) + 1
[ "def", "_setup", "(", "self", ")", ":", "ValueMap", ".", "_setup", "(", "self", ")", "cls", "=", "self", ".", "__class__", "if", "cls", ".", "_map", "is", "not", "None", ":", "cls", ".", "_size", "=", "max", "(", "self", ".", "_map", ".", "keys",...
21.7
0.00885
def dict2row(d, model, rel=None, exclude=None, exclude_pk=None, exclude_underscore=None, only=None, fk_suffix=None): """ Recursively walk dict attributes to serialize ones into a row. :param d: dict that represent a serialized row :param model: class nested from the declarative base class ...
[ "def", "dict2row", "(", "d", ",", "model", ",", "rel", "=", "None", ",", "exclude", "=", "None", ",", "exclude_pk", "=", "None", ",", "exclude_underscore", "=", "None", ",", "only", "=", "None", ",", "fk_suffix", "=", "None", ")", ":", "if", "not", ...
44.37931
0.00038
def create_table_sql(cls, db): ''' Returns the SQL command for creating a table for this model. ''' parts = ['CREATE TABLE IF NOT EXISTS `%s`.`%s` AS `%s`.`%s`' % (db.db_name, cls.table_name(), db.db_name, cls.engine...
[ "def", "create_table_sql", "(", "cls", ",", "db", ")", ":", "parts", "=", "[", "'CREATE TABLE IF NOT EXISTS `%s`.`%s` AS `%s`.`%s`'", "%", "(", "db", ".", "db_name", ",", "cls", ".", "table_name", "(", ")", ",", "db", ".", "db_name", ",", "cls", ".", "engi...
50.555556
0.008639
def get_basis(name, elements=None, version=None, fmt=None, uncontract_general=False, uncontract_spdf=False, uncontract_segmented=False, make_general=False, optimize_general=False, data_dir=None,...
[ "def", "get_basis", "(", "name", ",", "elements", "=", "None", ",", "version", "=", "None", ",", "fmt", "=", "None", ",", "uncontract_general", "=", "False", ",", "uncontract_spdf", "=", "False", ",", "uncontract_segmented", "=", "False", ",", "make_general"...
37.487179
0.002332
def show(config, username): """Display a specific user.""" client = Client() client.prepare_connection() user_api = API(client) CLI.show_user(user_api.show(username))
[ "def", "show", "(", "config", ",", "username", ")", ":", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "user_api", "=", "API", "(", "client", ")", "CLI", ".", "show_user", "(", "user_api", ".", "show", "(", "username...
33.5
0.009709
def metadata_query(fpid, apikey): """Queries the Last.fm servers for metadata about a given fingerprint ID (an integer). Returns the XML response (a string). """ params = { 'method': 'track.getFingerprintMetadata', 'fingerprintid': fpid, 'api_key': apikey, } url = '%s?%s'...
[ "def", "metadata_query", "(", "fpid", ",", "apikey", ")", ":", "params", "=", "{", "'method'", ":", "'track.getFingerprintMetadata'", ",", "'fingerprintid'", ":", "fpid", ",", "'api_key'", ":", "apikey", ",", "}", "url", "=", "'%s?%s'", "%", "(", "URL_METADA...
36.210526
0.001416
def subdivide(self, face_index=None): """ Subdivide a mesh, with each subdivided face replaced with four smaller faces. Parameters ---------- face_index: (m,) int or None If None all faces of mesh will be subdivided If (m,) int array of indices: only ...
[ "def", "subdivide", "(", "self", ",", "face_index", "=", "None", ")", ":", "vertices", ",", "faces", "=", "remesh", ".", "subdivide", "(", "vertices", "=", "self", ".", "vertices", ",", "faces", "=", "self", ".", "faces", ",", "face_index", "=", "face_...
45.5
0.002153
def makeGlyphsBoundingBoxes(self): """ Make bounding boxes for all the glyphs, and return a dictionary of BoundingBox(xMin, xMax, yMin, yMax) namedtuples keyed by glyph names. The bounding box of empty glyphs (without contours or components) is set to None. Float values ...
[ "def", "makeGlyphsBoundingBoxes", "(", "self", ")", ":", "def", "getControlPointBounds", "(", "glyph", ")", ":", "pen", ".", "init", "(", ")", "glyph", ".", "draw", "(", "pen", ")", "return", "pen", ".", "bounds", "glyphBoxes", "=", "{", "}", "pen", "=...
36.551724
0.001838
def com_google_fonts_check_code_pages(ttFont): """Check code page character ranges""" if not hasattr(ttFont['OS/2'], "ulCodePageRange1") or \ not hasattr(ttFont['OS/2'], "ulCodePageRange2") or \ (ttFont['OS/2'].ulCodePageRange1 == 0 and \ ttFont['OS/2'].ulCodePageRange2 == 0): yield FAIL, ("No ...
[ "def", "com_google_fonts_check_code_pages", "(", "ttFont", ")", ":", "if", "not", "hasattr", "(", "ttFont", "[", "'OS/2'", "]", ",", "\"ulCodePageRange1\"", ")", "or", "not", "hasattr", "(", "ttFont", "[", "'OS/2'", "]", ",", "\"ulCodePageRange2\"", ")", "or",...
42.818182
0.012474
def tile_images(img1, img2, mask1, mask2, opts): """Combine two images into one by tiling them. ``mask1`` and ``mask2`` provide optional masks for alpha-blending; pass None to avoid. Fills unused areas with ``opts.bgcolor``. Puts a ``opts.spacing``-wide bar with a thin line of ``opts.sepcolor`` ...
[ "def", "tile_images", "(", "img1", ",", "img2", ",", "mask1", ",", "mask2", ",", "opts", ")", ":", "w1", ",", "h1", "=", "img1", ".", "size", "w2", ",", "h2", "=", "img2", ".", "size", "if", "opts", ".", "orientation", "==", "'auto'", ":", "opts"...
30.682927
0.00077
def get_single_by_flags(self, flags): """Get the register info matching the flag. Raises ValueError if more than one are found.""" regs = list(self.get_by_flags(flags)) if len(regs) != 1: raise ValueError("Flags do not return unique resigter. {!r}", regs) return regs[0]
[ "def", "get_single_by_flags", "(", "self", ",", "flags", ")", ":", "regs", "=", "list", "(", "self", ".", "get_by_flags", "(", "flags", ")", ")", "if", "len", "(", "regs", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Flags do not return unique resig...
44.142857
0.009524
def local_minima(vector,min_distance = 4, brd_mode = "wrap"): """ Internal finder for local minima . Returns UNSORTED indices of minima in input vector. """ fits = gaussian_filter(numpy.asarray(vector,dtype=numpy.float32),1., mode=brd_mode) for ii in range(len(fits)): if fits[ii] == fits...
[ "def", "local_minima", "(", "vector", ",", "min_distance", "=", "4", ",", "brd_mode", "=", "\"wrap\"", ")", ":", "fits", "=", "gaussian_filter", "(", "numpy", ".", "asarray", "(", "vector", ",", "dtype", "=", "numpy", ".", "float32", ")", ",", "1.", ",...
41.615385
0.016275
def format_help(help): """Formats the help string.""" help = help.replace("Options:", str(crayons.normal("Options:", bold=True))) help = help.replace( "Usage: pipenv", str("Usage: {0}".format(crayons.normal("pipenv", bold=True))) ) help = help.replace(" check", str(crayons.red(" check", bo...
[ "def", "format_help", "(", "help", ")", ":", "help", "=", "help", ".", "replace", "(", "\"Options:\"", ",", "str", "(", "crayons", ".", "normal", "(", "\"Options:\"", ",", "bold", "=", "True", ")", ")", ")", "help", "=", "help", ".", "replace", "(", ...
37.087719
0.001843
def get_tops(extra_mods='', so_mods=''): ''' Get top directories for the dependencies, based on Python interpreter. :param extra_mods: :param so_mods: :return: ''' tops = [] for mod in [salt, jinja2, yaml, tornado, msgpack, certifi, singledispatch, concurrent, singledisp...
[ "def", "get_tops", "(", "extra_mods", "=", "''", ",", "so_mods", "=", "''", ")", ":", "tops", "=", "[", "]", "for", "mod", "in", "[", "salt", ",", "jinja2", ",", "yaml", ",", "tornado", ",", "msgpack", ",", "certifi", ",", "singledispatch", ",", "c...
36.552632
0.002104
def _file_exists(path, filename): """Checks if the filename exists under the path.""" return os.path.isfile(os.path.join(path, filename))
[ "def", "_file_exists", "(", "path", ",", "filename", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", ")" ]
46.333333
0.021277
def merge(self, status: 'Status[Input, Output]') -> 'Status[Input, Output]': """Merge the failure message from another status into this one. Whichever status represents parsing that has gone the farthest is retained. If both statuses have gone the same distance, then the expected values...
[ "def", "merge", "(", "self", ",", "status", ":", "'Status[Input, Output]'", ")", "->", "'Status[Input, Output]'", ":", "if", "status", "is", "None", "or", "status", ".", "farthest", "is", "None", ":", "# No new message; simply return unchanged", "pass", "elif", "s...
42.30303
0.002101
def _inject_into_mod(mod, name, value, force_lock=False): ''' Inject a variable into a module. This is used to inject "globals" like ``__salt__``, ``__pillar``, or ``grains``. Instead of injecting the value directly, a ``ThreadLocalProxy`` is created. If such a proxy is already present under the sp...
[ "def", "_inject_into_mod", "(", "mod", ",", "name", ",", "value", ",", "force_lock", "=", "False", ")", ":", "old_value", "=", "getattr", "(", "mod", ",", "name", ",", "None", ")", "# We use a double-checked locking scheme in order to avoid taking the lock", "# when...
48.45
0.000337
def task_dropped(self): """ Track (if required) drop event and do the same job as :meth:`.WScheduleRecord.task_dropped` method do :return: None """ tracker = self.task().tracker_storage() if tracker is not None and self.track_drop() is True: details = self.task().event_details(WTrackerEvents.drop) tr...
[ "def", "task_dropped", "(", "self", ")", ":", "tracker", "=", "self", ".", "task", "(", ")", ".", "tracker_storage", "(", ")", "if", "tracker", "is", "not", "None", "and", "self", ".", "track_drop", "(", ")", "is", "True", ":", "details", "=", "self"...
36.545455
0.029126
def read_trees(self, input_dir): """ Read a directory full of tree files, matching them up to the already loaded alignments """ if self.show_progress: pbar = setup_progressbar("Loading trees", len(self.records)) pbar.start() for i, rec in enumerate(self.records)...
[ "def", "read_trees", "(", "self", ",", "input_dir", ")", ":", "if", "self", ".", "show_progress", ":", "pbar", "=", "setup_progressbar", "(", "\"Loading trees\"", ",", "len", "(", "self", ".", "records", ")", ")", "pbar", ".", "start", "(", ")", "for", ...
30.535714
0.002268
def _decompose_pattern(self, pattern): """ Given a path pattern with format declaration, generates a four-tuple (glob_pattern, regexp pattern, fields, type map) """ sep = '~lancet~sep~' float_codes = ['e','E','f', 'F','g', 'G', 'n'] typecodes = dict([(k,float) for...
[ "def", "_decompose_pattern", "(", "self", ",", "pattern", ")", ":", "sep", "=", "'~lancet~sep~'", "float_codes", "=", "[", "'e'", ",", "'E'", ",", "'f'", ",", "'F'", ",", "'g'", ",", "'G'", ",", "'n'", "]", "typecodes", "=", "dict", "(", "[", "(", ...
45.034483
0.017241
def DropPrivileges(): """Attempt to drop privileges if required.""" if config.CONFIG["Server.username"]: try: os.setuid(pwd.getpwnam(config.CONFIG["Server.username"]).pw_uid) except (KeyError, OSError): logging.exception("Unable to switch to user %s", config.CONFIG["Serve...
[ "def", "DropPrivileges", "(", ")", ":", "if", "config", ".", "CONFIG", "[", "\"Server.username\"", "]", ":", "try", ":", "os", ".", "setuid", "(", "pwd", ".", "getpwnam", "(", "config", ".", "CONFIG", "[", "\"Server.username\"", "]", ")", ".", "pw_uid", ...
37.444444
0.017391
def docs(recreate, gen_index, run_doctests): # type: (bool, bool, bool) -> None """ Build the documentation for the project. Args: recreate (bool): If set to **True**, the build and output directories will be cleared prior to generating the docs. gen_index (bool): ...
[ "def", "docs", "(", "recreate", ",", "gen_index", ",", "run_doctests", ")", ":", "# type: (bool, bool, bool) -> None", "build_dir", "=", "conf", ".", "get_path", "(", "'build_dir'", ",", "'.build'", ")", "docs_dir", "=", "conf", ".", "get_path", "(", "'docs.path...
36.862069
0.001367
def from_EV(E, V): """ Creates an instance of a Gamma Prior by specifying the Expected value(s) and Variance(s) of the distribution. :param E: expected value :param V: variance """ a = np.square(E) / V b = E / V return Gamma(a, b)
[ "def", "from_EV", "(", "E", ",", "V", ")", ":", "a", "=", "np", ".", "square", "(", "E", ")", "/", "V", "b", "=", "E", "/", "V", "return", "Gamma", "(", "a", ",", "b", ")" ]
26.727273
0.009868
def create_script(job_name, job_directory, job_data_arrays = '', job_setup_commands = '', job_execution_commands = '', job_post_processing_commands = '', architecture = 'linux-x64', num_tasks = 1, memory_in_GB = 2, scratch_space_in_GB = 1, runtime_string = '24:00:00...
[ "def", "create_script", "(", "job_name", ",", "job_directory", ",", "job_data_arrays", "=", "''", ",", "job_setup_commands", "=", "''", ",", "job_execution_commands", "=", "''", ",", "job_post_processing_commands", "=", "''", ",", "architecture", "=", "'linux-x64'",...
51.742857
0.015714
def prepare(self, context, stream_id): """Invoke prepare() of this custom grouping""" self.grouping.prepare(context, self.source_comp_name, stream_id, self.task_ids)
[ "def", "prepare", "(", "self", ",", "context", ",", "stream_id", ")", ":", "self", ".", "grouping", ".", "prepare", "(", "context", ",", "self", ".", "source_comp_name", ",", "stream_id", ",", "self", ".", "task_ids", ")" ]
57
0.011561
def get_mining_contracts(): """ Get all the mining contracts information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining contracts data is available: coin_data: {symbol1: {'BlockNumber': ..., '...
[ "def", "get_mining_contracts", "(", ")", ":", "# load data", "url", "=", "build_url", "(", "'miningcontracts'", ")", "data", "=", "load_data", "(", "url", ")", "coin_data", "=", "data", "[", "'CoinData'", "]", "mining_data", "=", "data", "[", "'MiningData'", ...
24.833333
0.061975
def FindText(self, text: str, backward: bool, ignoreCase: bool) -> 'TextRange': """ Call IUIAutomationTextRange::FindText. text: str, backward: bool, True if the last occurring text range should be returned instead of the first; otherwise False. ignoreCase: bool, True if case sho...
[ "def", "FindText", "(", "self", ",", "text", ":", "str", ",", "backward", ":", "bool", ",", "ignoreCase", ":", "bool", ")", "->", "'TextRange'", ":", "textRange", "=", "self", ".", "textRange", ".", "FindText", "(", "text", ",", "int", "(", "backward",...
61.416667
0.008021
def _decoded_matrix_region(decoder, region, corrections): """A context manager for `DmtxMessage`, created and destoyed by `dmtxDecodeMatrixRegion` and `dmtxMessageDestroy`. Args: decoder (POINTER(DmtxDecode)): region (POINTER(DmtxRegion)): corrections (int): Yields: Dmt...
[ "def", "_decoded_matrix_region", "(", "decoder", ",", "region", ",", "corrections", ")", ":", "message", "=", "dmtxDecodeMatrixRegion", "(", "decoder", ",", "region", ",", "corrections", ")", "try", ":", "yield", "message", "finally", ":", "if", "message", ":"...
28.388889
0.001894
def lindblad_operator(A, rho): r"""This function returns the action of a Lindblad operator A on a density\ matrix rho. This is defined as : .. math:: \mathcal{L}(A, \rho) = A \rho A^\dagger - (A^\dagger A \rho + \rho A^\dagger A)/2. >>> rho=define_density_matrix(3) >>> lindblad_operat...
[ "def", "lindblad_operator", "(", "A", ",", "rho", ")", ":", "a", ",", "b", "=", "sigma_operator_indices", "(", "A", ")", "# print(111, a, b)", "if", "a", "is", "not", "None", "and", "b", "is", "not", "None", ":", "Ne", "=", "A", ".", "shape", "[", ...
26.8125
0.001125
def tabulate(tabular_data, headers=(), tablefmt="simple", floatfmt="g", numalign="decimal", stralign="left", missingval=""): """Format a fixed width table for pretty printing. >>> print(tabulate([[1, 2.34], [-56, "8.999"], ["2", "10001"]])) --- --------- 1 2.34 -56...
[ "def", "tabulate", "(", "tabular_data", ",", "headers", "=", "(", ")", ",", "tablefmt", "=", "\"simple\"", ",", "floatfmt", "=", "\"g\"", ",", "numalign", "=", "\"decimal\"", ",", "stralign", "=", "\"left\"", ",", "missingval", "=", "\"\"", ")", ":", "if...
34.555944
0.002164
def parseDiskStatLine(L): """ Parse a single line from C{/proc/diskstats} into a two-tuple of the name of the device to which it corresponds (ie 'hda') and an instance of the appropriate record type (either L{partitionstat} or L{diskstat}). """ parts = L.split() device = parts[2] if len(...
[ "def", "parseDiskStatLine", "(", "L", ")", ":", "parts", "=", "L", ".", "split", "(", ")", "device", "=", "parts", "[", "2", "]", "if", "len", "(", "parts", ")", "==", "7", ":", "factory", "=", "partitionstat", "else", ":", "factory", "=", "disksta...
33.692308
0.002222
def convolve_comb_lines(lines_wave, lines_flux, sigma, crpix1, crval1, cdelt1, naxis1): """Convolve a set of lines of known wavelengths and flux. Parameters ---------- lines_wave : array like Input array with wavelengths lines_flux : array like Input array wi...
[ "def", "convolve_comb_lines", "(", "lines_wave", ",", "lines_flux", ",", "sigma", ",", "crpix1", ",", "crval1", ",", "cdelt1", ",", "naxis1", ")", ":", "# generate wavelengths for output spectrum", "xwave", "=", "crval1", "+", "(", "np", ".", "arange", "(", "n...
29.255814
0.000769
def print_commands(): """Prints all commands available from Log with their description. """ dummy_log_file = Log() commands = Log.commands() commands.sort() for cmd in commands: cmd = getattr(dummy_log_file, 'cmd_{0}'.format(cmd)) description = cmd.__doc__ if descrip...
[ "def", "print_commands", "(", ")", ":", "dummy_log_file", "=", "Log", "(", ")", "commands", "=", "Log", ".", "commands", "(", ")", "commands", ".", "sort", "(", ")", "for", "cmd", "in", "commands", ":", "cmd", "=", "getattr", "(", "dummy_log_file", ","...
30
0.00202
def scons_copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an CopytreeError is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree res...
[ "def", "scons_copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "False", ")", ":", "names", "=", "os", ".", "listdir", "(", "src", ")", "# garyo@genarts.com fix: check for dir before making dirs.", "if", "not", "os", ".", "path", ".", "exists", "(", "...
36.521739
0.00058
def radviz(self, column_names, transforms=dict(), **kwargs): """ Radviz plot. Useful for exploratory visualization, a radviz plot can show multivariate data in 2D. Conceptually, the variables (here, specified in `column_names`) are distributed evenly around the unit circle. Th...
[ "def", "radviz", "(", "self", ",", "column_names", ",", "transforms", "=", "dict", "(", ")", ",", "*", "*", "kwargs", ")", ":", "# make a copy of data", "x", "=", "self", ".", "data", "[", "column_names", "]", ".", "copy", "(", ")", "for", "k", ",", ...
39.631579
0.000432
def parse_snpeff_log(self, f): """ Go through log file looking for snpeff output """ keys = { '# Summary table': [ 'Genome', 'Number_of_variants_before_filter', 'Number_of_known_variants', 'Number_of_effects', 'Genome_total_length', 'Change_ra...
[ "def", "parse_snpeff_log", "(", "self", ",", "f", ")", ":", "keys", "=", "{", "'# Summary table'", ":", "[", "'Genome'", ",", "'Number_of_variants_before_filter'", ",", "'Number_of_known_variants'", ",", "'Number_of_effects'", ",", "'Genome_total_length'", ",", "'Chan...
44.523077
0.009804
def get_value(self, column=0, row=0): """ Returns a the value at column, row. """ x = self._widget.item(row, column) if x==None: return x else: return str(self._widget.item(row,column).text())
[ "def", "get_value", "(", "self", ",", "column", "=", "0", ",", "row", "=", "0", ")", ":", "x", "=", "self", ".", "_widget", ".", "item", "(", "row", ",", "column", ")", "if", "x", "==", "None", ":", "return", "x", "else", ":", "return", "str", ...
30
0.032389
def time_reversal_asymmetry_statistic(x, lag): """ This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} - x_{i + lag} \cdot x_{i}^2 which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) - L(X) \cdot X^2] ...
[ "def", "time_reversal_asymmetry_statistic", "(", "x", ",", "lag", ")", ":", "n", "=", "len", "(", "x", ")", "x", "=", "np", ".", "asarray", "(", "x", ")", "if", "2", "*", "lag", ">=", "n", ":", "return", "0", "else", ":", "one_lag", "=", "_roll",...
30.289474
0.008418
def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's rpm database (not generally recommended). root use root as top level directory (default: "/") CLI Examples: .. code-block...
[ "def", "file_list", "(", "*", "packages", ",", "*", "*", "kwargs", ")", ":", "cmd", "=", "[", "'rpm'", "]", "if", "kwargs", ".", "get", "(", "'root'", ")", ":", "cmd", ".", "extend", "(", "[", "'--root'", ",", "kwargs", "[", "'root'", "]", "]", ...
26.870968
0.001159
def size(): """Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters """ try: assert os != 'nt' and sys.stdout.isatty() rows, columns = os.popen('stty size', 'r').read().split() except (AssertionErr...
[ "def", "size", "(", ")", ":", "try", ":", "assert", "os", "!=", "'nt'", "and", "sys", ".", "stdout", ".", "isatty", "(", ")", "rows", ",", "columns", "=", "os", ".", "popen", "(", "'stty size'", ",", "'r'", ")", ".", "read", "(", ")", ".", "spl...
35.857143
0.001942
def _callback_new_block(self, latest_block: Dict): """Called once a new block is detected by the alarm task. Note: This should be called only once per block, otherwise there will be duplicated `Block` state changes in the log. Therefore this method should be called ...
[ "def", "_callback_new_block", "(", "self", ",", "latest_block", ":", "Dict", ")", ":", "# User facing APIs, which have on-chain side-effects, force polled the", "# blockchain to update the node's state. This force poll is used to", "# provide a consistent view to the user, e.g. a channel ope...
52.145455
0.001711
def getrange(bch, fieldname): """get the ranges for this field""" keys = ['maximum', 'minimum', 'maximum<', 'minimum>', 'type'] index = bch.objls.index(fieldname) fielddct_orig = bch.objidd[index] fielddct = copy.deepcopy(fielddct_orig) therange = {} for key in keys: therange[key] = ...
[ "def", "getrange", "(", "bch", ",", "fieldname", ")", ":", "keys", "=", "[", "'maximum'", ",", "'minimum'", ",", "'maximum<'", ",", "'minimum>'", ",", "'type'", "]", "index", "=", "bch", ".", "objls", ".", "index", "(", "fieldname", ")", "fielddct_orig",...
36.3
0.001342
def _remove_enclosure_from_url(self, text_url, tld_pos, tld): """ Removes enclosure characters from URL given in text_url. For example: (example.com) -> example.com :param str text_url: text with URL that we want to extract from enclosure of two characters :param int tld...
[ "def", "_remove_enclosure_from_url", "(", "self", ",", "text_url", ",", "tld_pos", ",", "tld", ")", ":", "enclosure_map", "=", "{", "left_char", ":", "right_char", "for", "left_char", ",", "right_char", "in", "self", ".", "_enclosure", "}", "# get position of mo...
40.047619
0.001161
def remove_callback(self, callback): """Remove callback previously registered.""" if callback in self._async_callbacks: self._async_callbacks.remove(callback)
[ "def", "remove_callback", "(", "self", ",", "callback", ")", ":", "if", "callback", "in", "self", ".", "_async_callbacks", ":", "self", ".", "_async_callbacks", ".", "remove", "(", "callback", ")" ]
45.75
0.010753
def from_rgb(r, g=None, b=None): """ Return the nearest xterm 256 color code from rgb input. """ c = r if isinstance(r, list) else [r, g, b] best = {} for index, item in enumerate(colors): d = __distance(item, c) if(not best or d <= best['distance']): best = {'distan...
[ "def", "from_rgb", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "c", "=", "r", "if", "isinstance", "(", "r", ",", "list", ")", "else", "[", "r", ",", "g", ",", "b", "]", "best", "=", "{", "}", "for", "index", ",", "it...
25.5625
0.002358
def static_to_constantrotating(frame_i, frame_r, w, t=None): """ Transform from an inertial static frame to a rotating frame. Parameters ---------- frame_i : `~gala.potential.StaticFrame` frame_r : `~gala.potential.ConstantRotatingFrame` w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynam...
[ "def", "static_to_constantrotating", "(", "frame_i", ",", "frame_r", ",", "w", ",", "t", "=", "None", ")", ":", "return", "_constantrotating_static_helper", "(", "frame_r", "=", "frame_r", ",", "frame_i", "=", "frame_i", ",", "w", "=", "w", ",", "t", "=", ...
34.761905
0.001333
def _update_method(self, view): """Decide which method to use for *view* and configure it accordingly. """ method = self._method if method == 'auto': if view.transforms.get_transform().Linear: method = 'subdivide' else: method = 'im...
[ "def", "_update_method", "(", "self", ",", "view", ")", ":", "method", "=", "self", ".", "_method", "if", "method", "==", "'auto'", ":", "if", "view", ".", "transforms", ".", "get_transform", "(", ")", ".", "Linear", ":", "method", "=", "'subdivide'", ...
39.56
0.001974
def stop(self): """Close the ZAP socket""" if self.zap_socket: self.log.debug( 'Stopping ZAP at {}'.format(self.zap_socket.LAST_ENDPOINT)) super().stop()
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "zap_socket", ":", "self", ".", "log", ".", "debug", "(", "'Stopping ZAP at {}'", ".", "format", "(", "self", ".", "zap_socket", ".", "LAST_ENDPOINT", ")", ")", "super", "(", ")", ".", "stop", ...
34
0.009569
def StopToTuple(stop): """Return tuple as expected by javascript function addStopMarkerFromList""" return (stop.stop_id, stop.stop_name, float(stop.stop_lat), float(stop.stop_lon), stop.location_type)
[ "def", "StopToTuple", "(", "stop", ")", ":", "return", "(", "stop", ".", "stop_id", ",", "stop", ".", "stop_name", ",", "float", "(", "stop", ".", "stop_lat", ")", ",", "float", "(", "stop", ".", "stop_lon", ")", ",", "stop", ".", "location_type", ")...
52.75
0.014019
def get_moments(metricParams, vary_fmax=False, vary_density=None): """ This function will calculate the various integrals (moments) that are needed to compute the metric used in template bank placement and coincidence. Parameters ----------- metricParams : metricParameters instance ...
[ "def", "get_moments", "(", "metricParams", ",", "vary_fmax", "=", "False", ",", "vary_density", "=", "None", ")", ":", "# NOTE: Unless the TaylorR2F4 metric is used the log^3 and log^4 terms are", "# not needed. As this calculation is not too slow compared to bank", "# placement we j...
43.354331
0.009766
def _process_macro_args(self): """Macro args are pretty tricky! Arg names themselves are simple, but you can set arbitrary default values, including doing stuff like: {% macro my_macro(arg="x" + ("}% {# {% endmacro %}" * 2)) %} Which makes you a jerk, but is valid jinja. """ ...
[ "def", "_process_macro_args", "(", "self", ")", ":", "# we are currently after the first parenthesis (+ any whitespace) after", "# the macro args started. You can either have the close paren, or a", "# name.", "while", "self", ".", "_parenthesis_stack", ":", "match", "=", "self", "...
48.322581
0.001309
def use_contextual_arguments(**kw_only_args_defaults): """Decorator function which allows the wrapped function to accept arguments not specified in the call from the context. Arguments whose default value is set to the Required sentinel must be supplied either by the context or the call...
[ "def", "use_contextual_arguments", "(", "*", "*", "kw_only_args_defaults", ")", ":", "def", "decorator", "(", "f", ")", ":", "# Extract any positional and positional-and-key-word arguments", "# which may be set.", "arg_names", ",", "varargs", ",", "keywords", ",", "defaul...
44.388235
0.000519
def _request(self, req_func, end_point, params=None, files=None, **kwargs): """Send a HTTP request to a Todoist API end-point. :param req_func: The request function to use e.g. get or post. :type req_func: A request function from the :class:`requests` module. :param end_point: The Todoi...
[ "def", "_request", "(", "self", ",", "req_func", ",", "end_point", ",", "params", "=", "None", ",", "files", "=", "None", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "URL", "+", "end_point", "if", "params", "and", "kwargs", ":", "pa...
43.45
0.002252
def mconsensus(args): """ %prog mconsensus *.consensus Call consensus along the stacks from cross-sample clustering. """ p = OptionParser(mconsensus.__doc__) p.add_option("--allele_counts", default="allele_counts", help="Directory to generate allele counts") add_consensus_o...
[ "def", "mconsensus", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mconsensus", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--allele_counts\"", ",", "default", "=", "\"allele_counts\"", ",", "help", "=", "\"Directory to generate allele counts\"",...
33.918033
0.001409
def get_args(func, skip=0): """ Hackish way to get the arguments of a function Parameters ---------- func : callable Function to get the arguments from skip : int, optional Arguments to skip, defaults to 0 set it to 1 to skip the ``self`` argument of a method. R...
[ "def", "get_args", "(", "func", ",", "skip", "=", "0", ")", ":", "code", "=", "getattr", "(", "func", ",", "'__code__'", ",", "None", ")", "if", "code", "is", "None", ":", "code", "=", "func", ".", "__call__", ".", "__code__", "return", "code", "."...
22.521739
0.001852
def derived_sequence(graph): """ Compute the derived sequence of the graph G The intervals of G are collapsed into nodes, intervals of these nodes are built, and the process is repeated iteratively until we obtain a single node (if the graph is not irreducible) """ deriv_seq = [graph] de...
[ "def", "derived_sequence", "(", "graph", ")", ":", "deriv_seq", "=", "[", "graph", "]", "deriv_interv", "=", "[", "]", "single_node", "=", "False", "while", "not", "single_node", ":", "interv_graph", ",", "interv_heads", "=", "intervals", "(", "graph", ")", ...
28
0.001439
def rsp_find_cycles(signal): """ Find Respiratory cycles onsets, durations and phases. Parameters ---------- signal : list or array Respiratory (RSP) signal (preferably filtered). Returns ---------- rsp_cycles : dict RSP cycles features. Example ---------- ...
[ "def", "rsp_find_cycles", "(", "signal", ")", ":", "# Compute gradient (sort of derivative)", "gradient", "=", "np", ".", "gradient", "(", "signal", ")", "# Find zero-crossings", "zeros", ",", "=", "biosppy", ".", "tools", ".", "zero_cross", "(", "signal", "=", ...
25.96875
0.000773
def not_equal(array_or_none1, array_or_none2): """ Compare two arrays that can also be None or have diffent shapes and returns a boolean. >>> a1 = numpy.array([1]) >>> a2 = numpy.array([2]) >>> a3 = numpy.array([2, 3]) >>> not_equal(a1, a2) True >>> not_equal(a1, a3) True >>...
[ "def", "not_equal", "(", "array_or_none1", ",", "array_or_none2", ")", ":", "if", "array_or_none1", "is", "None", "and", "array_or_none2", "is", "None", ":", "return", "False", "elif", "array_or_none1", "is", "None", "and", "array_or_none2", "is", "not", "None",...
29.458333
0.00137
def delete_service_bindings(self, service_name): """ Remove service bindings to applications. """ instance = self.get_instance(service_name) return self.api.delete(instance['service_bindings_url'])
[ "def", "delete_service_bindings", "(", "self", ",", "service_name", ")", ":", "instance", "=", "self", ".", "get_instance", "(", "service_name", ")", "return", "self", ".", "api", ".", "delete", "(", "instance", "[", "'service_bindings_url'", "]", ")" ]
38.666667
0.008439
def get_pagination_context( page, pages_to_show=11, url=None, size=None, extra=None, parameter_name="page" ): """ Generate Bootstrap pagination context from a page object """ pages_to_show = int(pages_to_show) if pages_to_show < 1: raise ValueError( "Pagination pages_to_show ...
[ "def", "get_pagination_context", "(", "page", ",", "pages_to_show", "=", "11", ",", "url", "=", "None", ",", "size", "=", "None", ",", "extra", "=", "None", ",", "parameter_name", "=", "\"page\"", ")", ":", "pages_to_show", "=", "int", "(", "pages_to_show"...
32.321429
0.001072
def ctor_overridable(cls): """Return true if cls has on overridable __init__.""" prev_init = getattr(cls, "__init__", None) if not callable(prev_init): return True if prev_init in [object.__init__, _auto_init]: return True if getattr(prev_init, '_clobber_ok', False): return T...
[ "def", "ctor_overridable", "(", "cls", ")", ":", "prev_init", "=", "getattr", "(", "cls", ",", "\"__init__\"", ",", "None", ")", "if", "not", "callable", "(", "prev_init", ")", ":", "return", "True", "if", "prev_init", "in", "[", "object", ".", "__init__...
33.5
0.002421
def build_assets(args): """ Build the longclaw assets """ # Get the path to the JS directory asset_path = path.join(path.dirname(longclaw.__file__), 'client') try: # Move into client dir curdir = os.path.abspath(os.curdir) os.chdir(asset_path) print('Compiling ass...
[ "def", "build_assets", "(", "args", ")", ":", "# Get the path to the JS directory", "asset_path", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "longclaw", ".", "__file__", ")", ",", "'client'", ")", "try", ":", "# Move into client dir", "curdir", ...
34.111111
0.001585