text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _uncompress_file(self, path): ''' Writes the current file into a file in the temporary directory. If that doesn't work, create a new file in the CDFs directory. ''' with self.file.open('rb') as f: if (self.cdfversion == 3): data_start, data_size,...
[ "def", "_uncompress_file", "(", "self", ",", "path", ")", ":", "with", "self", ".", "file", ".", "open", "(", "'rb'", ")", "as", "f", ":", "if", "(", "self", ".", "cdfversion", "==", "3", ")", ":", "data_start", ",", "data_size", ",", "cType", ",",...
33.8
0.002301
def publishApp(self, app_info, map_info=None, fsInfo=None): """Publishes apps to AGOL/Portal Args: app_info (list): A list of JSON configuration apps to publish. map_info (list): Defaults to ``None``. fsInfo (list): Defaults to ``None``. Returns: ...
[ "def", "publishApp", "(", "self", ",", "app_info", ",", "map_info", "=", "None", ",", "fsInfo", "=", "None", ")", ":", "if", "self", ".", "securityhandler", "is", "None", ":", "print", "(", "\"Security handler required\"", ")", "return", "appDet", "=", "No...
32.268293
0.00807
def put(self, thing_id='0', property_name=None): """ Handle a PUT request. thing_id -- ID of the thing this request is for property_name -- the name of the property from the URL path """ thing = self.get_thing(thing_id) if thing is None: self.set_stat...
[ "def", "put", "(", "self", ",", "thing_id", "=", "'0'", ",", "property_name", "=", "None", ")", ":", "thing", "=", "self", ".", "get_thing", "(", "thing_id", ")", "if", "thing", "is", "None", ":", "self", ".", "set_status", "(", "404", ")", "return",...
28.942857
0.00191
def poll(self): """Return pairs of run ids and results of finish event loops. """ ret = self.communicationChannel.receive_finished() self.nruns -= len(ret) return ret
[ "def", "poll", "(", "self", ")", ":", "ret", "=", "self", ".", "communicationChannel", ".", "receive_finished", "(", ")", "self", ".", "nruns", "-=", "len", "(", "ret", ")", "return", "ret" ]
33.5
0.009709
def dirint(ghi, solar_zenith, times, pressure=101325., use_delta_kt_prime=True, temp_dew=None, min_cos_zenith=0.065, max_zenith=87): """ Determine DNI from GHI using the DIRINT modification of the DISC model. Implements the modified DISC model known as "DIRINT" introduced in [1]. DIRINT ...
[ "def", "dirint", "(", "ghi", ",", "solar_zenith", ",", "times", ",", "pressure", "=", "101325.", ",", "use_delta_kt_prime", "=", "True", ",", "temp_dew", "=", "None", ",", "min_cos_zenith", "=", "0.065", ",", "max_zenith", "=", "87", ")", ":", "disc_out", ...
38.11828
0.000275
def set_single_attribute(self, other, trigger_klass, property_name): """Used to set guard the setting of an attribute which is singular and can't be set twice""" if isinstance(other, trigger_klass): # Check property exists if not hasattr(self, property_name): ra...
[ "def", "set_single_attribute", "(", "self", ",", "other", ",", "trigger_klass", ",", "property_name", ")", ":", "if", "isinstance", "(", "other", ",", "trigger_klass", ")", ":", "# Check property exists", "if", "not", "hasattr", "(", "self", ",", "property_name"...
47.285714
0.007407
def model_data(self): """str: The model location in S3. Only set if Estimator has been ``fit()``.""" if self.latest_training_job is not None: model_uri = self.sagemaker_session.sagemaker_client.describe_training_job( TrainingJobName=self.latest_training_job.name)['ModelArtifa...
[ "def", "model_data", "(", "self", ")", ":", "if", "self", ".", "latest_training_job", "is", "not", "None", ":", "model_uri", "=", "self", ".", "sagemaker_session", ".", "sagemaker_client", ".", "describe_training_job", "(", "TrainingJobName", "=", "self", ".", ...
61.636364
0.011628
def _get_handler(self, handler_class): """Return an existing class of handler.""" element = None for handler in self.handlers: if isinstance(handler, handler_class): element = handler break return element
[ "def", "_get_handler", "(", "self", ",", "handler_class", ")", ":", "element", "=", "None", "for", "handler", "in", "self", ".", "handlers", ":", "if", "isinstance", "(", "handler", ",", "handler_class", ")", ":", "element", "=", "handler", "break", "retur...
34.125
0.007143
def sync(self, expectedThreads=0): 'Wait for all but expectedThreads async threads to finish.' while len(self.unfinishedThreads) > expectedThreads: time.sleep(.3) self.checkForFinishedThreads()
[ "def", "sync", "(", "self", ",", "expectedThreads", "=", "0", ")", ":", "while", "len", "(", "self", ".", "unfinishedThreads", ")", ">", "expectedThreads", ":", "time", ".", "sleep", "(", ".3", ")", "self", ".", "checkForFinishedThreads", "(", ")" ]
45.8
0.008584
def free(self, ptr): #pylint:disable=unused-argument """ A somewhat faithful implementation of libc `free`. :param ptr: the location in memory to be freed """ raise NotImplementedError("%s not implemented for %s" % (self.free.__func__.__name__, ...
[ "def", "free", "(", "self", ",", "ptr", ")", ":", "#pylint:disable=unused-argument", "raise", "NotImplementedError", "(", "\"%s not implemented for %s\"", "%", "(", "self", ".", "free", ".", "__func__", ".", "__name__", ",", "self", ".", "__class__", ".", "__nam...
46.25
0.013263
def is_task_running(self, task, connection_failure_control=None): """ Check if a task is running according to: TASK_PENDING_STATES ['New', 'Starting', 'Pending', 'Running', 'Suspended', 'Stopping'] Args: task (dict): OneView Task resource. connection_failure_cont...
[ "def", "is_task_running", "(", "self", ",", "task", ",", "connection_failure_control", "=", "None", ")", ":", "if", "'uri'", "in", "task", ":", "try", ":", "task", "=", "self", ".", "get", "(", "task", ")", "if", "connection_failure_control", ":", "# Updat...
40.652174
0.005744
def setdocument(self, doc): """Associate a document with this element. Arguments: doc (:class:`Document`): A document Each element must be associated with a FoLiA document. """ assert isinstance(doc, Document) if not self.doc: self.doc = doc ...
[ "def", "setdocument", "(", "self", ",", "doc", ")", ":", "assert", "isinstance", "(", "doc", ",", "Document", ")", "if", "not", "self", ".", "doc", ":", "self", ".", "doc", "=", "doc", "if", "self", ".", "id", ":", "if", "self", ".", "id", "in", ...
29.65
0.009804
def _parse_css_color(color): '''_parse_css_color(css_color) -> gtk.gdk.Color''' if color.startswith("rgb(") and color.endswith(')'): r, g, b = [int(c)*257 for c in color[4:-1].split(',')] return gtk.gdk.Color(r, g, b) else: return gtk.gdk.color_parse(color)
[ "def", "_parse_css_color", "(", "color", ")", ":", "if", "color", ".", "startswith", "(", "\"rgb(\"", ")", "and", "color", ".", "endswith", "(", "')'", ")", ":", "r", ",", "g", ",", "b", "=", "[", "int", "(", "c", ")", "*", "257", "for", "c", "...
41
0.003413
def _iterable_as_config_list(s): """Format an iterable as a sequence of comma-separated strings. To match what ConfigObj expects, a single item list has a trailing comma. """ items = sorted(s) if len(items) == 1: return "%s," % (items[0],) else: return ", ".join(items)
[ "def", "_iterable_as_config_list", "(", "s", ")", ":", "items", "=", "sorted", "(", "s", ")", "if", "len", "(", "items", ")", "==", "1", ":", "return", "\"%s,\"", "%", "(", "items", "[", "0", "]", ",", ")", "else", ":", "return", "\", \"", ".", "...
30.5
0.006369
def add_screen(self, ref): """ Add Screen """ if ref not in self.screens: screen = Screen(self, ref) screen.clear() # TODO Check this is needed, new screens should be clear. self.screens[ref] = screen return self.screens[ref]
[ "def", "add_screen", "(", "self", ",", "ref", ")", ":", "if", "ref", "not", "in", "self", ".", "screens", ":", "screen", "=", "Screen", "(", "self", ",", "ref", ")", "screen", ".", "clear", "(", ")", "# TODO Check this is needed, new screens should be clear....
32.888889
0.009868
def x_position(self, filter_order=None, window_size=None, tol=0.05, Lx=None): ''' Calculate $x$-position according to: __ | C | ╲╱ a ⋅ | - - c_f | | a | x = ────────────── c_d - c_f ...
[ "def", "x_position", "(", "self", ",", "filter_order", "=", "None", ",", "window_size", "=", "None", ",", "tol", "=", "0.05", ",", "Lx", "=", "None", ")", ":", "if", "self", ".", "calibration", ".", "_c_drop", ":", "c_drop", "=", "self", ".", "calibr...
37.526316
0.003418
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'limit'", ")", "and", "self", ".", "limit", "is", "not", "None", ":", "_dict", "[", "'limit'", "]", "=", "self", ".", "limit", "return", "_dict" ]
36.666667
0.008889
def start_session(self, causal_consistency=True, default_transaction_options=None): """Start a logical session. This method takes the same parameters as :class:`~pymongo.client_session.SessionOptions`. See the :mod:`~pymongo.client_session` mo...
[ "def", "start_session", "(", "self", ",", "causal_consistency", "=", "True", ",", "default_transaction_options", "=", "None", ")", ":", "return", "self", ".", "__start_session", "(", "False", ",", "causal_consistency", "=", "causal_consistency", ",", "default_transa...
39.48
0.003956
def Open(self): """Connects to the database and creates the required tables. Raises: IOError: if the specified output file already exists. OSError: if the specified output file already exists. ValueError: if the filename is not set. """ if not self._filename: raise ValueError('M...
[ "def", "Open", "(", "self", ")", ":", "if", "not", "self", ".", "_filename", ":", "raise", "ValueError", "(", "'Missing filename.'", ")", "if", "not", "self", ".", "_append", "and", "os", ".", "path", ".", "isfile", "(", "self", ".", "_filename", ")", ...
34.480769
0.008677
def print_source_location_info(print_fn, filename, lineno, fn_name=None, f_lasti=None, remapped_file=None): """Print out a source location , e.g. the first line in line in: (/tmp.py:2 @21): <module> L -- 2 import sys,os (trepan3k) """ if remapped_f...
[ "def", "print_source_location_info", "(", "print_fn", ",", "filename", ",", "lineno", ",", "fn_name", "=", "None", ",", "f_lasti", "=", "None", ",", "remapped_file", "=", "None", ")", ":", "if", "remapped_file", ":", "mess", "=", "'(%s:%s remapped %s'", "%", ...
30.380952
0.00152
def grid_search(fn, grd, fmin=True, nproc=None): """Perform a grid search for optimal parameters of a specified function. In the simplest case the function returns a float value, and a single optimum value and corresponding parameter values are identified. If the function returns a tuple of values, eac...
[ "def", "grid_search", "(", "fn", ",", "grd", ",", "fmin", "=", "True", ",", "nproc", "=", "None", ")", ":", "if", "fmin", ":", "slct", "=", "np", ".", "argmin", "else", ":", "slct", "=", "np", ".", "argmax", "fprm", "=", "itertools", ".", "produc...
40.153846
0.000623
def reset_weights(self): """ Initialize properly model weights """ self.input_block.reset_weights() self.policy_backbone.reset_weights() self.value_backbone.reset_weights() self.action_head.reset_weights() self.value_head.reset_weights()
[ "def", "reset_weights", "(", "self", ")", ":", "self", ".", "input_block", ".", "reset_weights", "(", ")", "self", ".", "policy_backbone", ".", "reset_weights", "(", ")", "self", ".", "value_backbone", ".", "reset_weights", "(", ")", "self", ".", "action_hea...
31
0.006969
def install(self, force=False, overrides={}): """ Install the wheel into site-packages. """ # Utility to get the target directory for a particular key def get_path(key): return overrides.get(key) or self.install_paths[key] # The base target location is eithe...
[ "def", "install", "(", "self", ",", "force", "=", "False", ",", "overrides", "=", "{", "}", ")", ":", "# Utility to get the target directory for a particular key", "def", "get_path", "(", "key", ")", ":", "return", "overrides", ".", "get", "(", "key", ")", "...
44.66055
0.001005
def validate_accept(form, field): """Validate that accept have not been set.""" if field.data and form.reject.data: raise validators.ValidationError( _("Both reject and accept cannot be set at the same time.") )
[ "def", "validate_accept", "(", "form", ",", "field", ")", ":", "if", "field", ".", "data", "and", "form", ".", "reject", ".", "data", ":", "raise", "validators", ".", "ValidationError", "(", "_", "(", "\"Both reject and accept cannot be set at the same time.\"", ...
43.666667
0.007491
def resolve(self, value): """ Resolve contextual value. :param value: Contextual value. :return: If value is a function with a single parameter, which is a read-only dictionary, the return value of the function called with context properties as its parameter. If not, the value itself. "...
[ "def", "resolve", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "collections", ".", "Callable", ")", ":", "return", "value", "(", "{", "\"base_dir\"", ":", "self", ".", "__base_dir", ",", "\"profile_dir\"", ":", "self", ".",...
24.85
0.050388
def upload_attachment(self, location, data): """Upload attachment as required by CommentThread class. See CommentThread.upload_attachment for details. """ self.validate_attachment_location(location) content = data.read() if hasattr(data, 'read') else data orig_content = ...
[ "def", "upload_attachment", "(", "self", ",", "location", ",", "data", ")", ":", "self", ".", "validate_attachment_location", "(", "location", ")", "content", "=", "data", ".", "read", "(", ")", "if", "hasattr", "(", "data", ",", "'read'", ")", "else", "...
45.5
0.001794
def rpm(state, host, source, present=True): ''' Add/remove ``.rpm`` file packages. + source: filename or URL of the ``.rpm`` package + present: whether ore not the package should exist on the system URL sources with ``present=False``: If the ``.rpm`` file isn't downloaded, pyinfra can't re...
[ "def", "rpm", "(", "state", ",", "host", ",", "source", ",", "present", "=", "True", ")", ":", "# If source is a url", "if", "urlparse", "(", "source", ")", ".", "scheme", ":", "# Generate a temp filename (with .rpm extension to please yum)", "temp_filename", "=", ...
32.269231
0.001735
def has_mixture_channel(val: Any) -> bool: """Returns whether the value has a mixture channel representation. In contrast to `has_mixture` this method falls back to checking whether the value has a unitary representation via `has_channel`. Returns: If `val` has a `_has_mixture_` method and its...
[ "def", "has_mixture_channel", "(", "val", ":", "Any", ")", "->", "bool", ":", "mixture_getter", "=", "getattr", "(", "val", ",", "'_has_mixture_'", ",", "None", ")", "result", "=", "NotImplemented", "if", "mixture_getter", "is", "None", "else", "mixture_getter...
42.84
0.001826
def set_service(self, name, service_config, project=False): """ Store a ServiceConfig in the keychain """ if not self.project_config.services or name not in self.project_config.services: self._raise_service_not_valid(name) self._validate_service(name, service_config) self._se...
[ "def", "set_service", "(", "self", ",", "name", ",", "service_config", ",", "project", "=", "False", ")", ":", "if", "not", "self", ".", "project_config", ".", "services", "or", "name", "not", "in", "self", ".", "project_config", ".", "services", ":", "s...
54.857143
0.007692
def startswith(string, prefix): """ Like str.startswith, but also checks that the string starts with the given prefixes sequence of graphemes. str.startswith may return true for a prefix that is not visually represented as a prefix if a grapheme cluster is continued after the prefix ends. >>> grap...
[ "def", "startswith", "(", "string", ",", "prefix", ")", ":", "return", "string", ".", "startswith", "(", "prefix", ")", "and", "safe_split_index", "(", "string", ",", "len", "(", "prefix", ")", ")", "==", "len", "(", "prefix", ")" ]
37.230769
0.008065
def FlipAllowed(self): """Raise an error if the not keyword is used where it is not allowed.""" if not hasattr(self, 'flipped'): raise errors.ParseError('Not defined.') if not self.flipped: return if self.current_expression.operator: if not self.current_expression.operator.lower() in...
[ "def", "FlipAllowed", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'flipped'", ")", ":", "raise", "errors", ".", "ParseError", "(", "'Not defined.'", ")", "if", "not", "self", ".", "flipped", ":", "return", "if", "self", ".", "curr...
36.928571
0.009434
def p_edgesigs(self, p): 'edgesigs : edgesigs SENS_OR edgesig' p[0] = p[1] + (p[3],) p.set_lineno(0, p.lineno(1))
[ "def", "p_edgesigs", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "(", "p", "[", "3", "]", ",", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", "(", "1", ")", ")" ]
33.5
0.014599
def load_module(self, name): """ If we get this far, then there are hooks waiting to be called on import of this module. We manually load the module and then run the hooks. @param name: The name of the module to import. """ self.loaded_modules.append(name) ...
[ "def", "load_module", "(", "self", ",", "name", ")", ":", "self", ".", "loaded_modules", ".", "append", "(", "name", ")", "try", ":", "__import__", "(", "name", ",", "{", "}", ",", "{", "}", ",", "[", "]", ")", "mod", "=", "sys", ".", "modules", ...
24.619048
0.005587
def write(self, chunk): """Write unbuffered data to the client.""" if self.chunked_write and chunk: chunk_size_hex = hex(len(chunk))[2:].encode('ascii') buf = [chunk_size_hex, CRLF, chunk, CRLF] self.conn.wfile.write(EMPTY.join(buf)) else: self.con...
[ "def", "write", "(", "self", ",", "chunk", ")", ":", "if", "self", ".", "chunked_write", "and", "chunk", ":", "chunk_size_hex", "=", "hex", "(", "len", "(", "chunk", ")", ")", "[", "2", ":", "]", ".", "encode", "(", "'ascii'", ")", "buf", "=", "[...
41.625
0.005882
def xmlrpc_run(self, port=24444, bind='127.0.0.1', logRequests=False): '''Run xmlrpc server''' import umsgpack from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication try: from xmlrpc.client import Binary except ImportError: from xmlrpclib import Binar...
[ "def", "xmlrpc_run", "(", "self", ",", "port", "=", "24444", ",", "bind", "=", "'127.0.0.1'", ",", "logRequests", "=", "False", ")", ":", "import", "umsgpack", "from", "pyspider", ".", "libs", ".", "wsgi_xmlrpc", "import", "WSGIXMLRPCApplication", "try", ":"...
37.558824
0.00229
def parse_table(table_string, header, remove_rows=1): '''parse a table to json from a string, where a header is expected by default. Return a jsonified table. Parameters ========== table_string: the string table, ideally with a header header: header of expected table, must match ...
[ "def", "parse_table", "(", "table_string", ",", "header", ",", "remove_rows", "=", "1", ")", ":", "rows", "=", "[", "x", "for", "x", "in", "table_string", ".", "split", "(", "'\\n'", ")", "if", "x", "]", "rows", "=", "rows", "[", "0", "+", "remove_...
35.96
0.002167
def get_vm_list(self): """Get the list of guests that are created by SDK return userid list""" action = "list all guests in database" with zvmutils.log_and_reraise_sdkbase_error(action): guests_in_db = self._GuestDbOperator.get_guest_list() guests_migrated = self....
[ "def", "get_vm_list", "(", "self", ")", ":", "action", "=", "\"list all guests in database\"", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "guests_in_db", "=", "self", ".", "_GuestDbOperator", ".", "get_guest_list", "(", ")", ...
46.642857
0.003003
def IIR_filter_design(CentralFreq, bandwidth, transitionWidth, SampleFreq, GainStop=40, GainPass=0.01): """ Function to calculate the coefficients of an IIR filter, IMPORTANT NOTE: make_butterworth_bandpass_b_a and make_butterworth_b_a can produce IIR filters with higher sample rates and are prefereabl...
[ "def", "IIR_filter_design", "(", "CentralFreq", ",", "bandwidth", ",", "transitionWidth", ",", "SampleFreq", ",", "GainStop", "=", "40", ",", "GainPass", "=", "0.01", ")", ":", "NyquistFreq", "=", "SampleFreq", "/", "2", "if", "(", "CentralFreq", "+", "bandw...
43.977273
0.004044
def get_uploadflags(self, location): """Return uploadflags for the given server. """ uploadflags = [] server = self.defaults.servers[location] if self.sign: uploadflags.append('--sign') elif server.sign is not None: if server.sign: ...
[ "def", "get_uploadflags", "(", "self", ",", "location", ")", ":", "uploadflags", "=", "[", "]", "server", "=", "self", ".", "defaults", ".", "servers", "[", "location", "]", "if", "self", ".", "sign", ":", "uploadflags", ".", "append", "(", "'--sign'", ...
35.461538
0.002112
def __recognize_scalar(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be a scalar. Args: node: The node to recognize. expected_type: The type it is expected to be. Returns: A list of...
[ "def", "__recognize_scalar", "(", "self", ",", "node", ":", "yaml", ".", "Node", ",", "expected_type", ":", "Type", ")", "->", "RecResult", ":", "logger", ".", "debug", "(", "'Recognizing as a scalar'", ")", "if", "(", "isinstance", "(", "node", ",", "yaml...
38.777778
0.004196
def dimensions(self, *dimensions): """ Add a list of Dimension ingredients to the query. These can either be Dimension objects or strings representing dimensions on the shelf. The Dimension expression will be added to the query's select statement and to the group_by. :param dim...
[ "def", "dimensions", "(", "self", ",", "*", "dimensions", ")", ":", "for", "d", "in", "dimensions", ":", "self", ".", "_cauldron", ".", "use", "(", "self", ".", "_shelf", ".", "find", "(", "d", ",", "Dimension", ")", ")", "self", ".", "dirty", "=",...
37.941176
0.004539
def query_params(self, value=None): """ Return or set a dictionary of query params :param dict value: new dictionary of values """ if value is not None: return URL._mutate(self, query=unicode_urlencode(value, doseq=True)) query = '' if self._tuple.query is No...
[ "def", "query_params", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "URL", ".", "_mutate", "(", "self", ",", "query", "=", "unicode_urlencode", "(", "value", ",", "doseq", "=", "True", ")", ")",...
34.764706
0.004942
def add(name, function_name, cron): """ Create an event """ lambder.add_event(name=name, function_name=function_name, cron=cron)
[ "def", "add", "(", "name", ",", "function_name", ",", "cron", ")", ":", "lambder", ".", "add_event", "(", "name", "=", "name", ",", "function_name", "=", "function_name", ",", "cron", "=", "cron", ")" ]
44.666667
0.007353
def polypeptide_vector(p, start_index=0, end_index=-1, unit=True): """Vector along the Chain primitive (default is from N-terminus to C-terminus). Notes ----- `start_index` and `end_index` can be changed to examine smaller sections of the Chain, or reversed to change the direction of the vector...
[ "def", "polypeptide_vector", "(", "p", ",", "start_index", "=", "0", ",", "end_index", "=", "-", "1", ",", "unit", "=", "True", ")", ":", "if", "len", "(", "p", ")", "<=", "1", ":", "raise", "ValueError", "(", "\"Polymer should have length greater than 1. ...
32.324324
0.002435
def del_svc_comment(self, comment_id): """Delete a service comment Format of the line that triggers function call:: DEL_SVC_COMMENT;<comment_id> :param comment_id: comment id to delete :type comment_id: int :return: None """ for svc in self.daemon.servic...
[ "def", "del_svc_comment", "(", "self", ",", "comment_id", ")", ":", "for", "svc", "in", "self", ".", "daemon", ".", "services", ":", "if", "comment_id", "in", "svc", ".", "comments", ":", "svc", ".", "del_comment", "(", "comment_id", ")", "self", ".", ...
36.473684
0.002813
def onTagDel(self, name, func): ''' Register a callback for tag deletion. Args: name (str): The name of the tag or tag glob. func (function): The callback func(node, tagname, tagval). ''' if '*' in name: self.ontagdelglobs.add(name, func) ...
[ "def", "onTagDel", "(", "self", ",", "name", ",", "func", ")", ":", "if", "'*'", "in", "name", ":", "self", ".", "ontagdelglobs", ".", "add", "(", "name", ",", "func", ")", "else", ":", "self", ".", "ontagdels", "[", "name", "]", ".", "append", "...
28
0.005319
def setProgressColor( self, color ): """ Sets the color that for the progress bar for this item. :param color | <QColor> """ self._progressColor = QColor(color) self.setAlternateProgressColor(self._progressColor.darker(110))
[ "def", "setProgressColor", "(", "self", ",", "color", ")", ":", "self", ".", "_progressColor", "=", "QColor", "(", "color", ")", "self", ".", "setAlternateProgressColor", "(", "self", ".", "_progressColor", ".", "darker", "(", "110", ")", ")" ]
35.75
0.017065
def validate_ok_for_update(update): """Validate an update document.""" validate_is_mapping("update", update) # Update can not be {} if not update: raise ValueError('update only works with $ operators') first = next(iter(update)) if not first.startswith('$'): raise ValueError('upd...
[ "def", "validate_ok_for_update", "(", "update", ")", ":", "validate_is_mapping", "(", "\"update\"", ",", "update", ")", "# Update can not be {}", "if", "not", "update", ":", "raise", "ValueError", "(", "'update only works with $ operators'", ")", "first", "=", "next",...
38.333333
0.002833
def _get_nodes_from_symbol(sym): """Given a symbol and shapes, return a list of `NodeDef`s for visualizing the the graph in TensorBoard.""" if not isinstance(sym, Symbol): raise TypeError('sym must be an `mxnet.symbol.Symbol`,' ' received type {}'.format(str(type(sym)))) ...
[ "def", "_get_nodes_from_symbol", "(", "sym", ")", ":", "if", "not", "isinstance", "(", "sym", ",", "Symbol", ")", ":", "raise", "TypeError", "(", "'sym must be an `mxnet.symbol.Symbol`,'", "' received type {}'", ".", "format", "(", "str", "(", "type", "(", "sym"...
50.403226
0.001883
def construct_schema_validators(schema, context): """ Given a schema object, construct a dictionary of validators needed to validate a response matching the given schema. Special Cases: - $ref: These validators need to be Lazily evaluating so that circular validation dep...
[ "def", "construct_schema_validators", "(", "schema", ",", "context", ")", ":", "validators", "=", "ValidationDict", "(", ")", "if", "'$ref'", "in", "schema", ":", "validators", ".", "add_validator", "(", "'$ref'", ",", "SchemaReferenceValidator", "(", "schema", ...
41.657895
0.001852
def set_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an it...
[ "def", "set_plugin_filepaths", "(", "self", ",", "filepaths", ",", "except_blacklisted", "=", "True", ")", ":", "filepaths", "=", "util", ".", "to_absolute_paths", "(", "filepaths", ")", "if", "except_blacklisted", ":", "filepaths", "=", "util", ".", "remove_fro...
40.705882
0.002825
def Write(self, output_writer): """Writes the table to output writer. Args: output_writer (CLIOutputWriter): output writer. """ # Round up the column sizes to the nearest tab. for column_index, column_size in enumerate(self._column_sizes): column_size, _ = divmod(column_size, self._NUMB...
[ "def", "Write", "(", "self", ",", "output_writer", ")", ":", "# Round up the column sizes to the nearest tab.", "for", "column_index", ",", "column_size", "in", "enumerate", "(", "self", ".", "_column_sizes", ")", ":", "column_size", ",", "_", "=", "divmod", "(", ...
35.882353
0.009585
def RFC3156_micalg_from_algo(hash_algo): """ Converts a GPGME hash algorithm name to one conforming to RFC3156. GPGME returns hash algorithm names such as "SHA256", but RFC3156 says that programs need to use names such as "pgp-sha256" instead. :param str hash_algo: GPGME hash_algo :returns: th...
[ "def", "RFC3156_micalg_from_algo", "(", "hash_algo", ")", ":", "# hash_algo will be something like SHA256, but we need pgp-sha256.", "algo", "=", "gpg", ".", "core", ".", "hash_algo_name", "(", "hash_algo", ")", "if", "algo", "is", "None", ":", "raise", "GPGProblem", ...
40.352941
0.001425
def _versioned_lib_suffix(env, suffix, version): """Generate versioned shared library suffix from a unversioned one. If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'""" Verbose = False if Verbose: print("_versioned_lib_suffix: suffix= ", suffix) print("_versioned_li...
[ "def", "_versioned_lib_suffix", "(", "env", ",", "suffix", ",", "version", ")", ":", "Verbose", "=", "False", "if", "Verbose", ":", "print", "(", "\"_versioned_lib_suffix: suffix= \"", ",", "suffix", ")", "print", "(", "\"_versioned_lib_suffix: version= \"", ",", ...
43.923077
0.003431
def is_equal(self, another, limit=0.8): """ Determine two simhash are similar or not similar. :param another: another simhash. :param limit: a limit of the similarity. :return: if similarity greater than limit return true and else return false. """ if another is ...
[ "def", "is_equal", "(", "self", ",", "another", ",", "limit", "=", "0.8", ")", ":", "if", "another", "is", "None", ":", "raise", "Exception", "(", "\"Parameter another is null\"", ")", "if", "isinstance", "(", "another", ",", "int", ")", ":", "distance", ...
37.913043
0.004474
def find_first_wt_parent(self, with_ip=False): """ Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns a parent Biosample ID if its wild_type attribute is True. Args: with_ip: `bool`. True means to restrict the search to the firs...
[ "def", "find_first_wt_parent", "(", "self", ",", "with_ip", "=", "False", ")", ":", "parent_id", "=", "self", ".", "part_of_id", "if", "not", "parent_id", ":", "return", "False", "parent", "=", "Biosample", "(", "parent_id", ")", "if", "parent", ".", "wild...
46.074074
0.011811
def numYields(self): """Extract numYields counter if available (lazy).""" if not self._counters_calculated: self._counters_calculated = True self._extract_counters() return self._numYields
[ "def", "numYields", "(", "self", ")", ":", "if", "not", "self", ".", "_counters_calculated", ":", "self", ".", "_counters_calculated", "=", "True", "self", ".", "_extract_counters", "(", ")", "return", "self", ".", "_numYields" ]
33
0.008439
def count_items(self): """Counts Items in full_soup and soup. For debugging""" soup_items = self.soup.findAll('item') full_soup_items = self.full_soup.findAll('item') return len(soup_items), len(full_soup_items)
[ "def", "count_items", "(", "self", ")", ":", "soup_items", "=", "self", ".", "soup", ".", "findAll", "(", "'item'", ")", "full_soup_items", "=", "self", ".", "full_soup", ".", "findAll", "(", "'item'", ")", "return", "len", "(", "soup_items", ")", ",", ...
47.8
0.00823
def remove_duplicates(self, ws): """When this analysis is unassigned from a worksheet, this function is responsible for deleting DuplicateAnalysis objects from the ws. """ for analysis in ws.objectValues(): if IDuplicateAnalysis.providedBy(analysis) \ and ...
[ "def", "remove_duplicates", "(", "self", ",", "ws", ")", ":", "for", "analysis", "in", "ws", ".", "objectValues", "(", ")", ":", "if", "IDuplicateAnalysis", ".", "providedBy", "(", "analysis", ")", "and", "analysis", ".", "getAnalysis", "(", ")", ".", "U...
50
0.004914
def format_back( number: FormatArg, light: Optional[bool] = False, extended: Optional[bool] = False) -> str: """ Return an escape code for a back color, by number. This is a convenience method for handling the different code types all in one shot. It also handles some...
[ "def", "format_back", "(", "number", ":", "FormatArg", ",", "light", ":", "Optional", "[", "bool", "]", "=", "False", ",", "extended", ":", "Optional", "[", "bool", "]", "=", "False", ")", "->", "str", ":", "return", "_format_code", "(", "number", ",",...
29.6
0.002183
def set_index(self, index): """Display the data of the given index :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None """ item = index.internalPointer() note = item.internal_data() se...
[ "def", "set_index", "(", "self", ",", "index", ")", ":", "item", "=", "index", ".", "internalPointer", "(", ")", "note", "=", "item", ".", "internal_data", "(", ")", "self", ".", "content_lb", ".", "setText", "(", "note", ".", "content", ")", "self", ...
36
0.00361
def complete(self, text, state): """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. """ if self.use_main_ns: self.namespace = __main__.__dict__ ...
[ "def", "complete", "(", "self", ",", "text", ",", "state", ")", ":", "if", "self", ".", "use_main_ns", ":", "self", ".", "namespace", "=", "__main__", ".", "__dict__", "if", "not", "text", ".", "strip", "(", ")", ":", "if", "state", "==", "0", ":",...
29.6
0.002181
def _stringlist(*args): """ Take a lists of strings or strings and flatten these into a list of strings. Arguments: - `*args`: "" or [""...] Return: [""...] Exceptions: None """ return list(itertools.chain.from_iterable(itertools.repeat(x,1) if stringy(x) else x for x in args if x)...
[ "def", "_stringlist", "(", "*", "args", ")", ":", "return", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "itertools", ".", "repeat", "(", "x", ",", "1", ")", "if", "stringy", "(", "x", ")", "else", "x", "for", "x", "in", "args...
25.833333
0.009346
def ValidateTimezone(timezone, column_name=None, problems=None): """ Validates a non-required timezone string value using IsValidTimezone(): - if invalid adds InvalidValue error (if problems accumulator is provided) - an empty timezone string is regarded as valid! Otherwise we might end up with many d...
[ "def", "ValidateTimezone", "(", "timezone", ",", "column_name", "=", "None", ",", "problems", "=", "None", ")", ":", "if", "IsEmpty", "(", "timezone", ")", "or", "IsValidTimezone", "(", "timezone", ")", ":", "return", "True", "else", ":", "if", "problems",...
42.368421
0.009721
def set_file_path(self, path): """Update the file_path Entry widget""" self.file_path.delete(0, END) self.file_path.insert(0, path)
[ "def", "set_file_path", "(", "self", ",", "path", ")", ":", "self", ".", "file_path", ".", "delete", "(", "0", ",", "END", ")", "self", ".", "file_path", ".", "insert", "(", "0", ",", "path", ")" ]
38
0.012903
def clear_response(self, assessment_section_id, item_id): """Clears the response to an item The item appears as unanswered. If no response exists, the method simply returns. arg: assessment_section_id (osid.id.Id): ``Id`` of the ``AssessmentSection`` arg: item_id ...
[ "def", "clear_response", "(", "self", ",", "assessment_section_id", ",", "item_id", ")", ":", "if", "(", "not", "self", ".", "has_assessment_section_begun", "(", "assessment_section_id", ")", "or", "self", ".", "is_assessment_section_over", "(", "assessment_section_id...
52.083333
0.002357
def parse_buckets(self, bucket, params): """ Parse a single S3 bucket TODO: - CORS - Lifecycle - Notification ? - Get bucket's policy :param bucket: :param params: :return: """ bucket['name'] = bucket.pop('Name') a...
[ "def", "parse_buckets", "(", "self", ",", "bucket", ",", "params", ")", ":", "bucket", "[", "'name'", "]", "=", "bucket", ".", "pop", "(", "'Name'", ")", "api_client", "=", "params", "[", "'api_clients'", "]", "[", "get_s3_list_region", "(", "list", "(",...
44.666667
0.003652
def map(self, **kwargs): ''' Change a name on the fly. Compat with kr/env. ''' return { key: str(self._envars[kwargs[key]]) # str strips Entry for key in kwargs }
[ "def", "map", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "{", "key", ":", "str", "(", "self", ".", "_envars", "[", "kwargs", "[", "key", "]", "]", ")", "# str strips Entry", "for", "key", "in", "kwargs", "}" ]
48.5
0.020305
def setposition(self, position): """ The move format is in long algebraic notation. Takes list of stirngs = ['e2e4', 'd7d5'] OR FEN = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1' """ try: if isinstance(position, list): ...
[ "def", "setposition", "(", "self", ",", "position", ")", ":", "try", ":", "if", "isinstance", "(", "position", ",", "list", ")", ":", "self", ".", "send", "(", "'position startpos moves {}'", ".", "format", "(", "self", ".", "__listtostring", "(", "positio...
53.26
0.011799
def colormesh(X, Y): """ Generates line paths for a quadmesh given 2D arrays of X and Y coordinates. """ X1 = X[0:-1, 0:-1].ravel() Y1 = Y[0:-1, 0:-1].ravel() X2 = X[1:, 0:-1].ravel() Y2 = Y[1:, 0:-1].ravel() X3 = X[1:, 1:].ravel() Y3 = Y[1:, 1:].ravel() X4 = X[0:-1, 1:].rave...
[ "def", "colormesh", "(", "X", ",", "Y", ")", ":", "X1", "=", "X", "[", "0", ":", "-", "1", ",", "0", ":", "-", "1", "]", ".", "ravel", "(", ")", "Y1", "=", "Y", "[", "0", ":", "-", "1", ",", "0", ":", "-", "1", "]", ".", "ravel", "(...
26.176471
0.002169
def wait(self, token, timeout=DEFAULT_POLL_TIMEOUT): """ Wait for the job until it has been processed. This method will block for up to `timeout` seconds. This method will wait for 4 seconds after the initial request and then will call :py:meth:`cloudsight.API.image_resp...
[ "def", "wait", "(", "self", ",", "token", ",", "timeout", "=", "DEFAULT_POLL_TIMEOUT", ")", ":", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "timeout", ")", "timeout_at", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "+", ...
40.666667
0.005005
def load_from(self, other, **kwargs): '''Create a :class:`Message` by merging `other` with `self`. Values from `other` will be copied to `self` if the value was not set on `self` and is set on `other`. :param other: The :class:`Message` to copy defaults from. :type other: :class...
[ "def", "load_from", "(", "self", ",", "other", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "data", "(", ")", "other_data", "=", "other", ".", "data", "(", ")", "for", "k", ",", "v", "in", "iteritems", "(", "other_data", ")", ":",...
40
0.005747
def text_to_pango(self): """ Replaces all ampersands in `full_text` and `short_text` attributes of `self.output` with `&amp;`. It is called internally when pango markup is used. Can be called multiple times (`&amp;` won't change to `&amp;amp;`). """ def replace(...
[ "def", "text_to_pango", "(", "self", ")", ":", "def", "replace", "(", "s", ")", ":", "s", "=", "s", ".", "split", "(", "\"&\"", ")", "out", "=", "s", "[", "0", "]", "for", "i", "in", "range", "(", "len", "(", "s", ")", "-", "1", ")", ":", ...
35.478261
0.002387
def element_data_from_sym(sym): '''Obtain elemental data given an elemental symbol The given symbol is not case sensitive An exception is thrown if the symbol is not found ''' sym_lower = sym.lower() if sym_lower not in _element_sym_map: raise KeyError('No element data for symbol \'{}...
[ "def", "element_data_from_sym", "(", "sym", ")", ":", "sym_lower", "=", "sym", ".", "lower", "(", ")", "if", "sym_lower", "not", "in", "_element_sym_map", ":", "raise", "KeyError", "(", "'No element data for symbol \\'{}\\''", ".", "format", "(", "sym", ")", "...
30.333333
0.002667
def _ParseLogFileOptions(self, options): """Parses the log file options. Args: options (argparse.Namespace): command line arguments. """ self._log_file = self.ParseStringOption(options, 'log_file') if not self._log_file: local_date_time = datetime.datetime.now() self._log_file = (...
[ "def", "_ParseLogFileOptions", "(", "self", ",", "options", ")", ":", "self", ".", "_log_file", "=", "self", ".", "ParseStringOption", "(", "options", ",", "'log_file'", ")", "if", "not", "self", ".", "_log_file", ":", "local_date_time", "=", "datetime", "."...
41
0.006814
async def async_change_special_device( self, device_id: int, group_number: int, unit_number: int, enable_status: ESFlags, switches: SwitchFlags, special_status: SSFlags, high_limit: Optional[Union[int, float]], low_limit: Optional[Union[int, float]], control_h...
[ "async", "def", "async_change_special_device", "(", "self", ",", "device_id", ":", "int", ",", "group_number", ":", "int", ",", "unit_number", ":", "int", ",", "enable_status", ":", "ESFlags", ",", "switches", ":", "SwitchFlags", ",", "special_status", ":", "S...
58.72549
0.003941
def create_refresh_token(self, access_token_value): # type: (str) -> str """ Creates an refresh token bound to the specified access token. """ if access_token_value not in self.access_tokens: raise InvalidAccessToken('{} unknown'.format(access_token_value)) i...
[ "def", "create_refresh_token", "(", "self", ",", "access_token_value", ")", ":", "# type: (str) -> str", "if", "access_token_value", "not", "in", "self", ".", "access_tokens", ":", "raise", "InvalidAccessToken", "(", "'{} unknown'", ".", "format", "(", "access_token_v...
44.526316
0.006944
def _findregex(self, reg_ex, start, end, bytealigned): """Find first occurrence of a compiled regular expression. Note that this doesn't support arbitrary regexes, in particular they must match a known length. """ p = start length = len(reg_ex.pattern) # We grab...
[ "def", "_findregex", "(", "self", ",", "reg_ex", ",", "start", ",", "end", ",", "bytealigned", ")", ":", "p", "=", "start", "length", "=", "len", "(", "reg_ex", ".", "pattern", ")", "# We grab overlapping chunks of the binary representation and", "# do an ordinary...
38.935484
0.002425
def sync_repo_hook(self, repo_id): """Sync a GitHub repo's hook with the locally stored repo.""" # Get the hook that we may have set in the past gh_repo = self.api.repository_with_id(repo_id) hooks = (hook.id for hook in gh_repo.hooks() if hook.config.get('url', '') == s...
[ "def", "sync_repo_hook", "(", "self", ",", "repo_id", ")", ":", "# Get the hook that we may have set in the past", "gh_repo", "=", "self", ".", "api", ".", "repository_with_id", "(", "repo_id", ")", "hooks", "=", "(", "hook", ".", "id", "for", "hook", "in", "g...
47.368421
0.002179
def trace_filter(mode): ''' Set the trace filter mode. mode: Whether to enable the trace hook. True: Trace filtering on (skipping methods tagged @DontTrace) False: Trace filtering off (trace methods tagged @DontTrace) None/default: Toggle trace filtering. ''' global should_trace_h...
[ "def", "trace_filter", "(", "mode", ")", ":", "global", "should_trace_hook", "if", "mode", "is", "None", ":", "mode", "=", "should_trace_hook", "is", "None", "if", "mode", ":", "should_trace_hook", "=", "default_should_trace_hook", "else", ":", "should_trace_hook"...
26.052632
0.001949
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] ...
[ "def", "cli", "(", "ctx", ",", "env", ")", ":", "# Set up the environment", "env", "=", "copy", ".", "deepcopy", "(", "env", ")", "env", ".", "load_modules_from_python", "(", "routes", ".", "ALL_ROUTES", ")", "env", ".", "aliases", ".", "update", "(", "r...
30.981818
0.000569
def take_home_pay(gross_pay, employer_match, taxes_and_fees, numtype='float'): """ Calculate net take-home pay including employer retirement savings match using the formula laid out by Mr. Money Mustache: http://www.mrmoneymustache.com/2015/01/26/calculating-net-worth/ Args: gross_pay: floa...
[ "def", "take_home_pay", "(", "gross_pay", ",", "employer_match", ",", "taxes_and_fees", ",", "numtype", "=", "'float'", ")", ":", "if", "numtype", "==", "'decimal'", ":", "return", "(", "Decimal", "(", "gross_pay", ")", "+", "Decimal", "(", "employer_match", ...
35.625
0.002278
def histogram_distance(arr1, arr2, bins=None): """ This function returns the sum of the squared error Parameters: two arrays constrained to 0..1 Returns: sum of the squared error between the histograms """ eps = 1e-6 assert arr1.min() > 0 - eps assert arr1.max() < 1 + eps ...
[ "def", "histogram_distance", "(", "arr1", ",", "arr2", ",", "bins", "=", "None", ")", ":", "eps", "=", "1e-6", "assert", "arr1", ".", "min", "(", ")", ">", "0", "-", "eps", "assert", "arr1", ".", "max", "(", ")", "<", "1", "+", "eps", "assert", ...
27.958333
0.001441
def roles(self): """List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji. If roles is empty, the emoji is unrestricted. """ guild = self.guild if guild is None: return [] return [role for role in guild.roles if self._roles.has(role...
[ "def", "roles", "(", "self", ")", ":", "guild", "=", "self", ".", "guild", "if", "guild", "is", "None", ":", "return", "[", "]", "return", "[", "role", "for", "role", "in", "guild", ".", "roles", "if", "self", ".", "_roles", ".", "has", "(", "rol...
31.6
0.009231
def mp_check_impl(self, process_count): """ a multiprocessing-enabled check implementation. Will create up to process_count helper processes and use them to perform the DistJarReport and DistClassReport actions. """ from multiprocessing import Process, Queue opt...
[ "def", "mp_check_impl", "(", "self", ",", "process_count", ")", ":", "from", "multiprocessing", "import", "Process", ",", "Queue", "options", "=", "self", ".", "reporter", ".", "options", "# this is the function that will be run in a separate process,", "# which will hand...
36.952381
0.000628
def persistant_success(request, message, extra_tags='', fail_silently=False, *args, **kwargs): """ Adds a persistant message with the ``SUCCESS`` level. """ add_message(request, SUCCESS_PERSISTENT, message, extra_tags=extra_tags, fail_silently=fail_silently, *args, **kwargs)
[ "def", "persistant_success", "(", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "add_message", "(", "request", ",", "SUCCESS_PERSISTENT", ",", "message", ",...
50.333333
0.006515
def next_open(self, dt): """ Given a dt, returns the next open. If the given dt happens to be a session open, the next session's open will be returned. Parameters ---------- dt: pd.Timestamp The dt for which to get the next open. Returns ...
[ "def", "next_open", "(", "self", ",", "dt", ")", ":", "idx", "=", "next_divider_idx", "(", "self", ".", "market_opens_nanos", ",", "dt", ".", "value", ")", "return", "pd", ".", "Timestamp", "(", "self", ".", "market_opens_nanos", "[", "idx", "]", ",", ...
27.736842
0.00367
def pipeline_getter(self): "For duck-typing with *Spec types" if not self.derivable: raise ArcanaUsageError( "There is no pipeline getter for {} because it doesn't " "fallback to a derived spec".format(self)) return self._fallback.pipeline_getter
[ "def", "pipeline_getter", "(", "self", ")", ":", "if", "not", "self", ".", "derivable", ":", "raise", "ArcanaUsageError", "(", "\"There is no pipeline getter for {} because it doesn't \"", "\"fallback to a derived spec\"", ".", "format", "(", "self", ")", ")", "return",...
44
0.006369
def write_byte(self, address, value): """Writes the byte to unaddressed register in a device. """ LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address)) return self.driver.write_byte(address, value)
[ "def", "write_byte", "(", "self", ",", "address", ",", "value", ")", ":", "LOGGER", ".", "debug", "(", "\"Writing byte %s to device %s!\"", ",", "bin", "(", "value", ")", ",", "hex", "(", "address", ")", ")", "return", "self", ".", "driver", ".", "write_...
59
0.008368
def add_method(self, m, **kwargs): """Add an instance method or function Args: m: The instance method or function to store """ if isinstance(m, types.FunctionType): self['function', id(m)] = m else: f, obj = get_method_vars(m) wrke...
[ "def", "add_method", "(", "self", ",", "m", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "m", ",", "types", ".", "FunctionType", ")", ":", "self", "[", "'function'", ",", "id", "(", "m", ")", "]", "=", "m", "else", ":", "f", ",",...
29.583333
0.005464
def transform(self,x,inds=None,labels = None): """return a transformation of x using population outputs""" if inds: # return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype) # for I in inds)).transpose() return np.asar...
[ "def", "transform", "(", "self", ",", "x", ",", "inds", "=", "None", ",", "labels", "=", "None", ")", ":", "if", "inds", ":", "# return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype) ", "# for I in inds)).transpose()", "ret...
53.785714
0.027415
def p2pkh_input(outpoint, sig, pubkey, sequence=0xFFFFFFFE): ''' OutPoint, hex_string, hex_string, int -> TxIn Create a signed legacy TxIn from a p2pkh prevout ''' stack_script = '{sig} {pk}'.format(sig=sig, pk=pubkey) stack_script = script_ser.serialize(stack_script) return tb.make_legacy_i...
[ "def", "p2pkh_input", "(", "outpoint", ",", "sig", ",", "pubkey", ",", "sequence", "=", "0xFFFFFFFE", ")", ":", "stack_script", "=", "'{sig} {pk}'", ".", "format", "(", "sig", "=", "sig", ",", "pk", "=", "pubkey", ")", "stack_script", "=", "script_ser", ...
44.5
0.002755
def changes(ctx, check, dry_run): """Show all the pending PRs for a given check.""" if not dry_run and check not in get_valid_checks(): abort('Check `{}` is not an Agent-based Integration'.format(check)) # get the name of the current release tag cur_version = get_version_string(check) targe...
[ "def", "changes", "(", "ctx", ",", "check", ",", "dry_run", ")", ":", "if", "not", "dry_run", "and", "check", "not", "in", "get_valid_checks", "(", ")", ":", "abort", "(", "'Check `{}` is not an Agent-based Integration'", ".", "format", "(", "check", ")", ")...
40.847458
0.002836
def reset(self): """Reset all OneTimeProperty attributes that may have fired already.""" instdict = self.__dict__ classdict = self.__class__.__dict__ # To reset them, we simply remove them from the instance dict. At that # point, it's as if they had never been computed. On the next acces...
[ "def", "reset", "(", "self", ")", ":", "instdict", "=", "self", ".", "__dict__", "classdict", "=", "self", ".", "__class__", ".", "__dict__", "# To reset them, we simply remove them from the instance dict. At that", "# point, it's as if they had never been computed. On the ne...
54.363636
0.018092
def writeObject(self, obj, output, setReferencePosition=False): """Serializes the given object to the output. Returns output. If setReferencePosition is True, will set the position the object was written. """ def proc_variable_length(format, length): result = b'...
[ "def", "writeObject", "(", "self", ",", "obj", ",", "output", ",", "setReferencePosition", "=", "False", ")", ":", "def", "proc_variable_length", "(", "format", ",", "length", ")", ":", "result", "=", "b''", "if", "length", ">", "0b1110", ":", "result", ...
45
0.002364
def node_theta(self, node): """ Convenience function to find the node's theta angle. """ group = self.find_node_group_membership(node) return self.group_theta(group)
[ "def", "node_theta", "(", "self", ",", "node", ")", ":", "group", "=", "self", ".", "find_node_group_membership", "(", "node", ")", "return", "self", ".", "group_theta", "(", "group", ")" ]
33.333333
0.009756
def list_of_dicts_to_dict_of_lists(list_of_dictionaries): """ Takes a list of dictionaries and creates a dictionary with the combined values for each key in each dicitonary. Missing values are set to `None` for each dicitonary that does not contain a key that is present in at least...
[ "def", "list_of_dicts_to_dict_of_lists", "(", "list_of_dictionaries", ")", ":", "result", "=", "{", "}", "all_keys", "=", "set", "(", "[", "k", "for", "d", "in", "list_of_dictionaries", "for", "k", "in", "d", ".", "keys", "(", ")", "]", ")", "for", "d", ...
40.842105
0.011335
def add_type_struct_or_union(self, name, interp, node): """Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node :interp: the 010 interpreter """ self.add_type...
[ "def", "add_type_struct_or_union", "(", "self", ",", "name", ",", "interp", ",", "node", ")", ":", "self", ".", "add_type_class", "(", "name", ",", "StructUnionDef", "(", "name", ",", "interp", ",", "node", ")", ")" ]
40
0.005435
def _get_type(points, soma_class): '''get the type of the soma Args: points: Soma points soma_class(str): one of 'contour' or 'cylinder' to specify the type ''' assert soma_class in (SOMA_CONTOUR, SOMA_CYLINDER) npoints = len(points) if soma_class == SOMA_CONTOUR: retur...
[ "def", "_get_type", "(", "points", ",", "soma_class", ")", ":", "assert", "soma_class", "in", "(", "SOMA_CONTOUR", ",", "SOMA_CYLINDER", ")", "npoints", "=", "len", "(", "points", ")", "if", "soma_class", "==", "SOMA_CONTOUR", ":", "return", "{", "0", ":",...
34.366667
0.000943
def merge(self,range2): """merge this bed with another bed to make a longer bed. Returns None if on different chromosomes. keeps the options of this class (not range2) :param range2: :type range2: GenomicRange :return: bigger range with both :rtype: GenomicRange """ if self.chr != ...
[ "def", "merge", "(", "self", ",", "range2", ")", ":", "if", "self", ".", "chr", "!=", "range2", ".", "chr", ":", "return", "None", "o", "=", "type", "(", "self", ")", "(", "self", ".", "chr", ",", "min", "(", "self", ".", "start", ",", "range2"...
29.4375
0.024691