text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _parse_qualimap_rnaseq(table): """ Retrieve metrics of interest from globals table. """ out = {} for row in table.find_all("tr"): col, val = [x.text for x in row.find_all("td")] col = col.replace(":", "").strip() val = val.replace(",", "") m = {col: val} i...
[ "def", "_parse_qualimap_rnaseq", "(", "table", ")", ":", "out", "=", "{", "}", "for", "row", "in", "table", ".", "find_all", "(", "\"tr\"", ")", ":", "col", ",", "val", "=", "[", "x", ".", "text", "for", "x", "in", "row", ".", "find_all", "(", "\...
30.214286
0.002294
def prebuild_arch(self, arch): """Make the build and target directories""" path = self.get_build_dir(arch.arch) if not exists(path): info("creating {}".format(path)) shprint(sh.mkdir, '-p', path)
[ "def", "prebuild_arch", "(", "self", ",", "arch", ")", ":", "path", "=", "self", ".", "get_build_dir", "(", "arch", ".", "arch", ")", "if", "not", "exists", "(", "path", ")", ":", "info", "(", "\"creating {}\"", ".", "format", "(", "path", ")", ")", ...
39.666667
0.00823
def switch(self, idx, control): """Switch a single control of <idx>""" old = None new = None if control == 'Q': if self.PQ[idx] == 1: old = 'PQ' new = 'PV' elif self.vQ[idx] == 1: old = 'vQ' new = 'vV...
[ "def", "switch", "(", "self", ",", "idx", ",", "control", ")", ":", "old", "=", "None", "new", "=", "None", "if", "control", "==", "'Q'", ":", "if", "self", ".", "PQ", "[", "idx", "]", "==", "1", ":", "old", "=", "'PQ'", "new", "=", "'PV'", "...
28.914286
0.001912
def get_ec_names(ecfile, fasta_names): """ convert equivalence classes to their set of transcripts """ df = pd.read_table(ecfile, header=None, names=["ec", "transcripts"]) transcript_groups = [x.split(",") for x in df["transcripts"]] transcripts = [] for group in transcript_groups: t...
[ "def", "get_ec_names", "(", "ecfile", ",", "fasta_names", ")", ":", "df", "=", "pd", ".", "read_table", "(", "ecfile", ",", "header", "=", "None", ",", "names", "=", "[", "\"ec\"", ",", "\"transcripts\"", "]", ")", "transcript_groups", "=", "[", "x", "...
39.9
0.002451
def setup_cmd_parser(cls): """Returns the GitLab argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, from_date=True, token_auth=True, a...
[ "def", "setup_cmd_parser", "(", "cls", ")", ":", "parser", "=", "BackendCommandArgumentParser", "(", "cls", ".", "BACKEND", ".", "CATEGORIES", ",", "from_date", "=", "True", ",", "token_auth", "=", "True", ",", "archive", "=", "True", ")", "# GitLab options", ...
48.631579
0.001061
def _adjust_offset(self, real_wave_mfcc, algo_parameters): """ OFFSET """ self.log(u"Called _adjust_offset") self._apply_offset(offset=algo_parameters[0])
[ "def", "_adjust_offset", "(", "self", ",", "real_wave_mfcc", ",", "algo_parameters", ")", ":", "self", ".", "log", "(", "u\"Called _adjust_offset\"", ")", "self", ".", "_apply_offset", "(", "offset", "=", "algo_parameters", "[", "0", "]", ")" ]
31.5
0.010309
def format_units(v, step=None, system="si", units=None): """Format the given value in standardized units. ``system`` is either 'binary' or 'si' For more info, see: http://en.wikipedia.org/wiki/SI_prefix http://en.wikipedia.org/wiki/Binary_prefix """ if v is None: return 0, ...
[ "def", "format_units", "(", "v", ",", "step", "=", "None", ",", "system", "=", "\"si\"", ",", "units", "=", "None", ")", ":", "if", "v", "is", "None", ":", "return", "0", ",", "''", "for", "prefix", ",", "size", "in", "UnitSystems", "[", "system", ...
28.035714
0.001232
def csv2list(csv_filename, deli=',', del_blank_row=True, encoding=None): """ 将指定的 csv 文件转换为 list 返回; :param: * csv_filename: (string) csv 文件的长文件名 * deli: (string) csv 文件分隔符,默认为逗号 * del_blank_row: (string) 是否要删除空行,默认为删除 * encode: (string) 文件编码 :return: * csv_list...
[ "def", "csv2list", "(", "csv_filename", ",", "deli", "=", "','", ",", "del_blank_row", "=", "True", ",", "encoding", "=", "None", ")", ":", "with", "open", "(", "csv_filename", ",", "encoding", "=", "encoding", ")", "as", "csv_file", ":", "csv_list", "="...
24.837838
0.002094
def switch_onoff(self, device, status): """Switch a Socket""" if status == 1 or status == True or status == '1': return self.switch_on(device) else: return self.switch_off(device)
[ "def", "switch_onoff", "(", "self", ",", "device", ",", "status", ")", ":", "if", "status", "==", "1", "or", "status", "==", "True", "or", "status", "==", "'1'", ":", "return", "self", ".", "switch_on", "(", "device", ")", "else", ":", "return", "sel...
37
0.013216
def open_volume_file(filepath): """Open a volumetric file using the tools following the file extension. Parameters ---------- filepath: str Path to a volume file Returns ------- volume_data: np.ndarray Volume data pixdim: 1xN np.ndarray Vector with the descript...
[ "def", "open_volume_file", "(", "filepath", ")", ":", "# check if the file exists", "if", "not", "op", ".", "exists", "(", "filepath", ")", ":", "raise", "IOError", "(", "'Could not find file {}.'", ".", "format", "(", "filepath", ")", ")", "# define helper functi...
26.951613
0.002309
def in6_getnsmac(a): # return multicast Ethernet address associated with multicast v6 destination """ Return the multicast mac address associated with provided IPv6 address. Passed address must be in network format. """ a = struct.unpack('16B', a)[-4:] mac = '33:33:' mac += (':'.join(map(l...
[ "def", "in6_getnsmac", "(", "a", ")", ":", "# return multicast Ethernet address associated with multicast v6 destination", "a", "=", "struct", ".", "unpack", "(", "'16B'", ",", "a", ")", "[", "-", "4", ":", "]", "mac", "=", "'33:33:'", "mac", "+=", "(", "':'",...
35
0.013928
def next(transport, wizard, step, data): """ Validate step and go to the next one (or finish the wizard) :param transport: Transport object :param wizard: Wizard block name :param step: Current step number :param data: form data for the step """ step = int(step) wizard = blocks.get(...
[ "def", "next", "(", "transport", ",", "wizard", ",", "step", ",", "data", ")", ":", "step", "=", "int", "(", "step", ")", "wizard", "=", "blocks", ".", "get", "(", "wizard", ")", "# Retrieve form block", "form", "=", "wizard", ".", "next", "(", "step...
24.961538
0.001484
def connect(self, broker, port=1883, client_id="", clean_session=True): """ Connect to an MQTT broker. This is a pre-requisite step for publish and subscribe keywords. `broker` MQTT broker host `port` broker port (default 1883) `client_id` if not specified, a random id is gene...
[ "def", "connect", "(", "self", ",", "broker", ",", "port", "=", "1883", ",", "client_id", "=", "\"\"", ",", "clean_session", "=", "True", ")", ":", "logger", ".", "info", "(", "'Connecting to %s at port %s'", "%", "(", "broker", ",", "port", ")", ")", ...
34
0.001787
def out_16(library, session, space, offset, data, extended=False): """Write in an 16-bit value from the specified memory space and offset. Corresponds to viOut16* functions of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. ...
[ "def", "out_16", "(", "library", ",", "session", ",", "space", ",", "offset", ",", "data", ",", "extended", "=", "False", ")", ":", "if", "extended", ":", "return", "library", ".", "viOut16Ex", "(", "session", ",", "space", ",", "offset", ",", "data", ...
47.111111
0.002312
def replacing_copy(src, dest, follow_symlinks=False): """Perform copy that overwrites any existing target. Will copy/copytree `src` to `dest`, and will remove `dest` if it exists, regardless of what it is. If `follow_symlinks` is False, symlinks are preserved, otherwise their contents are copied. ...
[ "def", "replacing_copy", "(", "src", ",", "dest", ",", "follow_symlinks", "=", "False", ")", ":", "with", "make_tmp_name", "(", "dest", ")", "as", "tmp_dest", ":", "if", "os", ".", "path", ".", "islink", "(", "src", ")", "and", "not", "follow_symlinks", ...
36.08
0.00108
def find_by_id(self, _id, **kwargs): """ Pass me anything that looks like an _id : str, ObjectId, {"_id": str}, {"_id": ObjectId} """ if type(_id) == dict and _id.get("_id"): return self.find_one({"_id": ObjectId(_id["_id"])}, **kwargs) return self.find_one({"_id": ...
[ "def", "find_by_id", "(", "self", ",", "_id", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "_id", ")", "==", "dict", "and", "_id", ".", "get", "(", "\"_id\"", ")", ":", "return", "self", ".", "find_one", "(", "{", "\"_id\"", ":", "Object...
37.444444
0.008696
def set_gateway(self, gateway): ''' :param crabpy.gateway.capakey.CapakeyGateway gateway: Gateway to use. ''' self.gateway = gateway self.afdeling.set_gateway(gateway)
[ "def", "set_gateway", "(", "self", ",", "gateway", ")", ":", "self", ".", "gateway", "=", "gateway", "self", ".", "afdeling", ".", "set_gateway", "(", "gateway", ")" ]
33.666667
0.009662
def on_epoch_end(self, epoch, logs=None): """ Run on end of each epoch """ if logs is None: logs = dict() logger.debug(logs) nni.report_intermediate_result(logs["val_acc"])
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "logs", "=", "None", ")", ":", "if", "logs", "is", "None", ":", "logs", "=", "dict", "(", ")", "logger", ".", "debug", "(", "logs", ")", "nni", ".", "report_intermediate_result", "(", "logs", "["...
28.125
0.008621
def get_hook_url(self, access_token): """Get URL for webhook. In debug and testing mode the hook URL can be overwritten using ``WEBHOOKS_DEBUG_RECEIVER_URLS`` configuration variable to allow testing webhooks via services such as e.g. Ultrahook. .. code-block:: python ...
[ "def", "get_hook_url", "(", "self", ",", "access_token", ")", ":", "# Allow overwriting hook URL in debug mode.", "if", "(", "current_app", ".", "debug", "or", "current_app", ".", "testing", ")", "and", "current_app", ".", "config", ".", "get", "(", "'WEBHOOKS_DEB...
38.576923
0.001946
def _datalog(self, parameter, run, maxrun, det_id): "Extract data from database" values = { 'parameter_name': parameter, 'minrun': run, 'maxrun': maxrun, 'detid': det_id, } data = urlencode(values) content = self._get_content('strea...
[ "def", "_datalog", "(", "self", ",", "parameter", ",", "run", ",", "maxrun", ",", "det_id", ")", ":", "values", "=", "{", "'parameter_name'", ":", "parameter", ",", "'minrun'", ":", "run", ",", "'maxrun'", ":", "maxrun", ",", "'detid'", ":", "det_id", ...
33.310345
0.002012
def response_headers(): """Returns a set of response headers from the query string. --- tags: - Response inspection parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: ...
[ "def", "response_headers", "(", ")", ":", "# Pending swaggerUI update", "# https://github.com/swagger-api/swagger-ui/issues/3850", "headers", "=", "MultiDict", "(", "request", ".", "args", ".", "items", "(", "multi", "=", "True", ")", ")", "response", "=", "jsonify", ...
27.878049
0.000845
def _add_indices(self): """Adds the database indices relating to n-grams.""" self._logger.info('Adding database indices') self._conn.execute(constants.CREATE_INDEX_TEXTNGRAM_SQL) self._logger.info('Indices added')
[ "def", "_add_indices", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Adding database indices'", ")", "self", ".", "_conn", ".", "execute", "(", "constants", ".", "CREATE_INDEX_TEXTNGRAM_SQL", ")", "self", ".", "_logger", ".", "info", "("...
48.2
0.008163
def open(self, filename, mode='r', bufsize=-1): """ Open a file on the remote server. The arguments are the same as for Python's built-in `python:file` (aka `python:open`). A file-like object is returned, which closely mimics the behavior of a normal Python file object, includi...
[ "def", "open", "(", "self", ",", "filename", ",", "mode", "=", "'r'", ",", "bufsize", "=", "-", "1", ")", ":", "filename", "=", "self", ".", "_adjust_cwd", "(", "filename", ")", "self", ".", "_log", "(", "DEBUG", ",", "'open(%r, %r)'", "%", "(", "f...
48.5
0.001166
def _parse_docstring(self, docstring): """Parse the method docstring.""" match = re.match(r""" # Following PEP 257 \s* (?P<summary>[^\n]+?) \s* # First line ( # Description and YAML are optional (\n \s*){2} ...
[ "def", "_parse_docstring", "(", "self", ",", "docstring", ")", ":", "match", "=", "re", ".", "match", "(", "r\"\"\"\n # Following PEP 257\n \\s* (?P<summary>[^\\n]+?) \\s* # First line\n\n ( # Description and YAML are option...
38.029412
0.001508
def lloyd_cluster(G, seeds, maxiter=10): """Perform Lloyd clustering on graph with weighted edges. Parameters ---------- G : csr_matrix, csc_matrix A sparse NxN matrix where each nonzero entry G[i,j] is the distance between nodes i and j. seeds : int array If seeds is an int...
[ "def", "lloyd_cluster", "(", "G", ",", "seeds", ",", "maxiter", "=", "10", ")", ":", "G", "=", "asgraph", "(", "G", ")", "N", "=", "G", ".", "shape", "[", "0", "]", "if", "G", ".", "dtype", ".", "kind", "==", "'c'", ":", "# complex dtype", "G",...
27.3125
0.000552
def parse_iso_8601_time_str(time_str): """ Parses a standard ISO 8601 time string. The Route53 API uses these here and there. :param str time_str: An ISO 8601 time string. :rtype: datetime.datetime :returns: A timezone aware (UTC) datetime.datetime instance. """ if re.search('\.\d{3}Z$'...
[ "def", "parse_iso_8601_time_str", "(", "time_str", ")", ":", "if", "re", ".", "search", "(", "'\\.\\d{3}Z$'", ",", "time_str", ")", ":", "submitted_at", "=", "datetime", ".", "datetime", ".", "strptime", "(", "time_str", ",", "'%Y-%m-%dT%H:%M:%S.%fZ'", ")", "e...
36.823529
0.010903
def UpdateCronJob(self, cronjob_id, last_run_status=db.Database.unchanged, last_run_time=db.Database.unchanged, current_run_id=db.Database.unchanged, state=db.Database.unchanged, forced_run_requested=...
[ "def", "UpdateCronJob", "(", "self", ",", "cronjob_id", ",", "last_run_status", "=", "db", ".", "Database", ".", "unchanged", ",", "last_run_time", "=", "db", ".", "Database", ".", "unchanged", ",", "current_run_id", "=", "db", ".", "Database", ".", "unchang...
43.545455
0.013279
def sys_maxfd(): """ Returns the maximum file descriptor limit. This is guaranteed to return a useful int value. """ maxfd = None try: maxfd = int(resource.getrlimit(resource.RLIMIT_NOFILE)[0]) if maxfd == resource.RLIM_INFINITY: #...
[ "def", "sys_maxfd", "(", ")", ":", "maxfd", "=", "None", "try", ":", "maxfd", "=", "int", "(", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ")", "[", "0", "]", ")", "if", "maxfd", "==", "resource", ".", "RLIM_INFINITY", ":", "...
31.857143
0.008715
def get_resource_data(incoming_request): """Return the data from the incoming *request* based on the Content-type.""" content_type = incoming_request.headers['Content-type'].split(';')[0] if ('Content-type' not in incoming_request.headers or content_type in JSON_CONTENT_TYPES): retur...
[ "def", "get_resource_data", "(", "incoming_request", ")", ":", "content_type", "=", "incoming_request", ".", "headers", "[", "'Content-type'", "]", ".", "split", "(", "';'", ")", "[", "0", "]", "if", "(", "'Content-type'", "not", "in", "incoming_request", ".",...
41.470588
0.001387
def export_as_file(self, filepath, hyperparameters): """Generates a Python file with the importable base learner set to ``hyperparameters`` This function generates a Python file in the specified file path that contains the base learner as an importable variable stored in ``base_learner``. The...
[ "def", "export_as_file", "(", "self", ",", "filepath", ",", "hyperparameters", ")", ":", "if", "not", "filepath", ".", "endswith", "(", "'.py'", ")", ":", "filepath", "+=", "'.py'", "file_contents", "=", "''", "file_contents", "+=", "self", ".", "source", ...
46.095238
0.008097
def render_image(self, rgbobj, dst_x, dst_y): """Render the image represented by (rgbobj) at dst_x, dst_y in the pixel space. """ pos = (0, 0) arr = self.viewer.getwin_array(order=self.rgb_order, alpha=1.0, dtype=np.uint8) #pos = (ds...
[ "def", "render_image", "(", "self", ",", "rgbobj", ",", "dst_x", ",", "dst_y", ")", ":", "pos", "=", "(", "0", ",", "0", ")", "arr", "=", "self", ".", "viewer", ".", "getwin_array", "(", "order", "=", "self", ".", "rgb_order", ",", "alpha", "=", ...
39
0.012526
def typed_encode(value, sub_schema, path, net_new_properties, buffer): """ :param value: THE DATA STRUCTURE TO ENCODE :param sub_schema: dict FROM PATH TO Column DESCRIBING THE TYPE :param path: list OF CURRENT PATH :param net_new_properties: list FOR ADDING NEW PROPERTIES NOT FOUND IN sub_schema ...
[ "def", "typed_encode", "(", "value", ",", "sub_schema", ",", "path", ",", "net_new_properties", ",", "buffer", ")", ":", "try", ":", "# from jx_base import Column", "if", "sub_schema", ".", "__class__", ".", "__name__", "==", "'Column'", ":", "value_json_type", ...
44.116883
0.002015
def add_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read): """ Addes a newly created file handler to the specified logger :param logger: logging name or object to modify, defaults to root logger :param file_path: path to file to lo...
[ "def", "add_file_handler", "(", "logger", "=", "None", ",", "file_path", "=", "\"out.log\"", ",", "level", "=", "logging", ".", "INFO", ",", "log_format", "=", "log_formats", ".", "easy_read", ")", ":", "if", "not", "isinstance", "(", "logger", ",", "loggi...
40.714286
0.001715
def __run_delta_py(self, delta): """Execute the delta py file""" self.__run_py_file(delta.get_file(), delta.get_name()) self.__update_upgrades_table(delta)
[ "def", "__run_delta_py", "(", "self", ",", "delta", ")", ":", "self", ".", "__run_py_file", "(", "delta", ".", "get_file", "(", ")", ",", "delta", ".", "get_name", "(", ")", ")", "self", ".", "__update_upgrades_table", "(", "delta", ")" ]
35.2
0.011111
def on_connect(self, connection): "Re-subscribe to any channels and patterns previously subscribed to" # NOTE: for python3, we can't pass bytestrings as keyword arguments # so we need to decode channel/pattern names back to unicode strings # before passing them to [p]subscribe. s...
[ "def", "on_connect", "(", "self", ",", "connection", ")", ":", "# NOTE: for python3, we can't pass bytestrings as keyword arguments", "# so we need to decode channel/pattern names back to unicode strings", "# before passing them to [p]subscribe.", "self", ".", "pending_unsubscribe_channels...
47.470588
0.00243
def _score(estimator, X_test, y_test, scorer): """Compute the score of an estimator on a given test set.""" if y_test is None: score = scorer(estimator, X_test) else: score = scorer(estimator, X_test, y_test) if not isinstance(score, numbers.Number): raise ValueError("scoring mus...
[ "def", "_score", "(", "estimator", ",", "X_test", ",", "y_test", ",", "scorer", ")", ":", "if", "y_test", "is", "None", ":", "score", "=", "scorer", "(", "estimator", ",", "X_test", ")", "else", ":", "score", "=", "scorer", "(", "estimator", ",", "X_...
42.2
0.00232
def get_instance_template(self, resource_id, project_id=None): """ Retrieves instance template by project_id and resource_id. Must be called with keyword arguments rather than positional. :param resource_id: Name of the instance template :type resource_id: str :param pro...
[ "def", "get_instance_template", "(", "self", ",", "resource_id", ",", "project_id", "=", "None", ")", ":", "response", "=", "self", ".", "get_conn", "(", ")", ".", "instanceTemplates", "(", ")", ".", "get", "(", "project", "=", "project_id", ",", "instance...
46.4
0.002112
def set_cookie(self, kaka, request): """Returns a http_cookiejar.Cookie based on a set-cookie header line""" if not kaka: return part = urlparse(request.url) _domain = part.hostname logger.debug("%s: '%s'", _domain, kaka) for cookie_name, morsel in kaka.ite...
[ "def", "set_cookie", "(", "self", ",", "kaka", ",", "request", ")", ":", "if", "not", "kaka", ":", "return", "part", "=", "urlparse", "(", "request", ".", "url", ")", "_domain", "=", "part", ".", "hostname", "logger", ".", "debug", "(", "\"%s: '%s'\"",...
39.446154
0.001142
def start(address, channel, key, loop=None): """Starts a new Interactive client. Takes the remote address of the Tetris robot, as well as the channel number and auth key to use. Additionally, it takes a list of handler. This should be a dict of protobuf wire IDs to handler functions (from the .prot...
[ "def", "start", "(", "address", ",", "channel", ",", "key", ",", "loop", "=", "None", ")", ":", "if", "loop", "is", "None", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "socket", "=", "yield", "from", "websockets", ".", "connect", "(...
31.611111
0.001706
def set_duty_cycle(self, pin, dutycycle): """Set percent duty cycle of PWM output on specified pin. Duty cycle must be a value 0.0 to 100.0 (inclusive). """ if dutycycle < 0.0 or dutycycle > 100.0: raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inc...
[ "def", "set_duty_cycle", "(", "self", ",", "pin", ",", "dutycycle", ")", ":", "if", "dutycycle", "<", "0.0", "or", "dutycycle", ">", "100.0", ":", "raise", "ValueError", "(", "'Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).'", ")", "if", "pin", ...
58.555556
0.009346
def get_color(self,callb=None): """Convenience method to request the colour status from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device and request tha...
[ "def", "get_color", "(", "self", ",", "callb", "=", "None", ")", ":", "response", "=", "self", ".", "req_with_resp", "(", "LightGet", ",", "LightState", ",", "callb", "=", "callb", ")", "return", "self", ".", "color" ]
46.8125
0.009162
def get_custom_annotations_for_alias(data_type): """ Given a Stone data type, returns all custom annotations applied to it. """ # annotations can only be applied to Aliases, but they can be wrapped in # Nullable. also, Aliases pointing to other Aliases don't automatically # inherit their custom ...
[ "def", "get_custom_annotations_for_alias", "(", "data_type", ")", ":", "# annotations can only be applied to Aliases, but they can be wrapped in", "# Nullable. also, Aliases pointing to other Aliases don't automatically", "# inherit their custom annotations, so we might have to traverse.", "result...
44.076923
0.001709
def commit(self): """ Insert the specified text in all selected lines, always at the same column position. """ # Get the number of lines and columns in last line. last_line, last_col = self.qteWidget.getNumLinesAndColumns() # If this is the first ever call to th...
[ "def", "commit", "(", "self", ")", ":", "# Get the number of lines and columns in last line.", "last_line", ",", "last_col", "=", "self", ".", "qteWidget", ".", "getNumLinesAndColumns", "(", ")", "# If this is the first ever call to this undo/redo element", "# then backup the c...
44.045455
0.000505
def start (self): ''' Starts (Subscribes) the client. ''' self.sub = rospy.Subscriber(self.topic, BumperEvent, self.__callback)
[ "def", "start", "(", "self", ")", ":", "self", ".", "sub", "=", "rospy", ".", "Subscriber", "(", "self", ".", "topic", ",", "BumperEvent", ",", "self", ".", "__callback", ")" ]
25.833333
0.01875
def ftdetect(filename): """Determine if filename is markdown or notebook, based on the file extension. """ _, extension = os.path.splitext(filename) md_exts = ['.md', '.markdown', '.mkd', '.mdown', '.mkdn', '.Rmd'] nb_exts = ['.ipynb'] if extension in md_exts: return 'markdown' e...
[ "def", "ftdetect", "(", "filename", ")", ":", "_", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "md_exts", "=", "[", "'.md'", ",", "'.markdown'", ",", "'.mkd'", ",", "'.mdown'", ",", "'.mkdn'", ",", "'.Rmd'", "]", ...
29.923077
0.002494
def IEEEContext(bitwidth): """ Return IEEE 754-2008 context for a given bit width. The IEEE 754 standard specifies binary interchange formats with bitwidths 16, 32, 64, 128, and all multiples of 32 greater than 128. This function returns the context corresponding to the interchange format for the ...
[ "def", "IEEEContext", "(", "bitwidth", ")", ":", "try", ":", "precision", "=", "{", "16", ":", "11", ",", "32", ":", "24", ",", "64", ":", "53", ",", "128", ":", "113", "}", "[", "bitwidth", "]", "except", "KeyError", ":", "if", "not", "(", "bi...
38.378378
0.000687
def to_single_symbol_list(self): """ Convert this HandwrittenData object into a list of HandwrittenData objects. Each element of the list is a single symbol. Returns ------- list of HandwrittenData objects """ symbol_stream = getattr(self, ...
[ "def", "to_single_symbol_list", "(", "self", ")", ":", "symbol_stream", "=", "getattr", "(", "self", ",", "'symbol_stream'", ",", "[", "None", "for", "symbol", "in", "self", ".", "segmentation", "]", ")", "single_symbols", "=", "[", "]", "pointlist", "=", ...
40.761905
0.002283
def read(self, entity=None, attrs=None, ignore=None, params=None): """Fetch an attribute missing from the server's response. Also add sync plan to the responce if needed, as :meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize sync plan. For more information, see...
[ "def", "read", "(", "self", ",", "entity", "=", "None", ",", "attrs", "=", "None", ",", "ignore", "=", "None", ",", "params", "=", "None", ")", ":", "if", "attrs", "is", "None", ":", "attrs", "=", "self", ".", "read_json", "(", ")", "if", "_get_v...
40.5
0.001507
def shift_feature_to_x0(xdata, ydata, x0=0, feature=imax): """ Finds a feature in the the ydata and shifts xdata so the feature is centered at x0. Returns shifted xdata, ydata. Try me with plot.tweaks.manipulate_shown_data()! xdata,ydata data set x0=0 where to shift the peak feat...
[ "def", "shift_feature_to_x0", "(", "xdata", ",", "ydata", ",", "x0", "=", "0", ",", "feature", "=", "imax", ")", ":", "i", "=", "feature", "(", "ydata", ")", "return", "xdata", "-", "xdata", "[", "i", "]", "+", "x0", ",", "ydata" ]
41.636364
0.008547
def add_adapter(widget_class, signal_name, getter, setter, value_type, flavour=None): """This function can be used to extend at runtime the set of default adapters. If given widget class which is being added is already in the default set, it will be substituted by the new one until the n...
[ "def", "add_adapter", "(", "widget_class", ",", "signal_name", ",", "getter", ",", "setter", ",", "value_type", ",", "flavour", "=", "None", ")", ":", "new_tu", "=", "(", "widget_class", ",", "signal_name", ",", "getter", ",", "setter", ",", "value_type", ...
41.05
0.002381
def get_aws_s3_handle(config_map): """Convenience function for getting AWS S3 objects Added by cjshaw@mit.edu, Jan 9, 2015 Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and added support for Configuration May 25, 2017: Switch to boto3 """ url = 'https://' + config_map['s3_b...
[ "def", "get_aws_s3_handle", "(", "config_map", ")", ":", "url", "=", "'https://'", "+", "config_map", "[", "'s3_bucket'", "]", "+", "'.s3.amazonaws.com'", "if", "not", "AWS_CLIENT", ".", "is_aws_s3_client_set", "(", ")", ":", "client", "=", "boto3", ".", "clie...
33.4
0.001456
def parents(self): """ Returns list of parents changesets. """ return [self.repository.get_changeset(parent) for parent in self._commit.parents]
[ "def", "parents", "(", "self", ")", ":", "return", "[", "self", ".", "repository", ".", "get_changeset", "(", "parent", ")", "for", "parent", "in", "self", ".", "_commit", ".", "parents", "]" ]
31.166667
0.010417
def normalize_mapping_line(mapping_line, previous_source_column=0): """ Often times the position will remain stable, such that the naive process will end up with many redundant values; this function will iterate through the line and remove all extra values. """ if not mapping_line: retu...
[ "def", "normalize_mapping_line", "(", "mapping_line", ",", "previous_source_column", "=", "0", ")", ":", "if", "not", "mapping_line", ":", "return", "[", "]", ",", "previous_source_column", "# Note that while the local record here is also done as a 4-tuple,", "# element 1 and...
42.378378
0.000312
def gql(query_string, *args, **kwds): """Parse a GQL query string. Args: query_string: Full GQL query, e.g. 'SELECT * FROM Kind WHERE prop = 1'. *args, **kwds: If present, used to call bind(). Returns: An instance of query_class. """ qry = _gql(query_string) if args or kwds: qry = qry._bin...
[ "def", "gql", "(", "query_string", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "qry", "=", "_gql", "(", "query_string", ")", "if", "args", "or", "kwds", ":", "qry", "=", "qry", ".", "_bind", "(", "args", ",", "kwds", ")", "return", "qry" ]
23.785714
0.014451
def send(self, recipient, subject, message): """ Sends an email using the SMTP connection. :param recipient: <tuple> recipient's email address as the first element and their name as an optional second element :param subject: <str> mail subject :param ...
[ "def", "send", "(", "self", ",", "recipient", ",", "subject", ",", "message", ")", ":", "if", "self", ".", "configured", "is", "False", ":", "return", "False", "# connecting to server", "try", ":", "self", ".", "smtp", "=", "smtplib", ".", "SMTP", "(", ...
33.230769
0.001349
def load(self, filename, create = None, default_conf = {}): """Load the config file Args: filename (str): the filename of the config, without any path create (str): if the config file not found, and this parameter is not None, a config file will be crea...
[ "def", "load", "(", "self", ",", "filename", ",", "create", "=", "None", ",", "default_conf", "=", "{", "}", ")", ":", "filenames", ",", "tries", "=", "self", ".", "__search_config_files", "(", "filename", ")", "if", "len", "(", "filenames", ")", ":", ...
39.75
0.010526
def model_loss(y, model, mean=True): """ Define loss of TF graph :param y: correct labels :param model: output of the model :param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch :return: return mean of loss if True, otherwise return...
[ "def", "model_loss", "(", "y", ",", "model", ",", "mean", "=", "True", ")", ":", "warnings", ".", "warn", "(", "\"This function is deprecated and will be removed on or after\"", "\" 2019-04-05. Switch to cleverhans.train.train.\"", ")", "op", "=", "model", ".", "op", ...
30.478261
0.012448
def mean(self): """ Compute the mean across records """ return self._constructor(self.values.mean(axis=self.baseaxes, keepdims=True))
[ "def", "mean", "(", "self", ")", ":", "return", "self", ".", "_constructor", "(", "self", ".", "values", ".", "mean", "(", "axis", "=", "self", ".", "baseaxes", ",", "keepdims", "=", "True", ")", ")" ]
32.2
0.018182
def ReadLine(self, file_object): """Reads a line. Args: file_object (dfvfs.FileIO): file-like object. Returns: str: line read from the lines buffer. """ line, _, self.lines = self.lines.partition('\n') if not line: self.ReadLines(file_object) line, _, self.lines = self....
[ "def", "ReadLine", "(", "self", ",", "file_object", ")", ":", "line", ",", "_", ",", "self", ".", "lines", "=", "self", ".", "lines", ".", "partition", "(", "'\\n'", ")", "if", "not", "line", ":", "self", ".", "ReadLines", "(", "file_object", ")", ...
22.933333
0.00838
def create(cls, name, vss_def=None): """ Create a VSS Container. This maps to the Service Manager within NSX. vss_def is optional and has the following definition: {"isc_ovf_appliance_model": 'virtual', "isc_ovf_appliance_version": '', "isc_ip_addr...
[ "def", "create", "(", "cls", ",", "name", ",", "vss_def", "=", "None", ")", ":", "vss_def", "=", "{", "}", "if", "vss_def", "is", "None", "else", "vss_def", "json", "=", "{", "'master_type'", ":", "'dcl2fw'", ",", "'name'", ":", "name", ",", "'vss_is...
34.04
0.002286
def set_default_subparser(self, name, args=None): """default subparser selection. Call after setup, just before parse_args() name: is the name of the subparser to call by default args: if set is the argument list handed to parse_args() , tested with 2.7, 3.2, 3.3, 3.4 it works with 2.6 assuming arg...
[ "def", "set_default_subparser", "(", "self", ",", "name", ",", "args", "=", "None", ")", ":", "subparser_found", "=", "False", "for", "arg", "in", "sys", ".", "argv", "[", "1", ":", "]", ":", "if", "arg", "in", "[", "'-h'", ",", "'--help'", "]", ":...
39.5
0.000951
def transplant(new_net, net, suffix=''): """ Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their equivalent convolutional layers, since the weights are the sa...
[ "def", "transplant", "(", "new_net", ",", "net", ",", "suffix", "=", "''", ")", ":", "for", "p", "in", "net", ".", "params", ":", "p_new", "=", "p", "+", "suffix", "if", "p_new", "not", "in", "new_net", ".", "params", ":", "print", "'dropping'", ",...
47.111111
0.002311
def take_screenshot(self, screenshot_name=None, screenshot_path=None): """Take a screenshot Use the screenshot_name args when you want to take a screenshot for reference If the `runner:cache_screenshot` config is set to True then screenshot sharing all the same name wil...
[ "def", "take_screenshot", "(", "self", ",", "screenshot_name", "=", "None", ",", "screenshot_path", "=", "None", ")", ":", "self", ".", "info_log", "(", "\"Taking a screenshot...\"", ")", "save_to_db", "=", "False", "if", "screenshot_path", ":", "self", ".", "...
39.752688
0.000528
def process_image(filepath, outpath, settings): """Process one image: resize, create thumbnail.""" logger = logging.getLogger(__name__) logger.info('Processing %s', filepath) filename = os.path.split(filepath)[1] outname = os.path.join(outpath, filename) ext = os.path.splitext(filename)[1] ...
[ "def", "process_image", "(", "filepath", ",", "outpath", ",", "settings", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'Processing %s'", ",", "filepath", ")", "filename", "=", "os", ".", "path", ...
33.575758
0.000877
def show_log(self): """Show log.""" self.action_show_report.setEnabled(True) self.action_show_log.setEnabled(False) self.load_html_file(self.log_path)
[ "def", "show_log", "(", "self", ")", ":", "self", ".", "action_show_report", ".", "setEnabled", "(", "True", ")", "self", ".", "action_show_log", ".", "setEnabled", "(", "False", ")", "self", ".", "load_html_file", "(", "self", ".", "log_path", ")" ]
35.6
0.010989
def md_from_etree(self, md_element, context=''): """Parse rs:md attributes returning a dict of the data. Parameters: md_element - etree element <rs:md> context - context for error reporting """ md = {} # grab all understood attributes into md dict ...
[ "def", "md_from_etree", "(", "self", ",", "md_element", ",", "context", "=", "''", ")", ":", "md", "=", "{", "}", "# grab all understood attributes into md dict", "for", "att", "in", "(", "'capability'", ",", "'change'", ",", "'hash'", ",", "'length'", ",", ...
42.297297
0.001874
def build_policy(self, name, statements, roles, is_managed_policy=False): """ Generate policy for IAM cloudformation template :param name: Name of the policy :param statements: The "rules" the policy should have :param roles: The roles associated with this policy :param i...
[ "def", "build_policy", "(", "self", ",", "name", ",", "statements", ",", "roles", ",", "is_managed_policy", "=", "False", ")", ":", "if", "is_managed_policy", ":", "policy", "=", "ManagedPolicy", "(", "self", ".", "name_strip", "(", "name", ",", "True", ")...
35
0.001738
def get_lang_array(self): """gets supported langs as an array""" r = self.yandex_translate_request("getLangs", "") self.handle_errors(r) return r.json()["dirs"]
[ "def", "get_lang_array", "(", "self", ")", ":", "r", "=", "self", ".", "yandex_translate_request", "(", "\"getLangs\"", ",", "\"\"", ")", "self", ".", "handle_errors", "(", "r", ")", "return", "r", ".", "json", "(", ")", "[", "\"dirs\"", "]" ]
26.857143
0.010309
def compute_output_shape(self, input_shape): """Computes the output shape of the layer. Args: input_shape: Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer. Returns: ...
[ "def", "compute_output_shape", "(", "self", ",", "input_shape", ")", ":", "input_shape", "=", "tf", ".", "TensorShape", "(", "input_shape", ")", "input_shape", "=", "input_shape", ".", "with_rank_at_least", "(", "2", ")", "if", "tf", ".", "compat", ".", "dim...
38.190476
0.002433
def _restore_and_log_checkpoint(self, actor): """Restore an actor from a checkpoint if available and log any errors. This should only be called on workers that have just executed an actor creation task. Args: actor: The actor to restore from a checkpoint. """ ...
[ "def", "_restore_and_log_checkpoint", "(", "self", ",", "actor", ")", ":", "actor_id", "=", "self", ".", "_worker", ".", "actor_id", "try", ":", "checkpoints", "=", "ray", ".", "actor", ".", "get_checkpoints_for_actor", "(", "actor_id", ")", "if", "len", "("...
47.815789
0.001079
def mbar_W_nk(u_kn, N_k, f_k): """Calculate the weight matrix. Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of sampl...
[ "def", "mbar_W_nk", "(", "u_kn", ",", "N_k", ",", "f_k", ")", ":", "return", "np", ".", "exp", "(", "mbar_log_W_nk", "(", "u_kn", ",", "N_k", ",", "f_k", ")", ")" ]
29.727273
0.001481
def p_information_conversion(self, p): 'information : information IN INFORMATION_UNIT' logger.debug( 'information = information %s in information unit %s', p[1], p[3]) p[0] = '{0: {1}}'.format(p[1], p[3])
[ "def", "p_information_conversion", "(", "self", ",", "p", ")", ":", "logger", ".", "debug", "(", "'information = information %s in information unit %s'", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", "p", "[", "0", "]", "=", "'{0: {1}}'", ".", "...
47.2
0.008333
def dump(df,fp): """ dump DataFrame to file :param DataFrame df: :param file fp: """ arff = __dump(df) liacarff.dump(arff,fp)
[ "def", "dump", "(", "df", ",", "fp", ")", ":", "arff", "=", "__dump", "(", "df", ")", "liacarff", ".", "dump", "(", "arff", ",", "fp", ")" ]
18.5
0.032258
def rankagg_R(df, method="stuart"): """Return aggregated ranks as implemented in the RobustRankAgg R package. This function is now deprecated. References: Kolde et al., 2012, DOI: 10.1093/bioinformatics/btr709 Stuart et al., 2003, DOI: 10.1126/science.1087447 Parameters --------...
[ "def", "rankagg_R", "(", "df", ",", "method", "=", "\"stuart\"", ")", ":", "tmpdf", "=", "NamedTemporaryFile", "(", ")", "tmpscript", "=", "NamedTemporaryFile", "(", "mode", "=", "\"w\"", ")", "tmpranks", "=", "NamedTemporaryFile", "(", ")", "df", ".", "to...
30.051282
0.01405
def _saturation(self, T): """Saturation calculation for two phase search""" rhoc = self._constants.get("rhoref", self.rhoc) Tc = self._constants.get("Tref", self.Tc) if T > Tc: T = Tc tau = Tc/T rhoLo = self._Liquid_Density(T) rhoGo = self._Vapor_Den...
[ "def", "_saturation", "(", "self", ",", "T", ")", ":", "rhoc", "=", "self", ".", "_constants", ".", "get", "(", "\"rhoref\"", ",", "self", ".", "rhoc", ")", "Tc", "=", "self", ".", "_constants", ".", "get", "(", "\"Tref\"", ",", "self", ".", "Tc", ...
33.810811
0.001554
def _pyshark_read_frame(self): """Read frames.""" from pcapkit.toolkit.pyshark import packet2dict, tcp_traceflow # fetch PyShark packet packet = next(self._extmp) # def _pyshark_packet2chain(packet): # """Fetch PyShark packet protocol chain.""" # return ...
[ "def", "_pyshark_read_frame", "(", "self", ")", ":", "from", "pcapkit", ".", "toolkit", ".", "pyshark", "import", "packet2dict", ",", "tcp_traceflow", "# fetch PyShark packet", "packet", "=", "next", "(", "self", ".", "_extmp", ")", "# def _pyshark_packet2chain(pack...
31.051282
0.002402
def upgrade_deployment(self, service_name, deployment_name, mode, package_url, configuration, label, force, role_to_upgrade=None, extended_properties=None): ''' Initiates an upgrade. service_name: Name of the hosted service. ...
[ "def", "upgrade_deployment", "(", "self", ",", "service_name", ",", "deployment_name", ",", "mode", ",", "package_url", ",", "configuration", ",", "label", ",", "force", ",", "role_to_upgrade", "=", "None", ",", "extended_properties", "=", "None", ")", ":", "_...
47.557377
0.001351
def finish(self): """Stop coverage and send relevant info back to the master.""" self.unset_env() self.cov.stop() self.cov.combine() self.cov.save() if self.is_collocated: # If we are collocated then just inform the master of our # data file to i...
[ "def", "finish", "(", "self", ")", ":", "self", ".", "unset_env", "(", ")", "self", ".", "cov", ".", "stop", "(", ")", "self", ".", "cov", ".", "combine", "(", ")", "self", ".", "cov", ".", "save", "(", ")", "if", "self", ".", "is_collocated", ...
42.545455
0.00209
def ParseRecord(self, parser_mediator, key, structure): """Parses a log record structure and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): identifier of the structure of tokens. ...
[ "def", "ParseRecord", "(", "self", ",", "parser_mediator", ",", "key", ",", "structure", ")", ":", "if", "key", "not", "in", "(", "'header'", ",", "'header_signature'", ",", "'logline'", ")", ":", "raise", "errors", ".", "ParseError", "(", "'Unable to parse ...
39.677419
0.00873
def sort(line): """ change point position if x1,y0 < x0,y0 """ x0, y0, x1, y1 = line # if (x0**2+y0**2)**0.5 < (x1**2+y1**2)**0.5: # return (x1,y1,x0,y0) # return line # # if x1 < x0: # return (x1,y1,x0,y0) # return line turn = False ...
[ "def", "sort", "(", "line", ")", ":", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "line", "# if (x0**2+y0**2)**0.5 < (x1**2+y1**2)**0.5:", "# return (x1,y1,x0,y0)", "# return line", "#", "# if x1 < x0:", "# return (x1,y1,x0,y0)", "# return li...
20.24
0.001887
def timeformat(timeobject, timeformat): """ Formats the specified time object to the target format type. :param timeobject: the object conveying the time value :type timeobject: int, ``datetime.datetime`` or ISO8601-formatted string with pattern ``YYYY-MM-DD HH:MM:SS+00`` :param timeformat:...
[ "def", "timeformat", "(", "timeobject", ",", "timeformat", ")", ":", "if", "timeformat", "==", "\"unix\"", ":", "return", "to_UNIXtime", "(", "timeobject", ")", "elif", "timeformat", "==", "\"iso\"", ":", "return", "to_ISO8601", "(", "timeobject", ")", "elif",...
42.208333
0.000965
def create(self, ogpgs): """ Method to create object group permissions general :param ogpgs: List containing vrf desired to be created on database :return: None """ data = {'ogpgs': ogpgs} return super(ApiObjectGroupPermissionGeneral, self).post('api/v3/object-g...
[ "def", "create", "(", "self", ",", "ogpgs", ")", ":", "data", "=", "{", "'ogpgs'", ":", "ogpgs", "}", "return", "super", "(", "ApiObjectGroupPermissionGeneral", ",", "self", ")", ".", "post", "(", "'api/v3/object-group-perm-general/'", ",", "data", ")" ]
33.7
0.008671
def remove_unused_categories(self, inplace=False): """ Remove categories which are not used. Parameters ---------- inplace : bool, default False Whether or not to drop unused categories inplace or return a copy of this categorical with unused categories dro...
[ "def", "remove_unused_categories", "(", "self", ",", "inplace", "=", "False", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")", "cat", "=", "self", "if", "inplace", "else", "self", ".", "copy", "(", ")", "idx", ",", ...
32
0.001639
def extract_agg_damages(dstore, what): """ Aggregate damages of the given loss type and tags. Use it as /extract/agg_damages/structural?taxonomy=RC&zipcode=20126 :returns: array of shape (R, D), being R the number of realizations and D the number of damage states, or an array of length ...
[ "def", "extract_agg_damages", "(", "dstore", ",", "what", ")", ":", "loss_type", ",", "tags", "=", "get_loss_type_tags", "(", "what", ")", "if", "'dmg_by_asset'", "in", "dstore", ":", "# scenario_damage", "lti", "=", "dstore", "[", "'oqparam'", "]", ".", "lt...
40.294118
0.001427
def trace2(A, B): r"""Trace of :math:`\mathrm A \mathrm B^\intercal`. Args: A (array_like): Left-hand side. B (array_like): Right-hand side. Returns: float: Trace of :math:`\mathrm A \mathrm B^\intercal`. """ A = asarray(A, float) B = asarray(B, float) layout_error...
[ "def", "trace2", "(", "A", ",", "B", ")", ":", "A", "=", "asarray", "(", "A", ",", "float", ")", "B", "=", "asarray", "(", "B", ",", "float", ")", "layout_error", "=", "\"Wrong matrix layout.\"", "if", "not", "(", "len", "(", "A", ".", "shape", "...
25.090909
0.001745
def normalize(data): """ Function to normalize data to have mean 0 and unity standard deviation (also called z-transform) Parameters ---------- data : numpy.ndarray Returns ------- numpy.ndarray z-transform of input array """ data = data.astyp...
[ "def", "normalize", "(", "data", ")", ":", "data", "=", "data", ".", "astype", "(", "float", ")", "data", "-=", "data", ".", "mean", "(", ")", "return", "data", "/", "data", ".", "std", "(", ")" ]
17.428571
0.018135
def visit_rules(self, node, rules_list): """Collate all the rules into a map. Return (map, default rule). The default rule is the first one. Or, if you have more than one rule of that name, it's the last-occurring rule of that name. (This lets you override the default rule when you exte...
[ "def", "visit_rules", "(", "self", ",", "node", ",", "rules_list", ")", ":", "_", ",", "rules", "=", "rules_list", "# Map each rule's name to its Expression. Later rules of the same name", "# override earlier ones. This lets us define rules multiple times and", "# have the last dec...
49.090909
0.001816
def dump_service(self, sc): """Read all data blocks of a given service. :meth:`dump_service` reads all data blocks from the service with service code *sc* and returns a list of strings suitable for printing. The number of strings returned does not necessarily reflect the number ...
[ "def", "dump_service", "(", "self", ",", "sc", ")", ":", "def", "lprint", "(", "fmt", ",", "data", ",", "index", ")", ":", "ispchr", "=", "lambda", "x", ":", "x", ">=", "32", "and", "x", "<=", "126", "# noqa: E731", "def", "print_bytes", "(", "octe...
33.884615
0.001655
def elementTypeName(self): """ String representation of the element type. """ dtype = self._ncVar.dtype if type(dtype) == type: # Handle the unexpected case that dtype is a regular Python type # (happens e.g. in the /PROCESSOR/processing_configuration of the Trop...
[ "def", "elementTypeName", "(", "self", ")", ":", "dtype", "=", "self", ".", "_ncVar", ".", "dtype", "if", "type", "(", "dtype", ")", "==", "type", ":", "# Handle the unexpected case that dtype is a regular Python type", "# (happens e.g. in the /PROCESSOR/processing_config...
41.7
0.00939
def parse(text: str) -> Docstring: """ Parse the Google-style docstring into its components. :returns: parsed docstring """ ret = Docstring() if not text: return ret # Clean according to PEP-0257 text = inspect.cleandoc(text) # Find first title and split on its position ...
[ "def", "parse", "(", "text", ":", "str", ")", "->", "Docstring", ":", "ret", "=", "Docstring", "(", ")", "if", "not", "text", ":", "return", "ret", "# Clean according to PEP-0257", "text", "=", "inspect", ".", "cleandoc", "(", "text", ")", "# Find first ti...
33.272727
0.000758
def _graphviz(self, dot=None): """Return a graphviz.Digraph object with a graph of all virtual columns""" from graphviz import Digraph dot = dot or Digraph(comment='whole dataframe') root_nodes = self._root_nodes() for column in root_nodes: self[column]._graphviz(dot=...
[ "def", "_graphviz", "(", "self", ",", "dot", "=", "None", ")", ":", "from", "graphviz", "import", "Digraph", "dot", "=", "dot", "or", "Digraph", "(", "comment", "=", "'whole dataframe'", ")", "root_nodes", "=", "self", ".", "_root_nodes", "(", ")", "for"...
42
0.008746
def run_model(self, times=None, weather=None): """ Run the model. Parameters ---------- times : None or DatetimeIndex, default None Times at which to evaluate the model. Can be None if attribute `times` is already set. weather : None or DataFrame,...
[ "def", "run_model", "(", "self", ",", "times", "=", "None", ",", "weather", "=", "None", ")", ":", "self", ".", "prepare_inputs", "(", "times", ",", "weather", ")", "self", ".", "aoi_model", "(", ")", "self", ".", "spectral_model", "(", ")", "self", ...
32.944444
0.001638
def highlight(code, lexer='html', formatter='html', output_wrapper=None): """Highlights given code using pygments.""" if not pygments: raise TypeError("pygments module required") if not isinstance(code, six.string_types): code = pprint.pformat(code) if isinstance(lexer, six.string_types)...
[ "def", "highlight", "(", "code", ",", "lexer", "=", "'html'", ",", "formatter", "=", "'html'", ",", "output_wrapper", "=", "None", ")", ":", "if", "not", "pygments", ":", "raise", "TypeError", "(", "\"pygments module required\"", ")", "if", "not", "isinstanc...
48.25
0.001271
def add_edge(self, u, v, weight=None): """ Add an edge between u and v. The nodes u and v will be automatically added if they are not already in the graph. Parameters ---------- u, v : nodes Nodes can be any hashable Python object. weight: i...
[ "def", "add_edge", "(", "self", ",", "u", ",", "v", ",", "weight", "=", "None", ")", ":", "super", "(", "DAG", ",", "self", ")", ".", "add_edge", "(", "u", ",", "v", ",", "weight", "=", "weight", ")" ]
28.410256
0.001745
def keep_entry_value(entry, values, converter, regex): """ Check if an entry does not match a given value. Every number in the entry will be extracted using *regex*, if any match a given value the entry will not be kept. Parameters ---------- entry : str values : iterable Colle...
[ "def", "keep_entry_value", "(", "entry", ",", "values", ",", "converter", ",", "regex", ")", ":", "return", "not", "any", "(", "converter", "(", "num", ")", "in", "values", "for", "num", "in", "regex", ".", "findall", "(", "entry", ")", ")" ]
29.26087
0.001439
def script_fields(self, **kwargs): """ Define script fields to be calculated on hits. See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html for more details. Example:: s = Search() s = s.script_fields(times...
[ "def", "script_fields", "(", "self", ",", "*", "*", "kwargs", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "for", "name", "in", "kwargs", ":", "if", "isinstance", "(", "kwargs", "[", "name", "]", ",", "string_types", ")", ":", "kwargs", "["...
31.5
0.00237
def lF_value (ER,EF,dfnum,dfden): """ Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees o...
[ "def", "lF_value", "(", "ER", ",", "EF", ",", "dfnum", ",", "dfden", ")", ":", "return", "(", "(", "ER", "-", "EF", ")", "/", "float", "(", "dfnum", ")", "/", "(", "EF", "/", "float", "(", "dfden", ")", ")", ")" ]
41.636364
0.010684
def draw_mask(im, mask, alpha=0.5, color=None): """ Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically """ if color is None: color = PALETTE_RGB[np.ran...
[ "def", "draw_mask", "(", "im", ",", "mask", ",", "alpha", "=", "0.5", ",", "color", "=", "None", ")", ":", "if", "color", "is", "None", ":", "color", "=", "PALETTE_RGB", "[", "np", ".", "random", ".", "choice", "(", "len", "(", "PALETTE_RGB", ")", ...
33.533333
0.001934
def _swap_database(self, query): """Swap database for query if swappable. Return **new query** with swapped database. This is experimental feature which allows us to have multiple managers configured against different databases for single model definition. The essential...
[ "def", "_swap_database", "(", "self", ",", "query", ")", ":", "database", "=", "_query_db", "(", "query", ")", "if", "database", "==", "self", ".", "database", ":", "return", "query", "if", "self", ".", "_subclassed", "(", "peewee", ".", "PostgresqlDatabas...
32.108108
0.001634
async def remove_all_pumps_async(self, reason): """ Stops all partition pumps (Note this might be wrong and need to await all tasks before returning done). :param reason: A reason for closing. :type reason: str :rtype: bool """ pump_tasks = [self.remove_p...
[ "async", "def", "remove_all_pumps_async", "(", "self", ",", "reason", ")", ":", "pump_tasks", "=", "[", "self", ".", "remove_pump_async", "(", "p_id", ",", "reason", ")", "for", "p_id", "in", "self", ".", "partition_pumps", "]", "await", "asyncio", ".", "g...
35.666667
0.009112