text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def set_multi(self, mappings, time=0, compress_level=-1): """ Set multiple keys with it's values on server. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int :param compress_level...
[ "def", "set_multi", "(", "self", ",", "mappings", ",", "time", "=", "0", ",", "compress_level", "=", "-", "1", ")", ":", "returns", "=", "[", "]", "if", "not", "mappings", ":", "return", "False", "server_mappings", "=", "defaultdict", "(", "dict", ")",...
37.846154
0.001982
def pop(self, name): """Get and remove key from database (atomic).""" name = mkey(name) temp = mkey((name, "__poptmp__")) self.rename(name, temp) value = self[temp] del(self[temp]) return value
[ "def", "pop", "(", "self", ",", "name", ")", ":", "name", "=", "mkey", "(", "name", ")", "temp", "=", "mkey", "(", "(", "name", ",", "\"__poptmp__\"", ")", ")", "self", ".", "rename", "(", "name", ",", "temp", ")", "value", "=", "self", "[", "t...
30.25
0.008032
def parse_color(color): """Take any css color definition and give back a tuple containing the r, g, b, a values along with a type which can be: #rgb, #rgba, #rrggbb, #rrggbbaa, rgb, rgba """ r = g = b = a = type = None if color.startswith('#'): color = color[1:] if len(color) == ...
[ "def", "parse_color", "(", "color", ")", ":", "r", "=", "g", "=", "b", "=", "a", "=", "type", "=", "None", "if", "color", ".", "startswith", "(", "'#'", ")", ":", "color", "=", "color", "[", "1", ":", "]", "if", "len", "(", "color", ")", "=="...
34.030303
0.000866
def dragData(self, format=None, default=None): """ Returns the drag information that is associated with this tree widget item for the given format. :param format | <str> :return <variant> """ if format is None: retu...
[ "def", "dragData", "(", "self", ",", "format", "=", "None", ",", "default", "=", "None", ")", ":", "if", "format", "is", "None", ":", "return", "self", ".", "_dragData", "return", "self", ".", "_dragData", ".", "get", "(", "nativestring", "(", "format"...
32.666667
0.009926
def GET_AUTH(self): """ GET request """ return self.template_helper.get_renderer().queue(*self.submission_manager.get_job_queue_snapshot(), datetime.fromtimestamp)
[ "def", "GET_AUTH", "(", "self", ")", ":", "return", "self", ".", "template_helper", ".", "get_renderer", "(", ")", ".", "queue", "(", "*", "self", ".", "submission_manager", ".", "get_job_queue_snapshot", "(", ")", ",", "datetime", ".", "fromtimestamp", ")" ...
59
0.01676
def convert(input_format, output_format, b64_data): """ Convert `b64_data` fron `input_format` to `output_format`. Args: input_format (str): Specification of input format (pdf/epub/whatever), see :attr:`INPUT_FORMATS` for list. output_format (str): Specificatio...
[ "def", "convert", "(", "input_format", ",", "output_format", ",", "b64_data", ")", ":", "# checks", "assert", "input_format", "in", "INPUT_FORMATS", ",", "\"Unsupported input format!\"", "assert", "output_format", "in", "OUTPUT_FORMATS", ",", "\"Unsupported output format!...
35.608696
0.001188
def reset(self): """Reset the database Drop all tables and recreate them """ self.metadata.drop_all(self.engine) self.metadata.create_all(self.engine)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "metadata", ".", "drop_all", "(", "self", ".", "engine", ")", "self", ".", "metadata", ".", "create_all", "(", "self", ".", "engine", ")" ]
26.428571
0.010471
def _deconv_rl_np_fft(data, h, Niter=10, h_is_fftshifted=False): """ deconvolves data with given psf (kernel) h data and h have to be same shape via lucy richardson deconvolution """ if data.shape!=h.shape: raise ValueError("data and h have to be same shape") i...
[ "def", "_deconv_rl_np_fft", "(", "data", ",", "h", ",", "Niter", "=", "10", ",", "h_is_fftshifted", "=", "False", ")", ":", "if", "data", ".", "shape", "!=", "h", ".", "shape", ":", "raise", "ValueError", "(", "\"data and h have to be same shape\"", ")", "...
25.38
0.001517
def hypercube_edges(dims, use_map=False): '''Create edge lists for an arbitrary hypercube. TODO: this is probably not the fastest way.''' edges = [] nodes = np.arange(np.product(dims)).reshape(dims) for i,d in enumerate(dims): for j in range(d-1): for n1, n2 in zip(np.take(nodes, [j]...
[ "def", "hypercube_edges", "(", "dims", ",", "use_map", "=", "False", ")", ":", "edges", "=", "[", "]", "nodes", "=", "np", ".", "arange", "(", "np", ".", "product", "(", "dims", ")", ")", ".", "reshape", "(", "dims", ")", "for", "i", ",", "d", ...
44.363636
0.012048
def complete_nonnull_value( exe_context, # type: ExecutionContext return_type, # type: GraphQLNonNull field_asts, # type: List[Field] info, # type: ResolveInfo path, # type: List[Union[int, str]] result, # type: Any ): # type: (...) -> Any """ Complete a NonNull value by comple...
[ "def", "complete_nonnull_value", "(", "exe_context", ",", "# type: ExecutionContext", "return_type", ",", "# type: GraphQLNonNull", "field_asts", ",", "# type: List[Field]", "info", ",", "# type: ResolveInfo", "path", ",", "# type: List[Union[int, str]]", "result", ",", "# ty...
28.12
0.001376
def build(self, message): """buffer all the streaming messages based on the message id. Reconstruct all fragments together. :param message: incoming message :return: next complete message or None if streaming is not done """ context = None ...
[ "def", "build", "(", "self", ",", "message", ")", ":", "context", "=", "None", "if", "message", ".", "message_type", "in", "[", "Types", ".", "CALL_REQ", ",", "Types", ".", "CALL_RES", "]", ":", "self", ".", "verify_message", "(", "message", ")", "cont...
34.321429
0.000674
def add(self, pk, quantity=1, **kwargs): """Add an item to the cart. If the item is already in the cart, then its quantity will be increased by `quantity` units. Parameters ---------- pk : str or int The primary key of the item. quantity : int-conver...
[ "def", "add", "(", "self", ",", "pk", ",", "quantity", "=", "1", ",", "*", "*", "kwargs", ")", ":", "pk", "=", "str", "(", "pk", ")", "if", "pk", "in", "self", ".", "items", ":", "existing_item", "=", "self", ".", "items", "[", "pk", "]", "ex...
29.026316
0.001754
def parse(md, model, encoding='utf-8', config=None): """ Translate the Versa Markdown syntax into Versa model relationships md -- markdown source text model -- Versa model to take the output relationship encoding -- character encoding (defaults to UTF-8) Returns: The overall base URI (`@base`)...
[ "def", "parse", "(", "md", ",", "model", ",", "encoding", "=", "'utf-8'", ",", "config", "=", "None", ")", ":", "#Set up configuration to interpret the conventions for the Markdown", "config", "=", "config", "or", "{", "}", "#This mapping takes syntactical elements such...
48.273438
0.008325
def table_exists(client, table_reference): """Return if a table exists. Args: client (google.cloud.bigquery.client.Client): A client to connect to the BigQuery API. table_reference (google.cloud.bigquery.table.TableReference): A reference to the table to look for. R...
[ "def", "table_exists", "(", "client", ",", "table_reference", ")", ":", "from", "google", ".", "cloud", ".", "exceptions", "import", "NotFound", "try", ":", "client", ".", "get_table", "(", "table_reference", ")", "return", "True", "except", "NotFound", ":", ...
28.684211
0.001776
def setuptools_install(self, chdir_to, pkg_name, setup_py_path=None, editable=False): """Install an sdist or an editable package into the virtualenv :param str chdir_to: The location to change to :param str setup_py_path: The path to the setup.py, if applicable defaults to None :param ...
[ "def", "setuptools_install", "(", "self", ",", "chdir_to", ",", "pkg_name", ",", "setup_py_path", "=", "None", ",", "editable", "=", "False", ")", ":", "install_options", "=", "[", "\"--prefix={0}\"", ".", "format", "(", "self", ".", "prefix", ".", "as_posix...
47.733333
0.009589
def draw_buffers(self, near, far): """ Draw framebuffers for debug purposes. We need to supply near and far plane so the depth buffer can be linearized when visualizing. :param near: Projection near value :param far: Projection far value """ self.ctx.disable(mode...
[ "def", "draw_buffers", "(", "self", ",", "near", ",", "far", ")", ":", "self", ".", "ctx", ".", "disable", "(", "moderngl", ".", "DEPTH_TEST", ")", "helper", ".", "draw", "(", "self", ".", "gbuffer", ".", "color_attachments", "[", "0", "]", ",", "pos...
50.357143
0.009749
def ignore(name): ''' Ignore a specific program update. When an update is ignored the '-' and version number at the end will be omitted, so "SecUpd2014-001-1.0" becomes "SecUpd2014-001". It will be removed automatically if present. An update is successfully ignored when it no longer shows up after l...
[ "def", "ignore", "(", "name", ")", ":", "# remove everything after and including the '-' in the updates name.", "to_ignore", "=", "name", ".", "rsplit", "(", "'-'", ",", "1", ")", "[", "0", "]", "cmd", "=", "[", "'softwareupdate'", ",", "'--ignore'", ",", "to_ig...
31.461538
0.001186
def iter_modules(path=None, prefix=''): """Yields (module_loader, name, ispkg) for all submodules on path, or, if path is None, all top-level modules on sys.path. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module nam...
[ "def", "iter_modules", "(", "path", "=", "None", ",", "prefix", "=", "''", ")", ":", "if", "path", "is", "None", ":", "importers", "=", "iter_importers", "(", ")", "else", ":", "importers", "=", "map", "(", "get_importer", ",", "path", ")", "yielded", ...
29.363636
0.001499
def discover(interface=None): """Print help and scan devices on screen. :return: None """ click.secho(HELP, fg='yellow') scan_devices(discovery_print, lfilter=lambda d: d.src not in mac_id_list, iface=interface)
[ "def", "discover", "(", "interface", "=", "None", ")", ":", "click", ".", "secho", "(", "HELP", ",", "fg", "=", "'yellow'", ")", "scan_devices", "(", "discovery_print", ",", "lfilter", "=", "lambda", "d", ":", "d", ".", "src", "not", "in", "mac_id_list...
32.285714
0.008621
def execute(self, input_data): ''' Execute ''' # Get the bro script path (workers/bro/__load__.bro) script_path = self.bro_script_dir # Create a temporary directory with self.goto_temp_directory() as temp_dir: # Get the pcap inputs (filenames) print 'pc...
[ "def", "execute", "(", "self", ",", "input_data", ")", ":", "# Get the bro script path (workers/bro/__load__.bro)", "script_path", "=", "self", ".", "bro_script_dir", "# Create a temporary directory", "with", "self", ".", "goto_temp_directory", "(", ")", "as", "temp_dir",...
40.568966
0.00249
def normalize_per_cell( data, counts_per_cell_after=None, counts_per_cell=None, key_n_counts=None, copy=False, layers=[], use_rep=None, min_counts=1, ) -> Optional[AnnData]: """Normalize total counts per cell. .. warning:: .. deprecated:: 1.3.7 Use :func:`~sc...
[ "def", "normalize_per_cell", "(", "data", ",", "counts_per_cell_after", "=", "None", ",", "counts_per_cell", "=", "None", ",", "key_n_counts", "=", "None", ",", "copy", "=", "False", ",", "layers", "=", "[", "]", ",", "use_rep", "=", "None", ",", "min_coun...
38.714286
0.002399
def toarray(self): """Returns the data as numpy.array from each partition.""" rdd = self._rdd.map(lambda x: x.toarray()) return np.concatenate(rdd.collect())
[ "def", "toarray", "(", "self", ")", ":", "rdd", "=", "self", ".", "_rdd", ".", "map", "(", "lambda", "x", ":", "x", ".", "toarray", "(", ")", ")", "return", "np", ".", "concatenate", "(", "rdd", ".", "collect", "(", ")", ")" ]
44.5
0.01105
async def make_response(*args: Any) -> Response: """Create a response, a simple wrapper function. This is most useful when you want to alter a Response before returning it, for example .. code-block:: python response = make_response(render_template('index.html')) response.headers['X-H...
[ "async", "def", "make_response", "(", "*", "args", ":", "Any", ")", "->", "Response", ":", "if", "not", "args", ":", "return", "current_app", ".", "response_class", "(", ")", "if", "len", "(", "args", ")", "==", "1", ":", "args", "=", "args", "[", ...
27.222222
0.001972
def format_valid_streams(plugin, streams): """Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight). """ delimiter = ", " validstreams = [] for name, strea...
[ "def", "format_valid_streams", "(", "plugin", ",", "streams", ")", ":", "delimiter", "=", "\", \"", "validstreams", "=", "[", "]", "for", "name", ",", "stream", "in", "sorted", "(", "streams", ".", "items", "(", ")", ",", "key", "=", "lambda", "stream", ...
26.354839
0.002361
def furnish(app: web.Application): """ Configures Application routes, readying it for running. This function modifies routes and resources that were added by calling code, and must be called immediately prior to `run(app)`. Args: app (web.Application): The Aiohttp Application a...
[ "def", "furnish", "(", "app", ":", "web", ".", "Application", ")", ":", "app_name", "=", "app", "[", "'config'", "]", "[", "'name'", "]", "prefix", "=", "'/'", "+", "app_name", ".", "lstrip", "(", "'/'", ")", "app", ".", "router", ".", "add_routes", ...
36.375
0.001339
def _before_cursor_execute(conn, cursor, statement, parameters, context, executemany): """Intercept low-level cursor execute() events before execution. If executemany is True, this is an executemany call, else an execute call. Note: If enabled tracing both SQLAlchemy and the data...
[ "def", "_before_cursor_execute", "(", "conn", ",", "cursor", ",", "statement", ",", "parameters", ",", "context", ",", "executemany", ")", ":", "# Find out the func name", "if", "executemany", ":", "query_func", "=", "'executemany'", "else", ":", "query_func", "="...
38.342857
0.000727
def _node_filter(self, node, ancestors, filtrates): '''_node_filter Low-level api: Remove unrelated nodes in config. This is a recursive method. Parameters ---------- node : `Element` A node to be processed. ancestors : `list` A list of...
[ "def", "_node_filter", "(", "self", ",", "node", ",", "ancestors", ",", "filtrates", ")", ":", "if", "node", "in", "filtrates", ":", "return", "elif", "node", "in", "ancestors", ":", "if", "node", ".", "tag", "!=", "config_tag", ":", "s_node", "=", "se...
30.72
0.001262
def validate_token_age(callback_token): """ Returns True if a given token is within the age expiration limit. """ try: token = CallbackToken.objects.get(key=callback_token, is_active=True) seconds = (timezone.now() - token.created_at).total_seconds() token_expiry_time = api_setti...
[ "def", "validate_token_age", "(", "callback_token", ")", ":", "try", ":", "token", "=", "CallbackToken", ".", "objects", ".", "get", "(", "key", "=", "callback_token", ",", "is_active", "=", "True", ")", "seconds", "=", "(", "timezone", ".", "now", "(", ...
31.2
0.001555
def sample_multinomial(N, p, size=None): r""" Draws fixed number of samples N from different multinomial distributions (with the same number dice sides). :param int N: How many samples to draw from each distribution. :param np.ndarray p: Probabilities specifying each distribution. Sum along...
[ "def", "sample_multinomial", "(", "N", ",", "p", ",", "size", "=", "None", ")", ":", "# ensure s is array", "s", "=", "np", ".", "array", "(", "[", "1", "]", ")", "if", "size", "is", "None", "else", "np", ".", "array", "(", "[", "size", "]", ")",...
36.275
0.001342
def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to conn...
[ "def", "list_domains", "(", "*", "*", "kwargs", ")", ":", "vms", "=", "[", "]", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "for", "dom", "in", "_get_domain", "(", "conn", ",", "iterable", "=", "True", ")", ":", "vms", ".", "append", ...
23.269231
0.001587
def is_sms_service_for_region(numobj, region_dialing_from): """Given a valid short number, determines whether it is an SMS service (however, nothing is implied about its validity). An SMS service is where the primary or only intended usage is to receive and/or send text messages (SMSs). This includes MM...
[ "def", "is_sms_service_for_region", "(", "numobj", ",", "region_dialing_from", ")", ":", "if", "not", "_region_dialing_from_matches_number", "(", "numobj", ",", "region_dialing_from", ")", ":", "return", "False", "metadata", "=", "PhoneMetadata", ".", "short_metadata_fo...
54.454545
0.001641
def line(h1: Histogram1D, **kwargs) -> dict: """Line plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- h1 : physt.histogram1d.Histogram1D Dimensionality of histogram for which it is applicable """ lw = kwargs.pop("lw", DEFAULT_STROKE...
[ "def", "line", "(", "h1", ":", "Histogram1D", ",", "*", "*", "kwargs", ")", "->", "dict", ":", "lw", "=", "kwargs", ".", "pop", "(", "\"lw\"", ",", "DEFAULT_STROKE_WIDTH", ")", "mark_template", "=", "[", "{", "\"type\"", ":", "\"line\"", ",", "\"encode...
28.518519
0.001256
def copy_qtgui_to_modules(): """Copies the QtGui list of PySide/PyQt4 into QtWidgets""" pyside_filepath = PREFIX + '/PySide.json' pyqt4_filepath = PREFIX + '/PyQt4.json' pyside = read_json(pyside_filepath) pyqt4 = read_json(pyqt4_filepath) # When Qt4 was moved to Qt5, they split QtGui into QtG...
[ "def", "copy_qtgui_to_modules", "(", ")", ":", "pyside_filepath", "=", "PREFIX", "+", "'/PySide.json'", "pyqt4_filepath", "=", "PREFIX", "+", "'/PyQt4.json'", "pyside", "=", "read_json", "(", "pyside_filepath", ")", "pyqt4", "=", "read_json", "(", "pyqt4_filepath", ...
39.714286
0.001171
def cleanup(self, **kwargs): """cleanup ASA context for an edge tenant pair. """ params = kwargs.get('params') LOG.info("asa_cleanup: tenant %(tenant)s %(in_vlan)d %(out_vlan)d" " %(in_ip)s %(in_mask)s %(out_ip)s %(out_mask)s", {'tenant': params.get('tenant_name...
[ "def", "cleanup", "(", "self", ",", "*", "*", "kwargs", ")", ":", "params", "=", "kwargs", ".", "get", "(", "'params'", ")", "LOG", ".", "info", "(", "\"asa_cleanup: tenant %(tenant)s %(in_vlan)d %(out_vlan)d\"", "\" %(in_ip)s %(in_mask)s %(out_ip)s %(out_mask)s\"", "...
48.3
0.001353
def createNetwork(dataSource): """Create the Network instance. The network has a sensor region reading data from `dataSource` and passing the encoded representation to an SPRegion. The SPRegion output is passed to a TMRegion. :param dataSource: a RecordStream instance to get data from :returns: a Network ...
[ "def", "createNetwork", "(", "dataSource", ")", ":", "network", "=", "Network", "(", ")", "# Our input is sensor data from the gym file. The RecordSensor region", "# allows us to specify a file record stream as the input source via the", "# dataSource attribute.", "network", ".", "ad...
43.6
0.016148
def get_scrollbar_value_height(self): """Return the value span height of the scrollbar""" vsb = self.editor.verticalScrollBar() return vsb.maximum()-vsb.minimum()+vsb.pageStep()
[ "def", "get_scrollbar_value_height", "(", "self", ")", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "return", "vsb", ".", "maximum", "(", ")", "-", "vsb", ".", "minimum", "(", ")", "+", "vsb", ".", "pageStep", "(", ")" ]
49.5
0.00995
def wheel_dist_name(self): """Return distribution full name with - replaced with _""" return '-'.join((safer_name(self.distribution.get_name()), safer_version(self.distribution.get_version())))
[ "def", "wheel_dist_name", "(", "self", ")", ":", "return", "'-'", ".", "join", "(", "(", "safer_name", "(", "self", ".", "distribution", ".", "get_name", "(", ")", ")", ",", "safer_version", "(", "self", ".", "distribution", ".", "get_version", "(", ")",...
57.75
0.008547
def handle_var(value, context): """ Handle template tag variable """ # Resolve FilterExpression and Variable immediately if isinstance(value, FilterExpression) or isinstance(value, Variable): return value.resolve(context) # Return quoted strings unquoted # http://djangosnippets.org/s...
[ "def", "handle_var", "(", "value", ",", "context", ")", ":", "# Resolve FilterExpression and Variable immediately", "if", "isinstance", "(", "value", ",", "FilterExpression", ")", "or", "isinstance", "(", "value", ",", "Variable", ")", ":", "return", "value", ".",...
33.941176
0.001686
def p_referenceInitializer(p): """referenceInitializer : objectHandle | aliasIdentifier """ if p[1][0] == '$': try: p[0] = p.parser.aliases[p[1]] except KeyError: ce = CIMError( CIM_ERR_FAILED, ...
[ "def", "p_referenceInitializer", "(", "p", ")", ":", "if", "p", "[", "1", "]", "[", "0", "]", "==", "'$'", ":", "try", ":", "p", "[", "0", "]", "=", "p", ".", "parser", ".", "aliases", "[", "p", "[", "1", "]", "]", "except", "KeyError", ":", ...
30.933333
0.002092
def parse(desktop_file_or_string): '''Parse a .desktop file. Parse a .desktop file or a string with its contents into an easy-to-use dict, with standard values present even if not defined in file. Args: desktop_file_or_string (str): Either the path to a .desktop file or a string with a .desktop file as its conten...
[ "def", "parse", "(", "desktop_file_or_string", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "desktop_file_or_string", ")", ":", "with", "open", "(", "desktop_file_or_string", ")", "as", "f", ":", "desktop_file", "=", "f", ".", "read", "(", ")", ...
26.176471
0.032503
def delete_object(self, object_name): """ Remove an object from this bucket. :param str object_name: The object to remove. """ self._client.remove_object(self._instance, self.name, object_name)
[ "def", "delete_object", "(", "self", ",", "object_name", ")", ":", "self", ".", "_client", ".", "remove_object", "(", "self", ".", "_instance", ",", "self", ".", "name", ",", "object_name", ")" ]
32.571429
0.008547
def get_config_file(): """ Return the loaded config file if one exists. """ # config will be created here if we can't find one new_config_path = os.path.expanduser('~/.dagobahd.yml') config_dirs = ['/etc', os.path.expanduser('~')] config_filenames = ['dagobahd.yml', ...
[ "def", "get_config_file", "(", ")", ":", "# config will be created here if we can't find one", "new_config_path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.dagobahd.yml'", ")", "config_dirs", "=", "[", "'/etc'", ",", "os", ".", "path", ".", "expanduser", ...
35.631579
0.001438
def delete_network_precommit(self, context): """Delete entry corresponding to Network's VLAN in the DB.""" segments = context.network_segments for segment in segments: if not self.check_segment(segment): return # Not a vlan network vlan_id = segment.get(a...
[ "def", "delete_network_precommit", "(", "self", ",", "context", ")", ":", "segments", "=", "context", ".", "network_segments", "for", "segment", "in", "segments", ":", "if", "not", "self", ".", "check_segment", "(", "segment", ")", ":", "return", "# Not a vlan...
47.045455
0.001894
def append_records(self, dataset_key, stream_id, body): """Append records to a stream. :param dataset_key: Dataset identifier, in the form of owner/id :type dataset_key: str :param stream_id: Stream unique identifier. :type stream_id: str :param body: Object body ...
[ "def", "append_records", "(", "self", ",", "dataset_key", ",", "stream_id", ",", "body", ")", ":", "owner_id", ",", "dataset_id", "=", "parse_dataset_key", "(", "dataset_key", ")", "try", ":", "return", "self", ".", "_streams_api", ".", "append_records", "(", ...
38.958333
0.002088
def find_surface_pores(network, markers=None, label='surface'): r""" Find the pores on the surface of the domain by performing a Delaunay triangulation between the network pores and some external ``markers``. All pores connected to these external marker points are considered surface pores. Para...
[ "def", "find_surface_pores", "(", "network", ",", "markers", "=", "None", ",", "label", "=", "'surface'", ")", ":", "import", "scipy", ".", "spatial", "as", "sptl", "if", "markers", "is", "None", ":", "(", "xmax", ",", "ymax", ",", "zmax", ")", "=", ...
38.223684
0.000336
def _parse_param(key): """ Parse the query param looking for filters Determine the field to filter on & the operator to be used when filtering. :param key: The query parameter to the left of the equal sign :return: tuple of string field name & string operator """ regex = r...
[ "def", "_parse_param", "(", "key", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'filter\\[([A-Za-z0-9_./]+)\\]'", ")", "match", "=", "regex", ".", "match", "(", "key", ")", "if", "match", ":", "field_and_oper", "=", "match", ".", "groups", "(", "...
31.233333
0.001035
def _load(self, value: Any): """ Load the value for the field, run validators and return the value. Subclasses can override this to provide custom load logic. :param value: value of the field """ if value in self.empty_values: # If a default has been set fo...
[ "def", "_load", "(", "self", ",", "value", ":", "Any", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "# If a default has been set for the field return it", "if", "self", ".", "default", "is", "not", "None", ":", "default", "=", "self", "."...
33.55814
0.001347
def lan(self, move: Move) -> str: """ Gets the long algebraic notation of the given move in the context of the current position. """ return self._algebraic(move, long=True)
[ "def", "lan", "(", "self", ",", "move", ":", "Move", ")", "->", "str", ":", "return", "self", ".", "_algebraic", "(", "move", ",", "long", "=", "True", ")" ]
34.5
0.009434
def find_dataset(h5o, path=None): """Find and return the relevant dataset inside the given H5 object If ``path=None`` is given, and ``h5o`` contains a single dataset, that will be returned Parameters ---------- h5o : `h5py.File`, `h5py.Group` the HDF5 object in which to search pat...
[ "def", "find_dataset", "(", "h5o", ",", "path", "=", "None", ")", ":", "# find dataset", "if", "isinstance", "(", "h5o", ",", "h5py", ".", "Dataset", ")", ":", "return", "h5o", "elif", "path", "is", "None", "and", "len", "(", "h5o", ")", "==", "1", ...
27.771429
0.000994
def download_and_extract(path, url, input_filename, target_filename): """Extract files from downloaded compressed archive file. Args: path: string directory where the files will be downloaded url: url containing the compressed input and target files input_filename: name of file containing data in sourc...
[ "def", "download_and_extract", "(", "path", ",", "url", ",", "input_filename", ",", "target_filename", ")", ":", "logging", ".", "info", "(", "'Downloading and extracting data to: %s'", "%", "path", ")", "# Check if extracted files already exist in path", "input_file", "=...
35.55
0.011636
def need_processing(self): """A utility to help determine which connections need processing. Returns a triple of lists containing those connections that 0) need to read from the network, 1) need to write to the network, 2) waiting for pending timers to expire. The timer list is sorted w...
[ "def", "need_processing", "(", "self", ")", ":", "readers", "=", "[", "]", "writers", "=", "[", "]", "timer_heap", "=", "[", "]", "for", "c", "in", "iter", "(", "self", ".", "_connections", ".", "values", "(", ")", ")", ":", "if", "c", ".", "need...
37.608696
0.002255
def merge_errors(errors1, errors2): """Deeply merge two error messages. The format of ``errors1`` and ``errors2`` matches the ``message`` parameter of :exc:`marshmallow.exceptions.ValidationError`. """ if not errors1: return errors2 if not errors2: return errors1 if isinstan...
[ "def", "merge_errors", "(", "errors1", ",", "errors2", ")", ":", "if", "not", "errors1", ":", "return", "errors2", "if", "not", "errors2", ":", "return", "errors1", "if", "isinstance", "(", "errors1", ",", "list", ")", ":", "if", "isinstance", "(", "erro...
33
0.000654
def check_triple_double_quotes(self, definition, docstring): r'''D300: Use """triple double quotes""". For consistency, always use """triple double quotes""" around docstrings. Use r"""raw triple double quotes""" if you use any backslashes in your docstrings. For Unicode docstrings, use...
[ "def", "check_triple_double_quotes", "(", "self", ",", "definition", ",", "docstring", ")", ":", "if", "docstring", ":", "if", "'\"\"\"'", "in", "ast", ".", "literal_eval", "(", "docstring", ")", ":", "# Allow ''' quotes if docstring contains \"\"\", because", "# othe...
43.12
0.001815
def rollback(**kwargs): ''' Roll back the last committed configuration changes and commit id : 0 The rollback ID value (0-49) dev_timeout : 30 The NETCONF RPC timeout (in seconds) comment Provide a comment for the commit confirm Provide time in minutes for commit ...
[ "def", "rollback", "(", "*", "*", "kwargs", ")", ":", "id_", "=", "kwargs", ".", "pop", "(", "'id'", ",", "0", ")", "ret", "=", "{", "}", "conn", "=", "__proxy__", "[", "'junos.conn'", "]", "(", ")", "op", "=", "dict", "(", ")", "if", "'__pub_a...
28.647727
0.000383
def _get_last_entries(db, qty): """get all entries and the last qty entries""" doc_ids = [post.doc_id for post in db.posts.all()] doc_ids = sorted(doc_ids, reverse=True) # bug: here we shoud only render doc_ids[:qty] # but we can't use mtimes for sorting. We'll need to add ptime for the # databa...
[ "def", "_get_last_entries", "(", "db", ",", "qty", ")", ":", "doc_ids", "=", "[", "post", ".", "doc_id", "for", "post", "in", "db", ".", "posts", ".", "all", "(", ")", "]", "doc_ids", "=", "sorted", "(", "doc_ids", ",", "reverse", "=", "True", ")",...
48.615385
0.001553
def update(self,table, sys_id, **kparams): """ use PUT to update a single record by table name and sys_id returns a dict (the json map) for python 3.4 """ result = self.table_api_put(table, sys_id, **kparams) return self.to_record(result, table)
[ "def", "update", "(", "self", ",", "table", ",", "sys_id", ",", "*", "*", "kparams", ")", ":", "result", "=", "self", ".", "table_api_put", "(", "table", ",", "sys_id", ",", "*", "*", "kparams", ")", "return", "self", ".", "to_record", "(", "result",...
41
0.010239
def tile_decode(tile, tileindex, tileshape, tiledshape, lsb2msb, decompress, unpack, unpredict, out): """Decode tile segment bytes into 5D output array.""" _, imagedepth, imagelength, imagewidth, _ = out.shape tileddepth, tiledlength, tiledwidth = tiledshape tiledepth, tilelength, tilewi...
[ "def", "tile_decode", "(", "tile", ",", "tileindex", ",", "tileshape", ",", "tiledshape", ",", "lsb2msb", ",", "decompress", ",", "unpack", ",", "unpredict", ",", "out", ")", ":", "_", ",", "imagedepth", ",", "imagelength", ",", "imagewidth", ",", "_", "...
43.044444
0.000505
def dict_of(**kwargs): """ Generates a homogeneous dict of the specified generators using kwargs. You can generate non-homogeneous dicts using `dict`. This is a class factory, it makes a class which is a closure around the specified keys and generators. """ class DictOfKeyGenerators(Arbitra...
[ "def", "dict_of", "(", "*", "*", "kwargs", ")", ":", "class", "DictOfKeyGenerators", "(", "ArbitraryInterface", ")", ":", "\"\"\"\n A closure class around the keys and generators specified above, which\n generates a dict of the keys and generators.\n \"\"\"", "@", ...
31.193548
0.001003
def unregister(self, fd): """ Unregister a previously registered descriptor :param fd: The descriptor to unregister :raises ValueError: If :meth:`closed()` is True :raises OSError: If the underlying ``epoll_ctl(2)`` fails. The error message ma...
[ "def", "unregister", "(", "self", ",", "fd", ")", ":", "if", "self", ".", "_epfd", "<", "0", ":", "_err_closed", "(", ")", "ev", "=", "epoll_event", "(", ")", "try", ":", "epoll_ctl", "(", "self", ".", "_epfd", ",", "EPOLL_CTL_DEL", ",", "fd", ",",...
33.24
0.002339
def get_older_backup(self, encrypted=None, compressed=None, content_type=None, database=None, servername=None): """ Return the older backup's file name. :param encrypted: Filter by encrypted or not :type encrypted: ``bool`` or ``None`` :param compressed...
[ "def", "get_older_backup", "(", "self", ",", "encrypted", "=", "None", ",", "compressed", "=", "None", ",", "content_type", "=", "None", ",", "database", "=", "None", ",", "servername", "=", "None", ")", ":", "files", "=", "self", ".", "list_backups", "(...
36.727273
0.002412
def mixedToUnder(s): # pragma: no cover """ Sample: >>> mixedToUnder("FooBarBaz") 'foo_bar_baz' Special case for ID: >>> mixedToUnder("FooBarID") 'foo_bar_id' """ if s.endswith('ID'): return mixedToUnder(s[:-2] + "_id") trans = _mixedToUnderRE.sub(mixedT...
[ "def", "mixedToUnder", "(", "s", ")", ":", "# pragma: no cover", "if", "s", ".", "endswith", "(", "'ID'", ")", ":", "return", "mixedToUnder", "(", "s", "[", ":", "-", "2", "]", "+", "\"_id\"", ")", "trans", "=", "_mixedToUnderRE", ".", "sub", "(", "m...
24.4375
0.002463
def scatterplot(x,y,*args,**kwargs): """ NAME: scatterplot PURPOSE: make a 'smart' scatterplot that is a density plot in high-density regions and a regular scatterplot for outliers INPUT: x, y xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed ...
[ "def", "scatterplot", "(", "x", ",", "y", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "xlabel", "=", "kwargs", ".", "pop", "(", "'xlabel'", ",", "None", ")", "ylabel", "=", "kwargs", ".", "pop", "(", "'ylabel'", ",", "None", ")", "if", ...
39.459574
0.018618
def dist(self, src, tar, weights='exponential', max_length=8): """Return normalized distance between the Eudex hashes of two terms. This is Eudex distance normalized to [0, 1]. Parameters ---------- src : str Source string for comparison tar : str ...
[ "def", "dist", "(", "self", ",", "src", ",", "tar", ",", "weights", "=", "'exponential'", ",", "max_length", "=", "8", ")", ":", "return", "self", ".", "dist_abs", "(", "src", ",", "tar", ",", "weights", ",", "max_length", ",", "True", ")" ]
29.542857
0.001873
def captchaform(field_name): """Decorator to add a simple captcha to a form To use this decorator, you must specify the captcha field's name as an argument to the decorator. For example: @captchaform('captcha') class MyForm(Form): pass This would add a new form field named 'captcha' t...
[ "def", "captchaform", "(", "field_name", ")", ":", "def", "wrapper", "(", "orig_form", ")", ":", "\"\"\"The actual function that wraps and modifies the form\"\"\"", "# Get the original init method so we can call it later", "orig_init", "=", "orig_form", ".", "__init__", "def", ...
35.017241
0.001437
def filter(coro, iterable, assert_fn=None, limit=0, loop=None): """ Returns a list of all the values in coll which pass an asynchronous truth test coroutine. Operations are executed concurrently by default, but results will be in order. You can configure the concurrency via `limit` param. ...
[ "def", "filter", "(", "coro", ",", "iterable", ",", "assert_fn", "=", "None", ",", "limit", "=", "0", ",", "loop", "=", "None", ")", ":", "assert_corofunction", "(", "coro", "=", "coro", ")", "assert_iter", "(", "iterable", "=", "iterable", ")", "# Che...
29.487805
0.0004
def contains_remove(self, item): # type (Any, Any) -> Any '''Takes a collection and an item and returns a new collection of the same type with that item removed. The notion of "contains" is defined by the object itself; the following must be ``True``: .. code-block:: python item not in con...
[ "def", "contains_remove", "(", "self", ",", "item", ")", ":", "# type (Any, Any) -> Any", "try", ":", "self", ".", "_lens_contains_remove", "except", "AttributeError", ":", "message", "=", "'Don\\'t know how to remove an item from {}'", "raise", "NotImplementedError", "("...
33.44
0.001163
def single_load(input_, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load single configuration file. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given input 'input\_' is single ...
[ "def", "single_load", "(", "input_", ",", "ac_parser", "=", "None", ",", "ac_template", "=", "False", ",", "ac_context", "=", "None", ",", "*", "*", "options", ")", ":", "cnf", "=", "_single_load", "(", "input_", ",", "ac_parser", "=", "ac_parser", ",", ...
43.491525
0.000381
def copy_expert(self, sql, filename, open=open): """ Executes SQL using psycopg2 copy_expert method. Necessary to execute COPY command without access to a superuser. Note: if this method is called with a "COPY FROM" statement and the specified input file does not exist, it creat...
[ "def", "copy_expert", "(", "self", ",", "sql", ",", "filename", ",", "open", "=", "open", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", ":", "pass", "with", "...
41.857143
0.002225
def repeating(first, mode=RepeatMode.Weekly, step=1, flags=0, startAt=None, repeatUntil=None, maximum=None): """ Returns a list of repeating dates from the inputted start date based on the given mode. If an repeatUntil date...
[ "def", "repeating", "(", "first", ",", "mode", "=", "RepeatMode", ".", "Weekly", ",", "step", "=", "1", ",", "flags", "=", "0", ",", "startAt", "=", "None", ",", "repeatUntil", "=", "None", ",", "maximum", "=", "None", ")", ":", "if", "repeatUntil", ...
30.761905
0.00075
def process_config(config_path, py3_wrapper=None): """ Parse i3status.conf so we can adapt our code to the i3status config. """ def notify_user(error): if py3_wrapper: py3_wrapper.notify_user(error) else: print(error) def parse_config(config): """ ...
[ "def", "process_config", "(", "config_path", ",", "py3_wrapper", "=", "None", ")", ":", "def", "notify_user", "(", "error", ")", ":", "if", "py3_wrapper", ":", "py3_wrapper", ".", "notify_user", "(", "error", ")", "else", ":", "print", "(", "error", ")", ...
32.393204
0.000436
def reset_index(self, level=None, drop=False, name=None, inplace=False): """ Generate a new DataFrame or Series with the index reset. This is useful when the index needs to be treated as a column, or when the index is meaningless and needs to be reset to the default before anoth...
[ "def", "reset_index", "(", "self", ",", "level", "=", "None", ",", "drop", "=", "False", ",", "name", "=", "None", ",", "inplace", "=", "False", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")", "if", "drop", ":", ...
33.152672
0.000447
def role( state, host, name, present=True, password=None, login=True, superuser=False, inherit=False, createdb=False, createrole=False, replication=False, connection_limit=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_hos...
[ "def", "role", "(", "state", ",", "host", ",", "name", ",", "present", "=", "True", ",", "password", "=", "None", ",", "login", "=", "True", ",", "superuser", "=", "False", ",", "inherit", "=", "False", ",", "createdb", "=", "False", ",", "createrole...
32.210526
0.000396
def getBottomRight(self): """ Return the ``Location`` of the bottom right corner of this region """ return Location(self.x+self.w, self.y+self.h)
[ "def", "getBottomRight", "(", "self", ")", ":", "return", "Location", "(", "self", ".", "x", "+", "self", ".", "w", ",", "self", ".", "y", "+", "self", ".", "h", ")" ]
53
0.018634
def make_outfiles(data, samples, output_formats, ipyclient): """ Get desired formats from paramsdict and write files to outfiles directory. """ ## will iterate optim loci at a time with h5py.File(data.clust_database, 'r') as io5: optim = io5["seqs"].attrs["chunksize"][0] nloci =...
[ "def", "make_outfiles", "(", "data", ",", "samples", ",", "output_formats", ",", "ipyclient", ")", ":", "## will iterate optim loci at a time", "with", "h5py", ".", "File", "(", "data", ".", "clust_database", ",", "'r'", ")", "as", "io5", ":", "optim", "=", ...
41.064815
0.01299
def check_component_for_specific_sbo_term(items, term): r""" Identify model components that lack a specific SBO term(s). Parameters ---------- items : list A list of model components i.e. reactions to be checked for a specific SBO term. term : str or list of str A string...
[ "def", "check_component_for_specific_sbo_term", "(", "items", ",", "term", ")", ":", "# check for multiple allowable SBO terms", "if", "isinstance", "(", "term", ",", "list", ")", ":", "return", "[", "elem", "for", "elem", "in", "items", "if", "elem", ".", "anno...
32.966667
0.000982
def printTPRegionParams(tpregion): """ Note: assumes we are using TemporalMemory/TPShim in the TPRegion """ tm = tpregion.getSelf()._tfdr print "------------PY TemporalMemory Parameters ------------------" print "numberOfCols =", tm.getColumnDimensions() print "cellsPerColumn =", tm...
[ "def", "printTPRegionParams", "(", "tpregion", ")", ":", "tm", "=", "tpregion", ".", "getSelf", "(", ")", ".", "_tfdr", "print", "\"------------PY TemporalMemory Parameters ------------------\"", "print", "\"numberOfCols =\"", ",", "tm", ".", "getColumnDimens...
50.352941
0.017202
def michael(key, to_hash): """Defined in 802.11i p.48""" # Block size: 4 nb_block, nb_extra_bytes = divmod(len(to_hash), 4) # Add padding data = to_hash + chb(0x5a) + b"\x00" * (7 - nb_extra_bytes) # Hash m_l, m_r = unpack('<II', key) for i in range(nb_block + 2): # Convert i-t...
[ "def", "michael", "(", "key", ",", "to_hash", ")", ":", "# Block size: 4", "nb_block", ",", "nb_extra_bytes", "=", "divmod", "(", "len", "(", "to_hash", ")", ",", "4", ")", "# Add padding", "data", "=", "to_hash", "+", "chb", "(", "0x5a", ")", "+", "b\...
29.5
0.002053
def uninstall(packages, options=None): """ Remove one or more packages. Extra *options* may be passed to ``yum`` if necessary. """ manager = MANAGER if options is None: options = [] elif isinstance(options, six.string_types): options = [options] if not isinstance(packag...
[ "def", "uninstall", "(", "packages", ",", "options", "=", "None", ")", ":", "manager", "=", "MANAGER", "if", "options", "is", "None", ":", "options", "=", "[", "]", "elif", "isinstance", "(", "options", ",", "six", ".", "string_types", ")", ":", "optio...
29.4375
0.002058
def compute_from_counts(self,countmat,beta=0): """ m.compute_from_counts(,countmat,beta=0) -- Utility function to build a motif object from a matrix of letter counts. """ self.counts = countmat self.width = len(countmat) self.bgscale = 0 maxcount = 0 #...
[ "def", "compute_from_counts", "(", "self", ",", "countmat", ",", "beta", "=", "0", ")", ":", "self", ".", "counts", "=", "countmat", "self", ".", "width", "=", "len", "(", "countmat", ")", "self", ".", "bgscale", "=", "0", "maxcount", "=", "0", "#Det...
31.478261
0.014735
def scf_compute_coeffs_axi(dens, N, L, a=1.,radial_order=None, costheta_order=None): """ NAME: scf_compute_coeffs_axi PURPOSE: Numerically compute the expansion coefficients for a given axi-symmetric density INPUT: dens - A density function that take...
[ "def", "scf_compute_coeffs_axi", "(", "dens", ",", "N", ",", "L", ",", "a", "=", "1.", ",", "radial_order", "=", "None", ",", "costheta_order", "=", "None", ")", ":", "numOfParam", "=", "0", "try", ":", "dens", "(", "0", ",", "0", ")", "numOfParam", ...
35.947368
0.021731
def start_user_session(self, username, domain, resource, **kwargs): """Method to add a user session for debugging. Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`. """ kwargs.setdefault('uptime', pytz.utc.localize(datetime.utcnow())...
[ "def", "start_user_session", "(", "self", ",", "username", ",", "domain", ",", "resource", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'uptime'", ",", "pytz", ".", "utc", ".", "localize", "(", "datetime", ".", "utcnow", "(", "...
42.315789
0.001824
def get_kwargs(self, args): """ Given a Namespace object drawn from argparse, determines the keyword arguments to pass to the underlying function. Note that, if the underlying function accepts all keyword arguments, the dictionary returned will contain the entire content...
[ "def", "get_kwargs", "(", "self", ",", "args", ")", ":", "# Now we need to figure out which arguments the final function", "# actually needs", "kwargs", "=", "{", "}", "argspec", "=", "inspect", ".", "getargspec", "(", "self", ".", "_func", ")", "required", "=", "...
38.459459
0.001371
def commit(self): """Makes a ``ReadModifyWriteRow`` API request. This commits modifications made by :meth:`append_cell_value` and :meth:`increment_cell_value`. If no modifications were made, makes no API request and just returns ``{}``. Modifies a row atomically, reading the la...
[ "def", "commit", "(", "self", ")", ":", "num_mutations", "=", "len", "(", "self", ".", "_rule_pb_list", ")", "if", "num_mutations", "==", "0", ":", "return", "{", "}", "if", "num_mutations", ">", "MAX_MUTATIONS", ":", "raise", "ValueError", "(", "\"%d tota...
42.938776
0.001394
def write_rk4(path,name,laser,omega,gamma,r,Lij,states=None,verbose=1): r""" This function writes the Fortran code needed to calculate the time evolution of the density matrix elements `\rho_{ij}` using the Runge-Kutta method of order 4. INPUT: - ``path`` - A string with the working directory where a...
[ "def", "write_rk4", "(", "path", ",", "name", ",", "laser", ",", "omega", ",", "gamma", ",", "r", ",", "Lij", ",", "states", "=", "None", ",", "verbose", "=", "1", ")", ":", "global", "omega_rescaled", "t0", "=", "time", "(", ")", "Ne", "=", "len...
33.516854
0.057947
def route_to_route_network(gtfs, walking_threshold, start_time, end_time): """ Creates networkx graph where the nodes are bus routes and a edge indicates that there is a possibility to transfer between the routes :param gtfs: :param walking_threshold: :param start_time: :param end_time: ...
[ "def", "route_to_route_network", "(", "gtfs", ",", "walking_threshold", ",", "start_time", ",", "end_time", ")", ":", "graph", "=", "networkx", ".", "Graph", "(", ")", "routes", "=", "gtfs", ".", "get_table", "(", "\"routes\"", ")", "for", "i", "in", "rout...
49.470588
0.008746
def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None): """Convert the job description to init params that can be handled by the class constructor Args: job_details: the returned job details from a describe_training_job API call. model_channel_n...
[ "def", "_prepare_init_params_from_job_description", "(", "cls", ",", "job_details", ",", "model_channel_name", "=", "None", ")", ":", "init_params", "=", "super", "(", "Estimator", ",", "cls", ")", ".", "_prepare_init_params_from_job_description", "(", "job_details", ...
45.066667
0.010145
def mavfmt(field, typeInfo=False): '''work out the struct format for a type''' map = { 'float' : ('float', 'Float'), 'double' : ('double', 'Double'), 'char' : ('byte', 'Byte'), 'int8_t' : ('byte', 'Byte'), 'uint8_t' : ('short', 'UnsignedByte'), 'uint8_...
[ "def", "mavfmt", "(", "field", ",", "typeInfo", "=", "False", ")", ":", "map", "=", "{", "'float'", ":", "(", "'float'", ",", "'Float'", ")", ",", "'double'", ":", "(", "'double'", ",", "'Double'", ")", ",", "'char'", ":", "(", "'byte'", ",", "'Byt...
33.857143
0.019152
def get_read_format(cls, source, args, kwargs): """Determine the read format for a given input source """ ctx = None if isinstance(source, FILE_LIKE): fileobj = source filepath = source.name if hasattr(source, 'name') else None else: filepath = source try: ...
[ "def", "get_read_format", "(", "cls", ",", "source", ",", "args", ",", "kwargs", ")", ":", "ctx", "=", "None", "if", "isinstance", "(", "source", ",", "FILE_LIKE", ")", ":", "fileobj", "=", "source", "filepath", "=", "source", ".", "name", "if", "hasat...
34
0.001362
def excmessage_decorator(description) -> Callable: """Wrap a function with |augment_excmessage|. Function |excmessage_decorator| is a means to apply function |augment_excmessage| more efficiently. Suppose you would apply function |augment_excmessage| in a function that adds and returns to numbers:...
[ "def", "excmessage_decorator", "(", "description", ")", "->", "Callable", ":", "@", "wrapt", ".", "decorator", "def", "wrapper", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "\"\"\"Apply |augment_excmessage| when the wrapped function fails.\"...
32.984127
0.000234
def graph2dict(g, return_dict_of_dict=True): """Takes a graph and returns an adjacency list. Parameters ---------- g : :any:`networkx.DiGraph`, :any:`networkx.Graph`, etc. Any object that networkx can turn into a :any:`DiGraph<networkx.DiGraph>`. return_dict_of_dict : bool (optional...
[ "def", "graph2dict", "(", "g", ",", "return_dict_of_dict", "=", "True", ")", ":", "if", "not", "isinstance", "(", "g", ",", "nx", ".", "DiGraph", ")", ":", "g", "=", "QueueNetworkDiGraph", "(", "g", ")", "dict_of_dicts", "=", "nx", ".", "to_dict_of_dicts...
32.44186
0.000696
def _preprocess_data(self, X, Y=None, idxs=None, train=False): """ Preprocess the data: 1. Convert sparse matrix to dense matrix. 2. Select subset of the input if idxs exists. :param X: The input data of the model. :type X: pair with candidates and corresponding features...
[ "def", "_preprocess_data", "(", "self", ",", "X", ",", "Y", "=", "None", ",", "idxs", "=", "None", ",", "train", "=", "False", ")", ":", "C", ",", "F", "=", "X", "if", "issparse", "(", "F", ")", ":", "F", "=", "np", ".", "array", "(", "F", ...
30.088235
0.001894
def _choose_host(self): """ This method randomly chooses a server from the server list given as a parameter to the parent PythonSDK :return: The selected host to which the Sender will attempt to connect """ # If a host hasn't been chosen yet or there is o...
[ "def", "_choose_host", "(", "self", ")", ":", "# If a host hasn't been chosen yet or there is only one host", "if", "len", "(", "self", ".", "_hosts", ")", "==", "1", "or", "self", ".", "_http_host", "is", "None", ":", "self", ".", "_http_host", "=", "self", "...
51.6
0.001268
def wrap_commands_in_shell(ostype, commands): """Wrap commands in a shell Originally in azure-batch-samples.Python.Batch.common.helpers :param list commands: list of commands to wrap :param str ostype: OS type, linux or windows :rtype: str :return: a shell wrapping commands """ if ostyp...
[ "def", "wrap_commands_in_shell", "(", "ostype", ",", "commands", ")", ":", "if", "ostype", ".", "lower", "(", ")", "==", "'linux'", ":", "return", "'/bin/bash -c \\'set -e; set -o pipefail; {}; wait\\''", ".", "format", "(", "';'", ".", "join", "(", "commands", ...
37.75
0.001616
def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: framelist.append((tb.tb_...
[ "def", "getinnerframes", "(", "tb", ",", "context", "=", "1", ")", ":", "framelist", "=", "[", "]", "while", "tb", ":", "framelist", ".", "append", "(", "(", "tb", ".", "tb_frame", ",", ")", "+", "getframeinfo", "(", "tb", ",", "context", ")", ")",...
39.2
0.002494
def reshape_text(buffer, from_row, to_row): """ Reformat text, taking the width into account. `to_row` is included. (Vi 'gq' operator.) """ lines = buffer.text.splitlines(True) lines_before = lines[:from_row] lines_after = lines[to_row + 1:] lines_to_reformat = lines[from_row:to_row ...
[ "def", "reshape_text", "(", "buffer", ",", "from_row", ",", "to_row", ")", ":", "lines", "=", "buffer", ".", "text", ".", "splitlines", "(", "True", ")", "lines_before", "=", "lines", "[", ":", "from_row", "]", "lines_after", "=", "lines", "[", "to_row",...
33.674419
0.000671
def disambiguate(self, word): """Disambiguate Prefix Rule 24 Rule 24 : perCAerV -> per-CAerV where C != 'r' """ matches = re.match(r'^per([bcdfghjklmnpqrstvwxyz])([a-z])er([aiueo])(.*)$', word) if matches: if matches.group(1) == 'r': return ...
[ "def", "disambiguate", "(", "self", ",", "word", ")", ":", "matches", "=", "re", ".", "match", "(", "r'^per([bcdfghjklmnpqrstvwxyz])([a-z])er([aiueo])(.*)$'", ",", "word", ")", "if", "matches", ":", "if", "matches", ".", "group", "(", "1", ")", "==", "'r'", ...
44.444444
0.009804
def func_str(func, args=[], kwargs={}, type_aliases=[], packed=False, packkw=None, truncate=False): """ string representation of function definition Returns: str: a representation of func with args, kwargs, and type_aliases Args: func (function): args (list): argum...
[ "def", "func_str", "(", "func", ",", "args", "=", "[", "]", ",", "kwargs", "=", "{", "}", ",", "type_aliases", "=", "[", "]", ",", "packed", "=", "False", ",", "packkw", "=", "None", ",", "truncate", "=", "False", ")", ":", "import", "utool", "as...
32.610169
0.000505
def startProcesses(self): """Create and start python multiprocesses Starting a multiprocess creates a process fork. In theory, there should be no problem in first starting the multithreading environment and after that perform forks (only the thread requestin the fork is copied)...
[ "def", "startProcesses", "(", "self", ")", ":", "self", ".", "process_map", "=", "{", "}", "# each key is a list of started multiprocesses", "# self.process_avail = {} # count instances", "for", "mvision_class", "in", "self", ".", "mvision_classes", ":", "name", "=", "m...
48.304348
0.010591
def _parse11(self): """Messages are split into chunks. Chunks and messages are delimited by the regex #RE_NC11_DELIM defined earlier in this file. Each time we get called here either a chunk delimiter or an end-of-message delimiter should be found iff there is enough data. If th...
[ "def", "_parse11", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"_parse11: starting\"", ")", "# suck in whole string that we have (this is what we will work on in", "# this function) and initialize a couple of useful values", "self", ".", "_buffer", ".", ...
50.058824
0.002305
def SystemNamedDict(name, fields, description=None): '''A SystemNamedDict object is simply a NamedDict intended for internal (dagster) use. ''' return NamedDict(name, fields, description, ConfigTypeAttributes(is_system_config=True))
[ "def", "SystemNamedDict", "(", "name", ",", "fields", ",", "description", "=", "None", ")", ":", "return", "NamedDict", "(", "name", ",", "fields", ",", "description", ",", "ConfigTypeAttributes", "(", "is_system_config", "=", "True", ")", ")" ]
60.25
0.012295