text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def destroy(self): """ A reimplemented destructor that destroys the layout widget. """ layout = self.layout if layout is not None: layout.removeFromSuperview() self.layout = None super(UiKitViewGroup, self).destroy()
[ "def", "destroy", "(", "self", ")", ":", "layout", "=", "self", ".", "layout", "if", "layout", "is", "not", "None", ":", "layout", ".", "removeFromSuperview", "(", ")", "self", ".", "layout", "=", "None", "super", "(", "UiKitViewGroup", ",", "self", ")...
30.333333
11
def _get_gcloud_records(self, gcloud_zone, page_token=None): """ Generator function which yields ResourceRecordSet for the managed gcloud zone, until there are no more records to pull. :param gcloud_zone: zone to pull records from :type gcloud_zone: google.cloud.dns.ManagedZ...
[ "def", "_get_gcloud_records", "(", "self", ",", "gcloud_zone", ",", "page_token", "=", "None", ")", ":", "gcloud_iterator", "=", "gcloud_zone", ".", "list_resource_record_sets", "(", "page_token", "=", "page_token", ")", "for", "gcloud_record", "in", "gcloud_iterato...
46.636364
15.363636
def intersects_all(self, other): """ Returns True if each segmentlist in other intersects the corresponding segmentlist in self; returns False if this is not the case, or if other is empty. See also: .intersects(), .all_intersects(), .all_intersects_all() """ return all(key in self and self[key].inte...
[ "def", "intersects_all", "(", "self", ",", "other", ")", ":", "return", "all", "(", "key", "in", "self", "and", "self", "[", "key", "]", ".", "intersects", "(", "value", ")", "for", "key", ",", "value", "in", "other", ".", "iteritems", "(", ")", ")...
34.181818
21.818182
def _getDistances(self, inputPattern, partitionId=None): """Return the distances from inputPattern to all stored patterns. :param inputPattern The pattern from which distances to all other patterns are returned :param partitionId If provided, ignore all training vectors with this partition...
[ "def", "_getDistances", "(", "self", ",", "inputPattern", ",", "partitionId", "=", "None", ")", ":", "if", "not", "self", ".", "_finishedLearning", ":", "self", ".", "finishLearning", "(", ")", "self", ".", "_finishedLearning", "=", "True", "if", "self", "...
33.862069
21.586207
def _get_callsites(self, function_address): """ Get where a specific function is called. :param function_address: Address of the target function :return: A list of CFGNodes whose exits include a call/jump to the given function """ all_predecessors =...
[ "def", "_get_callsites", "(", "self", ",", "function_address", ")", ":", "all_predecessors", "=", "[", "]", "nodes", "=", "self", ".", "get_all_nodes", "(", "function_address", ")", "for", "n", "in", "nodes", ":", "predecessors", "=", "list", "(", "self", ...
35.2
20
def validate(cls, partial=True, **kwargs): """ Validate kwargs before setting attributes on the model """ data = kwargs if not partial: data = dict(**kwargs, **{col.name: None for col in cls.__table__.c if col.name not in kwargs}) ...
[ "def", "validate", "(", "cls", ",", "partial", "=", "True", ",", "*", "*", "kwargs", ")", ":", "data", "=", "kwargs", "if", "not", "partial", ":", "data", "=", "dict", "(", "*", "*", "kwargs", ",", "*", "*", "{", "col", ".", "name", ":", "None"...
34.095238
14
def _set_best(self, v, load=False): """ Setter method for best, mapped from YANG variable /routing_system/route_map/content/match/additional_paths/advertise_set/best (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_best is considered as a private method. Back...
[ "def", "_set_best", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
87.583333
43.958333
def get_diff(original, fixed, file_name, original_label='original', fixed_label='fixed'): """Return text of unified diff between original and fixed.""" original, fixed = original.splitlines(True), fixed.splitlines(True) newline = '\n' from difflib import unified_diff diff = unified_dif...
[ "def", "get_diff", "(", "original", ",", "fixed", ",", "file_name", ",", "original_label", "=", "'original'", ",", "fixed_label", "=", "'fixed'", ")", ":", "original", ",", "fixed", "=", "original", ".", "splitlines", "(", "True", ")", ",", "fixed", ".", ...
41.5
17.777778
def report(self): """ Report elapsed time. """ if not self.end_time: self.end() print ("Time: {} mins".format((self.end_time - self.start_time )/ 60))
[ "def", "report", "(", "self", ")", ":", "if", "not", "self", ".", "end_time", ":", "self", ".", "end", "(", ")", "print", "(", "\"Time: {} mins\"", ".", "format", "(", "(", "self", ".", "end_time", "-", "self", ".", "start_time", ")", "/", "60", ")...
28
14.571429
def categorical(pvals, size=None, random_state=None): """Return random integer from a categorical distribution Parameters ---------- pvals : sequence of floats, length p Probabilities of each of the ``p`` different outcomes. These should sum to 1. size : int or tuple of ints, optio...
[ "def", "categorical", "(", "pvals", ",", "size", "=", "None", ",", "random_state", "=", "None", ")", ":", "cumsum", "=", "np", ".", "cumsum", "(", "pvals", ")", "if", "size", "is", "None", ":", "size", "=", "(", "1", ",", ")", "axis", "=", "0", ...
34.807692
17.461538
def service_details(self, io_handler, service_id): """ Prints the details of the service with the given ID """ svc_ref = self._context.get_service_reference( None, "({0}={1})".format(constants.SERVICE_ID, service_id) ) if svc_ref is None: io_handle...
[ "def", "service_details", "(", "self", ",", "io_handler", ",", "service_id", ")", ":", "svc_ref", "=", "self", ".", "_context", ".", "get_service_reference", "(", "None", ",", "\"({0}={1})\"", ".", "format", "(", "constants", ".", "SERVICE_ID", ",", "service_i...
35.558824
18.382353
def get_users(self, omit_empty_organisms=False): """ Get all users known to this Apollo instance :type omit_empty_organisms: bool :param omit_empty_organisms: Will omit users having no access to any organism :rtype: list of dicts :return: list of user info dictionaries ...
[ "def", "get_users", "(", "self", ",", "omit_empty_organisms", "=", "False", ")", ":", "payload", "=", "{", "}", "if", "omit_empty_organisms", ":", "payload", "[", "'omitEmptyOrganisms'", "]", "=", "omit_empty_organisms", "res", "=", "self", ".", "post", "(", ...
34.375
15.5
def parseGameTree(self): """ Called when "(" encountered, ends when a matching ")" encountered. Parses and returns one 'GameTree' from 'self.data'. Raises 'GameTreeParseError' if a problem is encountered.""" g = GameTree() while self.index < self.datalen: match = self.reGameTreeNext.match(self.data, self...
[ "def", "parseGameTree", "(", "self", ")", ":", "g", "=", "GameTree", "(", ")", "while", "self", ".", "index", "<", "self", ".", "datalen", ":", "match", "=", "self", ".", "reGameTreeNext", ".", "match", "(", "self", ".", "data", ",", "self", ".", "...
37.47619
14.095238
def availability_zone_list(request): """Utility method to retrieve a list of availability zones.""" try: return api.nova.availability_zone_list(request) except Exception: exceptions.handle(request, _('Unable to retrieve Nova availability zones.')) return []
[ "def", "availability_zone_list", "(", "request", ")", ":", "try", ":", "return", "api", ".", "nova", ".", "availability_zone_list", "(", "request", ")", "except", "Exception", ":", "exceptions", ".", "handle", "(", "request", ",", "_", "(", "'Unable to retriev...
39
16.75
def _checkremove_que(self, word): """If word ends in -que and if word is not in pass list, strip -que""" in_que_pass_list = False que_pass_list = ['atque', 'quoque', 'neque', 'itaque', 'absque', ...
[ "def", "_checkremove_que", "(", "self", ",", "word", ")", ":", "in_que_pass_list", "=", "False", "que_pass_list", "=", "[", "'atque'", ",", "'quoque'", ",", "'neque'", ",", "'itaque'", ",", "'absque'", ",", "'apsque'", ",", "'abusque'", ",", "'adaeque'", ","...
32.712121
7.984848
def download_file_part_run(download_context): """ Function run by CreateProjectCommand to create the project. Runs in a background process. :param download_context: UploadContext: contains data service setup and project name to create. """ destination_dir, file_url_data_dict, seek_amt, bytes_to_...
[ "def", "download_file_part_run", "(", "download_context", ")", ":", "destination_dir", ",", "file_url_data_dict", ",", "seek_amt", ",", "bytes_to_read", "=", "download_context", ".", "params", "project_file", "=", "ProjectFile", "(", "file_url_data_dict", ")", "local_pa...
51.285714
21.714286
def _from_string(cls, serialized): """ Return an instance of `cls` parsed from its `serialized` form. Args: cls: The :class:`OpaqueKey` subclass. serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed. Raises: InvalidKe...
[ "def", "_from_string", "(", "cls", ",", "serialized", ")", ":", "try", ":", "def_key", ",", "aside_type", "=", "_split_keys_v2", "(", "serialized", ")", "return", "cls", "(", "DefinitionKey", ".", "from_string", "(", "def_key", ")", ",", "aside_type", ")", ...
38.294118
22.529412
def _get_ngrams(segment, max_order): """Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n...
[ "def", "_get_ngrams", "(", "segment", ",", "max_order", ")", ":", "ngram_counts", "=", "collections", ".", "Counter", "(", ")", "for", "order", "in", "range", "(", "1", ",", "max_order", "+", "1", ")", ":", "for", "i", "in", "range", "(", "0", ",", ...
34.555556
17.055556
def is_entailed_by(self, other): """ Other is more specific than self. Other is bounded within self. """ other = self.coerce(other) to_i = self.to_i return to_i(other.low) >= to_i(self.low) and \ to_i(other.high) <= to_i(self.high)
[ "def", "is_entailed_by", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "coerce", "(", "other", ")", "to_i", "=", "self", ".", "to_i", "return", "to_i", "(", "other", ".", "low", ")", ">=", "to_i", "(", "self", ".", "low", ")", "...
36.25
11
def drop_tree(self): """ Removes this element from the tree, including its children and text. The tail text is joined to the previous element or parent. """ parent = self.getparent() assert parent is not None if self.tail: previous = self.getp...
[ "def", "drop_tree", "(", "self", ")", ":", "parent", "=", "self", ".", "getparent", "(", ")", "assert", "parent", "is", "not", "None", "if", "self", ".", "tail", ":", "previous", "=", "self", ".", "getprevious", "(", ")", "if", "previous", "is", "Non...
34.8
14.933333
def is_clicked(self, MouseStateType): """ Did the user depress and release the button to signify a click? MouseStateType is the button to query. Values found under StateTypes.py """ return self.previous_mouse_state.query_state(MouseStateType) and ( not self.current_mouse_...
[ "def", "is_clicked", "(", "self", ",", "MouseStateType", ")", ":", "return", "self", ".", "previous_mouse_state", ".", "query_state", "(", "MouseStateType", ")", "and", "(", "not", "self", ".", "current_mouse_state", ".", "query_state", "(", "MouseStateType", ")...
49.714286
18.857143
def clear_db(): """Clear the entire db.""" cursor = '0' while cursor != 0: cursor, keys = DB.scan(cursor, match='*', count=5000) if keys: DB.delete(*keys)
[ "def", "clear_db", "(", ")", ":", "cursor", "=", "'0'", "while", "cursor", "!=", "0", ":", "cursor", ",", "keys", "=", "DB", ".", "scan", "(", "cursor", ",", "match", "=", "'*'", ",", "count", "=", "5000", ")", "if", "keys", ":", "DB", ".", "de...
26.857143
17.714286
def withFile(file, func, mode='r', expand=False): """Pass `file` to `func` and ensure the file is closed afterwards. If `file` is a string, open according to `mode`; if `expand` is true also expand user and vars. """ file = _normalizeToFile(file, mode=mode, expand=expand) try: return ...
[ "def", "withFile", "(", "file", ",", "func", ",", "mode", "=", "'r'", ",", "expand", "=", "False", ")", ":", "file", "=", "_normalizeToFile", "(", "file", ",", "mode", "=", "mode", ",", "expand", "=", "expand", ")", "try", ":", "return", "func", "(...
43.75
12.5
def uninstall(self): """ Remove agent's files from remote host """ log_filename = "agent_{host}.log".format(host=self.host) data_filename = "agent_{host}.rawdata".format(host=self.host) try: if self.session: self.session.send("stop\n") ...
[ "def", "uninstall", "(", "self", ")", ":", "log_filename", "=", "\"agent_{host}.log\"", ".", "format", "(", "host", "=", "self", ".", "host", ")", "data_filename", "=", "\"agent_{host}.rawdata\"", ".", "format", "(", "host", "=", "self", ".", "host", ")", ...
37.264706
14.911765
def pyLocal(self, time_zone=''): ''' a method to report a python datetime from a labDT object :param time_zone: [optional] string with timezone to report in :return: string with date and time info ''' # validate inputs get_tz = get_localzone() title = 'Ti...
[ "def", "pyLocal", "(", "self", ",", "time_zone", "=", "''", ")", ":", "# validate inputs\r", "get_tz", "=", "get_localzone", "(", ")", "title", "=", "'Timezone input for labDT.pyLocal'", "if", "time_zone", ":", "# if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'...
37.75
22.8125
def emit(self, event, *event_args): """Call the registered listeners for ``event``. The listeners will be called with any extra arguments passed to :meth:`emit` first, and then the extra arguments passed to :meth:`on` """ listeners = self._listeners[event][:] for listene...
[ "def", "emit", "(", "self", ",", "event", ",", "*", "event_args", ")", ":", "listeners", "=", "self", ".", "_listeners", "[", "event", "]", "[", ":", "]", "for", "listener", "in", "listeners", ":", "args", "=", "list", "(", "event_args", ")", "+", ...
43
14.166667
def perform_remote_action(i): """ Input: { See 'perform_action' function } Output: { See 'perform_action' function } """ # Import modules compatible with Python 2.x and 3.x import urllib try: import urllib.request as urllib2 except: import urllib2 # pragma: no cover try: fr...
[ "def", "perform_remote_action", "(", "i", ")", ":", "# Import modules compatible with Python 2.x and 3.x", "import", "urllib", "try", ":", "import", "urllib", ".", "request", "as", "urllib2", "except", ":", "import", "urllib2", "# pragma: no cover", "try", ":", "from"...
26.347222
23.291667
def to_native(self, value, context=None): """ Schematics deserializer override :return: ToOne instance """ if isinstance(value, ToOne): return value value = self._cast_rid(value) return ToOne(self.rtype, self.field, rid=value)
[ "def", "to_native", "(", "self", ",", "value", ",", "context", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "ToOne", ")", ":", "return", "value", "value", "=", "self", ".", "_cast_rid", "(", "value", ")", "return", "ToOne", "(", "sel...
25.363636
15.272727
def interfaces(self): """list[dict]: A list of dictionary items describing the operational state of interfaces. This method currently only lists the Physical Interfaces ( Gigabitethernet, tengigabitethernet, fortygigabitethernet, hundredgigabitethernet) and Loopback interfaces. ...
[ "def", "interfaces", "(", "self", ")", ":", "urn", "=", "\"{urn:brocade.com:mgmt:brocade-interface-ext}\"", "int_ns", "=", "'urn:brocade.com:mgmt:brocade-interface-ext'", "result", "=", "[", "]", "has_more", "=", "''", "last_interface_name", "=", "''", "last_interface_typ...
51.283784
21.459459
def from_file(self, filename): """Read configuration from a .rc file. `filename` is a file name to read. """ self.attempted_config_files.append(filename) cp = HandyConfigParser() files_read = cp.read(filename) if files_read is not None: # return value changed ...
[ "def", "from_file", "(", "self", ",", "filename", ")", ":", "self", ".", "attempted_config_files", ".", "append", "(", "filename", ")", "cp", "=", "HandyConfigParser", "(", ")", "files_read", "=", "cp", ".", "read", "(", "filename", ")", "if", "files_read"...
32.55
17.4
def gibbs_binding_energy(self, eads=False): """ Returns the adsorption energy or Gibb's binding energy of an adsorbate on a surface Args: eads (bool): Whether to calculate the adsorption energy (True) or the binding energy (False) which is just ...
[ "def", "gibbs_binding_energy", "(", "self", ",", "eads", "=", "False", ")", ":", "n", "=", "self", ".", "get_unit_primitive_area", "Nads", "=", "self", ".", "Nads_in_slab", "BE", "=", "(", "self", ".", "energy", "-", "n", "*", "self", ".", "clean_entry",...
39.1875
17.1875
def _find_filepath_in_roots(filename): """Look for filename in all MEDIA_ROOTS, and return the first one found.""" for root in settings.DJANGO_STATIC_MEDIA_ROOTS: filepath = _filename2filepath(filename, root) if os.path.isfile(filepath): return filepath, root # havent found it in...
[ "def", "_find_filepath_in_roots", "(", "filename", ")", ":", "for", "root", "in", "settings", ".", "DJANGO_STATIC_MEDIA_ROOTS", ":", "filepath", "=", "_filename2filepath", "(", "filename", ",", "root", ")", "if", "os", ".", "path", ".", "isfile", "(", "filepat...
40.444444
14.5
def load_hgnc(adapter, genes=None, ensembl_lines=None, hgnc_lines=None, exac_lines=None, mim2gene_lines=None, genemap_lines=None, hpo_lines=None, transcripts_lines=None, build='37', omim_api_key=''): """Load Genes and transcripts into the database If no resources are provided the co...
[ "def", "load_hgnc", "(", "adapter", ",", "genes", "=", "None", ",", "ensembl_lines", "=", "None", ",", "hgnc_lines", "=", "None", ",", "exac_lines", "=", "None", ",", "mim2gene_lines", "=", "None", ",", "genemap_lines", "=", "None", ",", "hpo_lines", "=", ...
41.121951
21.609756
def _args_checks_gen(self, decorated_function, function_spec, arg_specs): """ Generate checks for positional argument testing :param decorated_function: function decorator :param function_spec: function inspect information :param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate...
[ "def", "_args_checks_gen", "(", "self", ",", "decorated_function", ",", "function_spec", ",", "arg_specs", ")", ":", "inspected_args", "=", "function_spec", ".", "args", "args_check", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "inspected_args",...
37.166667
23.166667
def unlink_android(self, path, pkg): """ Unlink's the android project to this library. 1. In the app's android/settings.gradle, it removes the following lines (if they exist): include ':<project-name>' project(':<project-name>').projectDir = new ...
[ "def", "unlink_android", "(", "self", ",", "path", ",", "pkg", ")", ":", "bundle_id", "=", "self", ".", "ctx", "[", "'bundle_id'", "]", "#: Check if it's already linked", "with", "open", "(", "join", "(", "'android'", ",", "'settings.gradle'", ")", ")", "as"...
41.695946
20.628378
def update_scheduled_time(self, when): """ Updates a scheduled task's date to the given date. If the task is not scheduled, a TaskNotFound exception is raised. """ tiger = self.tiger ts = get_timestamp(when) assert ts pipeline = tiger.connection.pipeline...
[ "def", "update_scheduled_time", "(", "self", ",", "when", ")", ":", "tiger", "=", "self", ".", "tiger", "ts", "=", "get_timestamp", "(", "when", ")", "assert", "ts", "pipeline", "=", "tiger", ".", "connection", ".", "pipeline", "(", ")", "key", "=", "t...
33.047619
18.380952
def to_int(data): """ :params data: proquint :returns: proquint decoded into an integer :type data: string :rtype: int """ if not isinstance(data, basestring): raise TypeError('Input must be string') res = 0 for part in data.split('-'): if len(part) != 5: ...
[ "def", "to_int", "(", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "basestring", ")", ":", "raise", "TypeError", "(", "'Input must be string'", ")", "res", "=", "0", "for", "part", "in", "data", ".", "split", "(", "'-'", ")", ":", "...
29.2
15.6
def _async_route(self, msg, in_stream=None): """ Arrange for `msg` to be forwarded towards its destination. If its destination is the local context, then arrange for it to be dispatched using the local handlers. This is a lower overhead version of :meth:`route` that may only be ...
[ "def", "_async_route", "(", "self", ",", "msg", ",", "in_stream", "=", "None", ")", ":", "_vv", "and", "IOLOG", ".", "debug", "(", "'%r._async_route(%r, %r)'", ",", "self", ",", "msg", ",", "in_stream", ")", "if", "len", "(", "msg", ".", "data", ")", ...
39.650794
22.126984
def do_help(self, arg): """h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. "help pdb" shows the full pdb documentation. "help exec" gives help on the ! command. """ if not arg: ...
[ "def", "do_help", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ":", "return", "cmd", ".", "Cmd", ".", "do_help", "(", "self", ",", "arg", ")", "try", ":", "try", ":", "topic", "=", "getattr", "(", "self", ",", "'help_'", "+", "arg", "...
38.434783
14.782609
def is_reduced_grid(nc, variable): ''' Returns True if the feature-type of the variable corresponds to a reduced horizontal grid. :param netCDF4.Dataset nc: An open netCDF dataset :param str variable: name of the variable to check ''' axis_map = get_axis_map(nc, variable) if 'X' not in...
[ "def", "is_reduced_grid", "(", "nc", ",", "variable", ")", ":", "axis_map", "=", "get_axis_map", "(", "nc", ",", "variable", ")", "if", "'X'", "not", "in", "axis_map", ":", "return", "False", "if", "'Y'", "not", "in", "axis_map", ":", "return", "False", ...
28.88
19.04
def get_available_course_modes(self, request, course_run_id, enterprise_catalog): """ Return the available course modes for the course run. The provided EnterpriseCustomerCatalog is used to filter and order the course modes returned using the EnterpriseCustomerCatalog's field "e...
[ "def", "get_available_course_modes", "(", "self", ",", "request", ",", "course_run_id", ",", "enterprise_catalog", ")", ":", "modes", "=", "EnrollmentApiClient", "(", ")", ".", "get_course_modes", "(", "course_run_id", ")", "if", "not", "modes", ":", "LOGGER", "...
48.3
28.033333
def _evaluate(self,x,return_indices = False): ''' Returns the level of the interpolated function at each value in x. Only called internally by HARKinterpolator1D.__call__ (etc). ''' return self._evalOrDer(x,True,False)[0]
[ "def", "_evaluate", "(", "self", ",", "x", ",", "return_indices", "=", "False", ")", ":", "return", "self", ".", "_evalOrDer", "(", "x", ",", "True", ",", "False", ")", "[", "0", "]" ]
42.833333
22.166667
def _get_json_content_from_folder(folder): """yield objects from json files in the folder and subfolders.""" for dirpath, dirnames, filenames in os.walk(folder): for filename in filenames: if filename.lower().endswith(".json"): filepath = os.path.join(dirpath, filename) ...
[ "def", "_get_json_content_from_folder", "(", "folder", ")", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "folder", ")", ":", "for", "filename", "in", "filenames", ":", "if", "filename", ".", "lower", "(", ")", "...
53
10.875
def extraction(self, event_collection, timeframe=None, timezone=None, filters=None, latest=None, email=None, property_names=None): """ Performs a data extraction Returns either a JSON object of events or a response indicating an email will be sent to you with data. ...
[ "def", "extraction", "(", "self", ",", "event_collection", ",", "timeframe", "=", "None", ",", "timezone", "=", "None", ",", "filters", "=", "None", ",", "latest", "=", "None", ",", "email", "=", "None", ",", "property_names", "=", "None", ")", ":", "p...
60.681818
33.818182
def __recv_log_set_exc_and_wait(self, msg, level=None, wait_seconds=CONN_RETRY_DELAY_SECONDS): """Equivalent to __send_log_set_exc_and_wait but for receiver thread""" logger.log( ((logging.DEBUG if self.__recv_exc else logging.ERROR) if level is None else level), msg, ...
[ "def", "__recv_log_set_exc_and_wait", "(", "self", ",", "msg", ",", "level", "=", "None", ",", "wait_seconds", "=", "CONN_RETRY_DELAY_SECONDS", ")", ":", "logger", ".", "log", "(", "(", "(", "logging", ".", "DEBUG", "if", "self", ".", "__recv_exc", "else", ...
47
21.777778
def add_comment(self, line: str) -> None: '''Keeping track of "last comment" for section and parameter ''' # the rule is like # # # comment line --> add to last comment # blank line --> clears last comment # [ ] --> use last comment # parameter: --> use last comm...
[ "def", "add_comment", "(", "self", ",", "line", ":", "str", ")", "->", "None", ":", "# the rule is like", "#", "# # comment line --> add to last comment", "# blank line --> clears last comment", "# [ ] --> use last comment", "# parameter: --> use last comment", "# All others: cl...
41.909091
11.909091
def do_handshake(self): """Perform a handshake with the peer This method forces an explicit handshake to be performed with either the client or server peer. """ _logger.debug("Initiating handshake...") try: self._wrap_socket_library_call( lam...
[ "def", "do_handshake", "(", "self", ")", ":", "_logger", ".", "debug", "(", "\"Initiating handshake...\"", ")", "try", ":", "self", ".", "_wrap_socket_library_call", "(", "lambda", ":", "SSL_do_handshake", "(", "self", ".", "_ssl", ".", "value", ")", ",", "E...
36.277778
15.777778
def save(cls, dct, filename): r""" Saves data from the given dictionary into the specified file. Parameters ---------- dct : dictionary A dictionary to save to file, presumably obtained from the ``to_dict`` method of this class. filename : string...
[ "def", "save", "(", "cls", ",", "dct", ",", "filename", ")", ":", "fname", "=", "cls", ".", "_parse_filename", "(", "filename", "=", "filename", ",", "ext", "=", "'dct'", ")", "dct", "=", "sanitize_dict", "(", "dct", ")", "with", "open", "(", "fname"...
30.5
17.222222
def recursive_model_update(model, props): """ Recursively updates attributes on a model including other models. If the type of the new model matches the old model properties are simply updated, otherwise the model is replaced. """ updates = {} valid_properties = model.properties_with_values(...
[ "def", "recursive_model_update", "(", "model", ",", "props", ")", ":", "updates", "=", "{", "}", "valid_properties", "=", "model", ".", "properties_with_values", "(", ")", "for", "k", ",", "v", "in", "props", ".", "items", "(", ")", ":", "if", "isinstanc...
41.052632
14.631579
def Email(v): """Verify that the value is an Email or not. >>> s = Schema(Email()) >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a.com") >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a@.com") >>> with raises(MultipleInvalid, 'expected an Email'): ... ...
[ "def", "Email", "(", "v", ")", ":", "try", ":", "if", "not", "v", "or", "\"@\"", "not", "in", "v", ":", "raise", "EmailInvalid", "(", "\"Invalid Email\"", ")", "user_part", ",", "domain_part", "=", "v", ".", "rsplit", "(", "'@'", ",", "1", ")", "if...
29.565217
19.608696
def from_transformation_string(cls, transformation_string="a,b,c;0,0,0"): """ Construct SpaceGroupTransformation from its transformation string. :param P: matrix :param p: origin shift vector :return: """ P, p = JonesFaithfulTransformation.parse_transformation_str...
[ "def", "from_transformation_string", "(", "cls", ",", "transformation_string", "=", "\"a,b,c;0,0,0\"", ")", ":", "P", ",", "p", "=", "JonesFaithfulTransformation", ".", "parse_transformation_string", "(", "transformation_string", ")", "return", "cls", "(", "P", ",", ...
37.5
16.3
def _make_info(self, piece_size, progress, walker, piece_callback=None): """ Create info dict. """ # These collect the file descriptions and piece hashes file_list = [] pieces = [] # Initialize progress state hashing_secs = time.time() totalsize = -1 if s...
[ "def", "_make_info", "(", "self", ",", "piece_size", ",", "progress", ",", "walker", ",", "piece_callback", "=", "None", ")", ":", "# These collect the file descriptions and piece hashes", "file_list", "=", "[", "]", "pieces", "=", "[", "]", "# Initialize progress s...
36.341463
19.682927
def add_ipv4(self, id_network_ipv4, id_equipamento, descricao): """Allocate an IP on a network to an equipment. Insert new IP for network and associate to the equipment :param id_network_ipv4: ID for NetworkIPv4. :param id_equipamento: ID for Equipment. :param descricao: Descrip...
[ "def", "add_ipv4", "(", "self", ",", "id_network_ipv4", ",", "id_equipamento", ",", "descricao", ")", ":", "ip_map", "=", "dict", "(", ")", "ip_map", "[", "'id_network_ipv4'", "]", "=", "id_network_ipv4", "ip_map", "[", "'description'", "]", "=", "descricao", ...
39.605263
21.973684
def product_get(self, ids=None, names=None, include_fields=None, exclude_fields=None, ptype=None): """ Raw wrapper around Product.get https://bugzilla.readthedocs.io/en/latest/api/core/v1/product.html#get-product This does not perform any caching ...
[ "def", "product_get", "(", "self", ",", "ids", "=", "None", ",", "names", "=", "None", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "ptype", "=", "None", ")", ":", "if", "ids", "is", "None", "and", "names", "is", "None...
38.425532
18.255319
def parser_from_buffer(cls, fp): """Construct YamlParser from a file pointer.""" yaml = YAML(typ="safe") return cls(yaml.load(fp))
[ "def", "parser_from_buffer", "(", "cls", ",", "fp", ")", ":", "yaml", "=", "YAML", "(", "typ", "=", "\"safe\"", ")", "return", "cls", "(", "yaml", ".", "load", "(", "fp", ")", ")" ]
37.75
6
def get_param_tuples(url_rule) -> List[Tuple[str, str]]: """ Returns a list of parameter tuples in a URL rule, eg:: url_rule = '/users/<string:username>/roles/<int:id>' param_tuples = get_param_tuples(url_rule) assert param_tuples == [('string', 'username'), ('int', 'id')] """ i...
[ "def", "get_param_tuples", "(", "url_rule", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "if", "not", "url_rule", ":", "return", "[", "]", "return", "[", "(", "type_", "[", ":", "-", "1", "]", ",", "name", ")", "for", ...
36.75
16.083333
def traverse(self): """Traverse this linked list. Yields: PlasmaObjectFuture: PlasmaObjectFuture instances. """ current = self.head while current is not None: yield current current = current.next
[ "def", "traverse", "(", "self", ")", ":", "current", "=", "self", ".", "head", "while", "current", "is", "not", "None", ":", "yield", "current", "current", "=", "current", ".", "next" ]
26.3
14.7
def name(self) -> Optional[str]: """Returns name specified in Content-Disposition header or None if missed or header is malformed. """ _, params = parse_content_disposition( self.headers.get(CONTENT_DISPOSITION)) return content_disposition_filename(params, 'name')
[ "def", "name", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "_", ",", "params", "=", "parse_content_disposition", "(", "self", ".", "headers", ".", "get", "(", "CONTENT_DISPOSITION", ")", ")", "return", "content_disposition_filename", "(", "para...
38.75
10.5
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.linode.com/'): ''' Make a web call to the Linode API. ''' global LASTCALL vm_ = get_configured_provider() ratelimit_slee...
[ "def", "_query", "(", "action", "=", "None", ",", "command", "=", "None", ",", "args", "=", "None", ",", "method", "=", "'GET'", ",", "header_dict", "=", "None", ",", "data", "=", "None", ",", "url", "=", "'https://api.linode.com/'", ")", ":", "global"...
26.74359
20.487179
def _wait_for_state_change(self, target_states, update_interval=10): """ Blocking wait until target_state reached. update_interval is in seconds. Warning: state change must begin before calling this method. """ while self.state not in target_states: if self.state == ...
[ "def", "_wait_for_state_change", "(", "self", ",", "target_states", ",", "update_interval", "=", "10", ")", ":", "while", "self", ".", "state", "not", "in", "target_states", ":", "if", "self", ".", "state", "==", "'error'", ":", "raise", "Exception", "(", ...
37.230769
17.384615
def parse_value(parser, event, node): # pylint: disable=unused-argument """ Parse CIM/XML VALUE element and return the value""" value = '' (next_event, next_node) = six.next(parser) if next_event == pulldom.CHARACTERS: value = next_node.nodeValue (next_event, next_node) = six.next(pa...
[ "def", "parse_value", "(", "parser", ",", "event", ",", "node", ")", ":", "# pylint: disable=unused-argument", "value", "=", "''", "(", "next_event", ",", "next_node", ")", "=", "six", ".", "next", "(", "parser", ")", "if", "next_event", "==", "pulldom", "...
26.8125
22.5
def expand_paths(inputs): """Yield sys.path directories that might contain "old-style" packages""" seen = {} for dirname in inputs: dirname = normalize_path(dirname) if dirname in seen: continue seen[dirname] = 1 if not os.path.isdir(dirname): conti...
[ "def", "expand_paths", "(", "inputs", ")", ":", "seen", "=", "{", "}", "for", "dirname", "in", "inputs", ":", "dirname", "=", "normalize_path", "(", "dirname", ")", "if", "dirname", "in", "seen", ":", "continue", "seen", "[", "dirname", "]", "=", "1", ...
31.282051
16.615385
def _message_in_range(self, message): """ Determine whether the given message is in the range or it should be ignored (and avoid loading more chunks). """ # No entity means message IDs between chats may vary if self.entity: if self.reverse: if ...
[ "def", "_message_in_range", "(", "self", ",", "message", ")", ":", "# No entity means message IDs between chats may vary", "if", "self", ".", "entity", ":", "if", "self", ".", "reverse", ":", "if", "message", ".", "id", "<=", "self", ".", "last_id", "or", "mes...
36.2
17.666667
def query(self, attributes=None, filters=None, only_unique=True, use_attr_names=False, dtypes = None ): """Queries the dataset to retrieve the contained data. Args: attributes (list[str]): Names of attribute...
[ "def", "query", "(", "self", ",", "attributes", "=", "None", ",", "filters", "=", "None", ",", "only_unique", "=", "True", ",", "use_attr_names", "=", "False", ",", "dtypes", "=", "None", ")", ":", "# Example query from Ensembl biomart:", "#", "# <?xml version...
40.415094
20.575472
def close_all_pages(self): """Closes all tabs of the states editor""" states_to_be_closed = [] for state_identifier in self.tabs: states_to_be_closed.append(state_identifier) for state_identifier in states_to_be_closed: self.close_page(state_identifier, delete=Fal...
[ "def", "close_all_pages", "(", "self", ")", ":", "states_to_be_closed", "=", "[", "]", "for", "state_identifier", "in", "self", ".", "tabs", ":", "states_to_be_closed", ".", "append", "(", "state_identifier", ")", "for", "state_identifier", "in", "states_to_be_clo...
45.285714
10.142857
def get_codon(seq, codon_no, start_offset): """ This function takes a sequece and a codon number and returns the codon found in the sequence at that position """ seq = seq.replace("-","") codon_start_pos = int(codon_no - 1)*3 - start_offset codon = seq[codon_start_pos:codon_start_pos + 3] ...
[ "def", "get_codon", "(", "seq", ",", "codon_no", ",", "start_offset", ")", ":", "seq", "=", "seq", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", "codon_start_pos", "=", "int", "(", "codon_no", "-", "1", ")", "*", "3", "-", "start_offset", "codon", ...
36.333333
11.444444
def sdb_get_or_set_hash(uri, opts, length=8, chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)', utils=None): ''' Check if value exists in sdb. If it does, return, otherwise generate a random string and ...
[ "def", "sdb_get_or_set_hash", "(", "uri", ",", "opts", ",", "length", "=", "8", ",", "chars", "=", "'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'", ",", "utils", "=", "None", ")", ":", "if", "not", "isinstance", "(", "uri", ",", "string_types", ")", "or...
32.565217
23.869565
def ratio_split(amount, ratios): """ Split in_value according to the ratios specified in `ratios` This is special in that it ensures the returned values always sum to in_value (i.e. we avoid losses or gains due to rounding errors). As a result, this method returns a list of `Decimal` values with length...
[ "def", "ratio_split", "(", "amount", ",", "ratios", ")", ":", "ratio_total", "=", "sum", "(", "ratios", ")", "divided_value", "=", "amount", "/", "ratio_total", "values", "=", "[", "]", "for", "ratio", "in", "ratios", ":", "value", "=", "divided_value", ...
34.956522
24.369565
def extract_acl(cls, acl): """ parse an individual ACL (i.e.: world:anyone:cdrwa) """ try: scheme, rest = acl.split(":", 1) credential = ":".join(rest.split(":")[0:-1]) cdrwa = rest.split(":")[-1] except ValueError: raise cls.BadACL("Bad ACL: %s. F...
[ "def", "extract_acl", "(", "cls", ",", "acl", ")", ":", "try", ":", "scheme", ",", "rest", "=", "acl", ".", "split", "(", "\":\"", ",", "1", ")", "credential", "=", "\":\"", ".", "join", "(", "rest", ".", "split", "(", "\":\"", ")", "[", "0", "...
38.578947
12.263158
def spkw05(handle, body, center, inframe, first, last, segid, gm, n, states, epochs): # see libspice args for solution to array[][N] problem """ Write an SPK segment of type 5 given a time-ordered set of discrete states and epochs, and the gravitational parameter of a central body. h...
[ "def", "spkw05", "(", "handle", ",", "body", ",", "center", ",", "inframe", ",", "first", ",", "last", ",", "segid", ",", "gm", ",", "n", ",", "states", ",", "epochs", ")", ":", "# see libspice args for solution to array[][N] problem", "handle", "=", "ctypes...
36.652174
15.826087
def filter_indices(self, options, verbosity, *args, **kwargs): """Filter indices and execute an action for each index.""" index_name_map = { index.__class__.__name__: index for index in index_builder.indexes } # Process includes. if options['index']: ...
[ "def", "filter_indices", "(", "self", ",", "options", ",", "verbosity", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "index_name_map", "=", "{", "index", ".", "__class__", ".", "__name__", ":", "index", "for", "index", "in", "index_builder", ".",...
32.6875
16.875
def set_mutation_type(self, mut_type=''): """Sets the mutation type attribute to a single label based on attribute flags. Kwargs: mut_type (str): value to set self.mut_type """ if mut_type: # user specifies a mutation type self.mutation_type =...
[ "def", "set_mutation_type", "(", "self", ",", "mut_type", "=", "''", ")", ":", "if", "mut_type", ":", "# user specifies a mutation type", "self", ".", "mutation_type", "=", "mut_type", "else", ":", "# mutation type is taken from object attributes", "if", "not", "self"...
43.904762
12.595238
def transfer_options(cls, obj, new_obj, backend=None): """ Transfers options for all backends from one object to another. Drops any options defined in the supplied drop list. """ backend = cls.current_backend if backend is None else backend type_name = type(new_obj).__nam...
[ "def", "transfer_options", "(", "cls", ",", "obj", ",", "new_obj", ",", "backend", "=", "None", ")", ":", "backend", "=", "cls", ".", "current_backend", "if", "backend", "is", "None", "else", "backend", "type_name", "=", "type", "(", "new_obj", ")", ".",...
50.533333
19.866667
def capture_delete_records(records): """Writes all of our delete events to DynamoDB.""" for rec in records: model = create_delete_model(rec) if model: try: model.delete(condition=(CurrentSecurityGroupModel.eventTime <= rec['detail']['eventTime'])) except D...
[ "def", "capture_delete_records", "(", "records", ")", ":", "for", "rec", "in", "records", ":", "model", "=", "create_delete_model", "(", "rec", ")", "if", "model", ":", "try", ":", "model", ".", "delete", "(", "condition", "=", "(", "CurrentSecurityGroupMode...
50.818182
28.454545
def aliasstr(self): '''Concatenate the aliases tuple into a string.''' return ', '.join(repr(self.ns + x) for x in self.aliases)
[ "def", "aliasstr", "(", "self", ")", ":", "return", "', '", ".", "join", "(", "repr", "(", "self", ".", "ns", "+", "x", ")", "for", "x", "in", "self", ".", "aliases", ")" ]
43.333333
17.333333
def guess_type(self, path): """Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file's extension up in the table self.extensions_map...
[ "def", "guess_type", "(", "self", ",", "path", ")", ":", "base", ",", "ext", "=", "posixpath", ".", "splitext", "(", "path", ")", "if", "ext", "in", "self", ".", "extensions_map", ":", "return", "self", ".", "extensions_map", "[", "ext", "]", "ext", ...
32.956522
16.913043
def convert_activation(builder, layer, input_names, output_names, keras_layer): """ Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get ...
[ "def", "convert_activation", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", ...
37.635135
16.283784
def addToPrepares(self, prepare: Prepare, sender: str): """ Add the specified PREPARE to this replica's list of received PREPAREs and try sending COMMIT :param prepare: the PREPARE to add to the list """ # BLS multi-sig: self._bls_bft_replica.process_prepare(prep...
[ "def", "addToPrepares", "(", "self", ",", "prepare", ":", "Prepare", ",", "sender", ":", "str", ")", ":", "# BLS multi-sig:", "self", ".", "_bls_bft_replica", ".", "process_prepare", "(", "prepare", ",", "sender", ")", "self", ".", "prepares", ".", "addVote"...
35.538462
16.307692
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Ensure a distribution with the given Name tag does not exist. Note that CloudFront does not allow directly deleting an enabled Distribution. If such is requested, Salt will attempt to first update the dist...
[ "def", "distribution_absent", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "Name", "=", "kwargs", "[", "'Name'", "]", "if", "'Name'", "i...
36.10084
24.403361
def negate_gate(wordlen, input='x', output='~x'): """Implements two's complement negation.""" neg = bitwise_negate(wordlen, input, "tmp") inc = inc_gate(wordlen, "tmp", output) return neg >> inc
[ "def", "negate_gate", "(", "wordlen", ",", "input", "=", "'x'", ",", "output", "=", "'~x'", ")", ":", "neg", "=", "bitwise_negate", "(", "wordlen", ",", "input", ",", "\"tmp\"", ")", "inc", "=", "inc_gate", "(", "wordlen", ",", "\"tmp\"", ",", "output"...
41.2
7.4
def split_by_line(content): """Split the given content into a list of items by newline. Both \r\n and \n are supported. This is done since it seems that TTY devices on POSIX systems use \r\n for newlines in some instances. If the given content is an empty string or a string of only whitespace,...
[ "def", "split_by_line", "(", "content", ")", ":", "# Make sure we don't end up splitting a string with", "# just a single trailing \\n or \\r\\n into multiple parts.", "stripped", "=", "content", ".", "strip", "(", ")", "if", "not", "stripped", ":", "return", "[", "]", "i...
34.533333
19.866667
def blank_stim(self,type=None,fill=0): '''Makes a blank version of stim. If a type is not given, returned as same type as current stim. If a column stim, will fill in blanks with ``fill``''' blank = copy.copy(self) blank.name = 'Blank' if type==None: type = self.type(...
[ "def", "blank_stim", "(", "self", ",", "type", "=", "None", ",", "fill", "=", "0", ")", ":", "blank", "=", "copy", ".", "copy", "(", "self", ")", "blank", ".", "name", "=", "'Blank'", "if", "type", "==", "None", ":", "type", "=", "self", ".", "...
41.85
18.35
def get_all_elements( node: astroid.node_classes.NodeNG ) -> Iterable[astroid.node_classes.NodeNG]: """Recursively returns all atoms in nested lists and tuples.""" if isinstance(node, (astroid.Tuple, astroid.List)): for child in node.elts: for e in get_all_elements(child): ...
[ "def", "get_all_elements", "(", "node", ":", "astroid", ".", "node_classes", ".", "NodeNG", ")", "->", "Iterable", "[", "astroid", ".", "node_classes", ".", "NodeNG", "]", ":", "if", "isinstance", "(", "node", ",", "(", "astroid", ".", "Tuple", ",", "ast...
34.9
12.4
def migrateUp(self): """ Recreate the hooks in the site store to trigger this SubScheduler. """ te = self.store.findFirst(TimedEvent, sort=TimedEvent.time.descending) if te is not None: self._transientSchedule(te.time, None)
[ "def", "migrateUp", "(", "self", ")", ":", "te", "=", "self", ".", "store", ".", "findFirst", "(", "TimedEvent", ",", "sort", "=", "TimedEvent", ".", "time", ".", "descending", ")", "if", "te", "is", "not", "None", ":", "self", ".", "_transientSchedule...
38.571429
16.571429
def fit_from_cfg(cls, df, cfgname, debug=False, outcfgname=None): """ Parameters ---------- df : DataFrame The dataframe which contains the columns to use for the estimation. cfgname : string The name of the yaml config file which describes the hedonic mod...
[ "def", "fit_from_cfg", "(", "cls", ",", "df", ",", "cfgname", ",", "debug", "=", "False", ",", "outcfgname", "=", "None", ")", ":", "logger", ".", "debug", "(", "'start: fit from configuration {}'", ".", "format", "(", "cfgname", ")", ")", "hm", "=", "cl...
41.12
19.92
def __parse(self, function_meta): """ init func as lazy functon instance Args: function_meta (dict): function meta including name, args and kwargs """ self._func = get_mapping_function( function_meta["func_name"], self.functions_mapping ) ...
[ "def", "__parse", "(", "self", ",", "function_meta", ")", ":", "self", ".", "_func", "=", "get_mapping_function", "(", "function_meta", "[", "\"func_name\"", "]", ",", "self", ".", "functions_mapping", ")", "self", ".", "func_name", "=", "self", ".", "_func"...
37.5
13.8
def id(self): """Return a unique id for the detected board, if any.""" # There are some times we want to trick the platform detection # say if a raspberry pi doesn't have the right ID, or for testing try: return os.environ['BLINKA_FORCEBOARD'] except KeyError: # no fo...
[ "def", "id", "(", "self", ")", ":", "# There are some times we want to trick the platform detection", "# say if a raspberry pi doesn't have the right ID, or for testing", "try", ":", "return", "os", ".", "environ", "[", "'BLINKA_FORCEBOARD'", "]", "except", "KeyError", ":", "...
37.486486
10.513514
def __read_device(self): """Read the state of the gamepad.""" state = XinputState() res = self.manager.xinput.XInputGetState( self.__device_number, ctypes.byref(state)) if res == XINPUT_ERROR_SUCCESS: return state if res != XINPUT_ERROR_DEVICE_NOT_CONNECTE...
[ "def", "__read_device", "(", "self", ")", ":", "state", "=", "XinputState", "(", ")", "res", "=", "self", ".", "manager", ".", "xinput", ".", "XInputGetState", "(", "self", ".", "__device_number", ",", "ctypes", ".", "byref", "(", "state", ")", ")", "i...
40.538462
11.615385
def install_payment_instruction(self, instruction, token_type="Unrestricted", transaction_id=None): """ InstallPaymentInstruction instruction: The PaymentInstruction to send, for example: MyRole=='Calle...
[ "def", "install_payment_instruction", "(", "self", ",", "instruction", ",", "token_type", "=", "\"Unrestricted\"", ",", "transaction_id", "=", "None", ")", ":", "if", "(", "transaction_id", "==", "None", ")", ":", "transaction_id", "=", "uuid", ".", "uuid4", "...
37.285714
14.714286
def get_anchor_format(a): """ Extract the resource file-type format from the anchor. """ # (. or format=) then (file_extension) then (? or $) # e.g. "...format=txt" or "...download.mp4?..." fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a) return fmt.group(1) if fmt else None
[ "def", "get_anchor_format", "(", "a", ")", ":", "# (. or format=) then (file_extension) then (? or $)", "# e.g. \"...format=txt\" or \"...download.mp4?...\"", "fmt", "=", "re", ".", "search", "(", "r\"(?:\\.|format=)(\\w+)(?:\\?.*)?$\"", ",", "a", ")", "return", "fmt", ".", ...
33.333333
12.888889
def propagateClkRst(obj): """ Propagate "clk" clock and reset "rst" signal to all subcomponents """ clk = obj.clk rst = obj.rst for u in obj._units: _tryConnect(clk, u, 'clk') _tryConnect(~rst, u, 'rst_n') _tryConnect(rst, u, 'rst')
[ "def", "propagateClkRst", "(", "obj", ")", ":", "clk", "=", "obj", ".", "clk", "rst", "=", "obj", ".", "rst", "for", "u", "in", "obj", ".", "_units", ":", "_tryConnect", "(", "clk", ",", "u", ",", "'clk'", ")", "_tryConnect", "(", "~", "rst", ","...
24.636364
14.636364
def thread_tracker_exception(self, raised_exception): """ Method is called whenever an exception is raised during registering a event :param raised_exception: raised exception :return: None """ print('Thread tracker execution was stopped by the exception. Exception: %s' % str(raised_exception)) print('Tra...
[ "def", "thread_tracker_exception", "(", "self", ",", "raised_exception", ")", ":", "print", "(", "'Thread tracker execution was stopped by the exception. Exception: %s'", "%", "str", "(", "raised_exception", ")", ")", "print", "(", "'Traceback:'", ")", "print", "(", "tr...
35.2
21.2
def clear_lock(self, key): """ Remove the lock file. """ lock_path = self._get_lock_path(key) os.remove(lock_path)
[ "def", "clear_lock", "(", "self", ",", "key", ")", ":", "lock_path", "=", "self", ".", "_get_lock_path", "(", "key", ")", "os", ".", "remove", "(", "lock_path", ")" ]
24.833333
6.833333
def getAngle(self, mode='deg'): """ return bend angle :param mode: 'deg' or 'rad' :return: deflecting angle in RAD """ if self.refresh is True: self.getMatrix() try: if self.mflag: if mode == 'deg': return self...
[ "def", "getAngle", "(", "self", ",", "mode", "=", "'deg'", ")", ":", "if", "self", ".", "refresh", "is", "True", ":", "self", ".", "getMatrix", "(", ")", "try", ":", "if", "self", ".", "mflag", ":", "if", "mode", "==", "'deg'", ":", "return", "se...
27.368421
13.263158
def time_slice(self,timerange,surf=False): ''' slice object given a time range :parameter timerange: rime range to be used. ''' if isinstance(timerange[0],str): trange = cnes_convert(timerange)[0] else: trange=timerange return self.slice('date',tr...
[ "def", "time_slice", "(", "self", ",", "timerange", ",", "surf", "=", "False", ")", ":", "if", "isinstance", "(", "timerange", "[", "0", "]", ",", "str", ")", ":", "trange", "=", "cnes_convert", "(", "timerange", ")", "[", "0", "]", "else", ":", "t...
36.333333
17.666667
def _raw_split(itxt): """ Parse HTML from text into array filled with tags end text. Source code is little bit unintutive, because it is state machine parser. For better understanding, look at http://bit.ly/1rXRcJj Example:: >>> dhtmlparser._raw_split('<html><tag params="true"></html>') ...
[ "def", "_raw_split", "(", "itxt", ")", ":", "echr", "=", "\"\"", "buff", "=", "[", "\"\"", ",", "\"\"", ",", "\"\"", ",", "\"\"", "]", "content", "=", "\"\"", "array", "=", "[", "]", "next_state", "=", "0", "inside_tag", "=", "False", "escaped", "=...
26.342593
20.972222
def ip_rtm_config_route_static_route_oif_static_route_dest(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:brocade.c...
[ "def", "ip_rtm_config_route_static_route_oif_static_route_dest", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ip", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ip\"", ",", "xmlns", "=",...
60.058824
28.470588
def parse_args(args, kwargs): """Returns a kwargs dictionary by turning args into kwargs""" if 'style' in kwargs: args += (kwargs['style'],) del kwargs['style'] for arg in args: if not isinstance(arg, (bytes, unicode)): raise ValueError("args must be strings:" + repr(args...
[ "def", "parse_args", "(", "args", ",", "kwargs", ")", ":", "if", "'style'", "in", "kwargs", ":", "args", "+=", "(", "kwargs", "[", "'style'", "]", ",", ")", "del", "kwargs", "[", "'style'", "]", "for", "arg", "in", "args", ":", "if", "not", "isinst...
43.875
15.34375
def get_stp_mst_detail_output_has_more(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") has_more = ET.Su...
[ "def", "get_stp_mst_detail_output_has_more", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_stp_mst_detail", "=", "ET", ".", "Element", "(", "\"get_stp_mst_detail\"", ")", "config", "=", "get_s...
39.583333
12.333333
def get_called_sequence(self, section, fastq=False): """ Return either the called sequence data, if present. :param section: ['template', 'complement' or '2D'] :param fastq: If True, return a single, multiline fastq string. If False, return a tuple of (name, sequence, qstrin...
[ "def", "get_called_sequence", "(", "self", ",", "section", ",", "fastq", "=", "False", ")", ":", "event_group", "=", "'{}/BaseCalled_{}'", ".", "format", "(", "self", ".", "group_name", ",", "section", ")", "data", "=", "self", ".", "handle", ".", "get_ana...
45.833333
22.5