text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def run(self, reporter=None): """This should generally not be overloaded. Runs the benchmark functions that are found in the child class. """ if not reporter: reporter = ConsoleReporter() benchmarks = sorted(self._find_benchmarks()) reporter.write_titles(map(self._...
[ "def", "run", "(", "self", ",", "reporter", "=", "None", ")", ":", "if", "not", "reporter", ":", "reporter", "=", "ConsoleReporter", "(", ")", "benchmarks", "=", "sorted", "(", "self", ".", "_find_benchmarks", "(", ")", ")", "reporter", ".", "write_title...
41.666667
14.428571
def add_user(name, password=None, read_only=None, db=None, **kwargs): """ Adds a user that can be used for authentication. @param name: the name of the user to create @param passowrd: the password of the user to create. Can not be used with the userSource argument. @param read_only: if ...
[ "def", "add_user", "(", "name", ",", "password", "=", "None", ",", "read_only", "=", "None", ",", "db", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "CONNECTION", ".", "add_user", "(", "name", ",", "password", "=", "password", ",", "read...
47.916667
23.666667
def do_gui_update(self): """ This method gets called also by Timer, a new thread, and so needs to lock the update """ with self.update_lock: changed_widget_dict = {} self.root.repr(changed_widget_dict) for widget in changed_widget_dict.keys(): ...
[ "def", "do_gui_update", "(", "self", ")", ":", "with", "self", ".", "update_lock", ":", "changed_widget_dict", "=", "{", "}", "self", ".", "root", ".", "repr", "(", "changed_widget_dict", ")", "for", "widget", "in", "changed_widget_dict", ".", "keys", "(", ...
48.454545
11.818182
def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[powe...
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "power_status", "=", "SYSTEM_POWER_STATUS", "(", ")", "if", "not", "GetSystemPowerStatus", "(", "pointer", "(", "power_status", ")", ")", ":", "raise", "WinError", "(", ")", "if", "POWER_TYPE_MAP", "["...
41.357143
17.071429
def jsonrpc_map(self, request): """ Map of json-rpc available calls. :return str: """ result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return HttpR...
[ "def", "jsonrpc_map", "(", "self", ",", "request", ")", ":", "result", "=", "\"<h1>JSON-RPC map</h1><pre>{0}</pre>\"", ".", "format", "(", "\"\\n\\n\"", ".", "join", "(", "[", "\"{0}: {1}\"", ".", "format", "(", "fname", ",", "f", ".", "__doc__", ")", "for",...
29.545455
17.818182
def place_svg_use_coords(self, x, y, symbol_id, layer_id, group=None): """Similar to :meth:`place` but with an id as :paramref:`symbol_id`. :param str symbol_id: an id which identifies an svg object defined in the defs :param dict group: a dictionary of values to add to the group the ...
[ "def", "place_svg_use_coords", "(", "self", ",", "x", ",", "y", ",", "symbol_id", ",", "layer_id", ",", "group", "=", "None", ")", ":", "if", "group", "is", "None", ":", "group", "=", "{", "}", "use", "=", "{", "\"@x\"", ":", "x", ",", "\"@y\"", ...
41.625
18.6875
def annotate_metadata_platform(repo): """ Update metadata host information """ print("Added platform information") package = repo.package mgr = plugins_get_mgr() repomgr = mgr.get(what='instrumentation', name='platform') package['platform'] = repomgr.get_metadata()
[ "def", "annotate_metadata_platform", "(", "repo", ")", ":", "print", "(", "\"Added platform information\"", ")", "package", "=", "repo", ".", "package", "mgr", "=", "plugins_get_mgr", "(", ")", "repomgr", "=", "mgr", ".", "get", "(", "what", "=", "'instrumenta...
28.9
10.5
def synchronize(self): """ Synchronize Spyder's path list with PYTHONPATH environment variable Only apply to: current user, on Windows platforms """ answer = QMessageBox.question(self, _("Synchronize"), _("This will synchronize Spyder's path list with " ...
[ "def", "synchronize", "(", "self", ")", ":", "answer", "=", "QMessageBox", ".", "question", "(", "self", ",", "_", "(", "\"Synchronize\"", ")", ",", "_", "(", "\"This will synchronize Spyder's path list with \"", "\"<b>PYTHONPATH</b> environment variable for current user,...
46.515152
18.090909
def sendintr(self): '''This sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line. ''' n, byte = self.ptyproc.sendintr() self._log_control(byte)
[ "def", "sendintr", "(", "self", ")", ":", "n", ",", "byte", "=", "self", ".", "ptyproc", ".", "sendintr", "(", ")", "self", ".", "_log_control", "(", "byte", ")" ]
35.666667
19
def _reset(self, **kwargs): """ Reset the objects attributes. Accepts servers as either unflattened or flattened UUID strings or Server objects. """ super(Tag, self)._reset(**kwargs) # backup name for changing it (look: Tag.save) self._api_name = self.name ...
[ "def", "_reset", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Tag", ",", "self", ")", ".", "_reset", "(", "*", "*", "kwargs", ")", "# backup name for changing it (look: Tag.save)", "self", ".", "_api_name", "=", "self", ".", "name", "# ...
36.055556
19.944444
def workflow_incomplete(self): """ **Purpose**: Method to check if the workflow execution is incomplete. """ try: for pipe in self._workflow: with pipe.lock: if pipe.completed: pass else: ...
[ "def", "workflow_incomplete", "(", "self", ")", ":", "try", ":", "for", "pipe", "in", "self", ".", "_workflow", ":", "with", "pipe", ".", "lock", ":", "if", "pipe", ".", "completed", ":", "pass", "else", ":", "return", "True", "return", "False", "excep...
28.722222
16.055556
def symmetry_normalised_sites(self, scaled_positions): """Returns an array of same size as *scaled_positions*, containing the corresponding symmetry-equivalent sites within the unit cell of lowest indices. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> s...
[ "def", "symmetry_normalised_sites", "(", "self", ",", "scaled_positions", ")", ":", "scaled", "=", "np", ".", "array", "(", "scaled_positions", ",", "ndmin", "=", "2", ")", "normalised", "=", "np", ".", "empty", "(", "scaled", ".", "shape", ",", "np", "....
38.791667
13.625
def _createSegment(cls, connections, lastUsedIterationForSegment, cell, iteration, maxSegmentsPerCell): """ Create a segment on the connections, enforcing the maxSegmentsPerCell parameter. """ # Enforce maxSegmentsPerCell. while connections.numSegments(cell) >= maxSegmentsPe...
[ "def", "_createSegment", "(", "cls", ",", "connections", ",", "lastUsedIterationForSegment", ",", "cell", ",", "iteration", ",", "maxSegmentsPerCell", ")", ":", "# Enforce maxSegmentsPerCell.", "while", "connections", ".", "numSegments", "(", "cell", ")", ">=", "max...
37.178571
19.964286
def _move_install_requirements_markers(self): """ Move requirements in `install_requires` that are using environment markers `extras_require`. """ # divide the install_requires into two sets, simple ones still # handled by install_requires and more complex ones handled ...
[ "def", "_move_install_requirements_markers", "(", "self", ")", ":", "# divide the install_requires into two sets, simple ones still", "# handled by install_requires and more complex ones handled", "# by extras_require.", "def", "is_simple_req", "(", "req", ")", ":", "return", "not", ...
39
20.6
def default(session, django_dep=('django',)): """Default unit test session. """ # Install all test dependencies, then install this package in-place. deps = UNIT_TEST_DEPS deps += django_dep session.install(*deps) for local_dep in LOCAL_DEPS: session.install('-e', local_dep) ses...
[ "def", "default", "(", "session", ",", "django_dep", "=", "(", "'django'", ",", ")", ")", ":", "# Install all test dependencies, then install this package in-place.", "deps", "=", "UNIT_TEST_DEPS", "deps", "+=", "django_dep", "session", ".", "install", "(", "*", "de...
25.038462
16.346154
def set_cover_tilt_position(self, position, channel=None): """Seek a specific value by specifying a float() from 0.0 to 1.0.""" try: position = float(position) except Exception as err: LOG.debug("HelperActorBlindTilt.set_level_2: Exception %s" % (err,)) return...
[ "def", "set_cover_tilt_position", "(", "self", ",", "position", ",", "channel", "=", "None", ")", ":", "try", ":", "position", "=", "float", "(", "position", ")", "except", "Exception", "as", "err", ":", "LOG", ".", "debug", "(", "\"HelperActorBlindTilt.set_...
38.214286
20.5
def chart_type(self, value): """Set the MetricsGraphics chart type. Allowed charts are: line, histogram, point, and bar Args: value (str): chart type. Raises: ValueError: Not a valid chart type. """ if value not in self._allow...
[ "def", "chart_type", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "self", ".", "_allowed_charts", ":", "raise", "ValueError", "(", "\"Not a valid chart type\"", ")", "self", ".", "options", "[", "\"chart_type\"", "]", "=", "value" ]
29.714286
16.5
def parseruninfo(self): """Extracts the flowcell ID, as well as the instrument name from RunInfo.xml. If this file is not provided, NA values are substituted""" # Check if the RunInfo.xml file is provided, otherwise, yield N/A try: runinfo = ElementTree.ElementTree(file=self....
[ "def", "parseruninfo", "(", "self", ")", ":", "# Check if the RunInfo.xml file is provided, otherwise, yield N/A", "try", ":", "runinfo", "=", "ElementTree", ".", "ElementTree", "(", "file", "=", "self", ".", "runinfo", ")", "# Get the run id from the", "for", "elem", ...
46.869565
16.043478
def bias(mass, z, h=h, Om_M=Om_M, Om_L=Om_L): """Calculate halo bias, from Seljak & Warren 2004. Parameters ---------- mass : ndarray or float Halo mass to calculate bias for. z : ndarray or float Halo z, same type and size as mass. h : float, optional Hubble parameter, ...
[ "def", "bias", "(", "mass", ",", "z", ",", "h", "=", "h", ",", "Om_M", "=", "Om_M", ",", "Om_L", "=", "Om_L", ")", ":", "M_nl_0", "=", "(", "8.73", "/", "h", ")", "*", "(", "10.", "**", "12.", ")", "# nonlinear mass today [M_sun]", "M_nl", "=", ...
36.564103
21.25641
def series_resistors(target, pore_area='pore.area', throat_area='throat.area', pore_thermal_conductivity='pore.thermal_conductivity', throat_thermal_conductivity='throat.thermal_conductivity', conduit_lengths='throa...
[ "def", "series_resistors", "(", "target", ",", "pore_area", "=", "'pore.area'", ",", "throat_area", "=", "'throat.area'", ",", "pore_thermal_conductivity", "=", "'pore.thermal_conductivity'", ",", "throat_thermal_conductivity", "=", "'throat.thermal_conductivity'", ",", "co...
39.932203
26.016949
def create_router(self, name, ext_network=None, admin_state_up=True): ''' Creates a new router ''' body = {'name': name, 'admin_state_up': admin_state_up} if ext_network: net_id = self._find_network_id(ext_network) body['external_gateway_in...
[ "def", "create_router", "(", "self", ",", "name", ",", "ext_network", "=", "None", ",", "admin_state_up", "=", "True", ")", ":", "body", "=", "{", "'name'", ":", "name", ",", "'admin_state_up'", ":", "admin_state_up", "}", "if", "ext_network", ":", "net_id...
41
20.6
def _execute_commands_from_dir(self, directory): """Re-attempt to split and execute the failed commands""" # Get file paths and contents commands = get_commands_from_dir(directory) # Execute failed commands again print('\tAttempting to execute {0} failed commands'.format(len(com...
[ "def", "_execute_commands_from_dir", "(", "self", ",", "directory", ")", ":", "# Get file paths and contents", "commands", "=", "get_commands_from_dir", "(", "directory", ")", "# Execute failed commands again", "print", "(", "'\\tAttempting to execute {0} failed commands'", "."...
50.25
18.125
def _gatherUpdatedJobs(self, updatedJobTuple): """Gather any new, updated jobGraph from the batch system""" jobID, result, wallTime = updatedJobTuple # easy, track different state try: updatedJob = self.jobBatchSystemIDToIssuedJob[jobID] except KeyError: l...
[ "def", "_gatherUpdatedJobs", "(", "self", ",", "updatedJobTuple", ")", ":", "jobID", ",", "result", ",", "wallTime", "=", "updatedJobTuple", "# easy, track different state", "try", ":", "updatedJob", "=", "self", ".", "jobBatchSystemIDToIssuedJob", "[", "jobID", "]"...
48.35
18.35
def cartopy_globe(self): """Initialize a `cartopy.crs.Globe` from the metadata.""" if 'earth_radius' in self._attrs: kwargs = {'ellipse': 'sphere', 'semimajor_axis': self._attrs['earth_radius'], 'semiminor_axis': self._attrs['earth_radius']} else: at...
[ "def", "cartopy_globe", "(", "self", ")", ":", "if", "'earth_radius'", "in", "self", ".", "_attrs", ":", "kwargs", "=", "{", "'ellipse'", ":", "'sphere'", ",", "'semimajor_axis'", ":", "self", ".", "_attrs", "[", "'earth_radius'", "]", ",", "'semiminor_axis'...
51.625
26.0625
def desc(self) -> str: """A helper property to describe a token as a string for debugging""" kind, value = self.kind.value, self.value return f"{kind} {value!r}" if value else kind
[ "def", "desc", "(", "self", ")", "->", "str", ":", "kind", ",", "value", "=", "self", ".", "kind", ".", "value", ",", "self", ".", "value", "return", "f\"{kind} {value!r}\"", "if", "value", "else", "kind" ]
50.25
10
def crop(self, lat, lon, var): """ Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the ...
[ "def", "crop", "(", "self", ",", "lat", ",", "lon", ",", "var", ")", ":", "dims", ",", "idx", "=", "cropIndices", "(", "self", ".", "dims", ",", "lat", ",", "lon", ")", "subset", "=", "{", "}", "for", "v", "in", "var", ":", "subset", "=", "{"...
40.4
23.5
def sort_by_efficiency(self, reverse=True): """Sort the configurations in place. items with highest efficiency come first""" self._confs.sort(key=lambda c: c.efficiency, reverse=reverse) return self
[ "def", "sort_by_efficiency", "(", "self", ",", "reverse", "=", "True", ")", ":", "self", ".", "_confs", ".", "sort", "(", "key", "=", "lambda", "c", ":", "c", ".", "efficiency", ",", "reverse", "=", "reverse", ")", "return", "self" ]
54.75
13.25
def configure_parser(self, parser): """ Adds the necessary supported arguments to the argument parser. Args: parser (argparse.ArgumentParser): The parser to add arguments to. """ parser.add_argument("--log_path", default="", help="The log file path") parser.a...
[ "def", "configure_parser", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "\"--log_path\"", ",", "default", "=", "\"\"", ",", "help", "=", "\"The log file path\"", ")", "parser", ".", "add_argument", "(", "\"--verbose\"", ",", "help"...
43.555556
26
async def _request_io(self, h11_request, h11_body, h11_connection): ''' Takes care of the i/o side of the request once it's been built, and calls a couple of cleanup functions to check for redirects / store cookies and the likes. Args: h11_request (h11.Request): A h1...
[ "async", "def", "_request_io", "(", "self", ",", "h11_request", ",", "h11_body", ",", "h11_connection", ")", ":", "await", "self", ".", "_send", "(", "h11_request", ",", "h11_body", ",", "h11_connection", ")", "response_obj", "=", "await", "self", ".", "_cat...
39.511111
23.333333
def find_one(self): """ Return the first index of an entry that is either one or DC. If no item is found, return None. """ num = quotient = 0 while num < self._len: chunk = self.data[quotient] if chunk & self.one_mask: remainder = 0...
[ "def", "find_one", "(", "self", ")", ":", "num", "=", "quotient", "=", "0", "while", "num", "<", "self", ".", "_len", ":", "chunk", "=", "self", ".", "data", "[", "quotient", "]", "if", "chunk", "&", "self", ".", "one_mask", ":", "remainder", "=", ...
33.1
10.5
def get_mnemonics_from_regex(self, pattern): """ Should probably integrate getting curves with regex, vs getting with aliases, even though mixing them is probably confusing. For now I can't think of another use case for these wildcards, so I'll just implement for the curve table ...
[ "def", "get_mnemonics_from_regex", "(", "self", ",", "pattern", ")", ":", "regex", "=", "re", ".", "compile", "(", "pattern", ")", "keys", "=", "list", "(", "self", ".", "data", ".", "keys", "(", ")", ")", "return", "[", "m", ".", "group", "(", "0"...
50
18.727273
def get_setter(cls, prop_name, # @NoSelf user_setter=None, setter_takes_name=False, user_getter=None, getter_takes_name=False): """The setter follows the rules of the getter. First search for property variable, then logical custom setter. If no setter i...
[ "def", "get_setter", "(", "cls", ",", "prop_name", ",", "# @NoSelf", "user_setter", "=", "None", ",", "setter_takes_name", "=", "False", ",", "user_getter", "=", "None", ",", "getter_takes_name", "=", "False", ")", ":", "has_prop_variable", "=", "cls", ".", ...
41.120879
19.736264
def write (self, vm_address, value): """ Writes to VM addresses of Siemens Logo. Example: write("VW10", 200) or write("V10.3", 1) :param vm_address: write offset :param value: integer """ area = snap7types.S7AreaDB db_number = 1 start = 0 ...
[ "def", "write", "(", "self", ",", "vm_address", ",", "value", ")", ":", "area", "=", "snap7types", ".", "S7AreaDB", "db_number", "=", "1", "start", "=", "0", "amount", "=", "1", "wordlen", "=", "0", "data", "=", "bytearray", "(", "0", ")", "logger", ...
37.859375
14.546875
def search_meta(self, attr, value=None, stronly=False): """ Get a list of Symbols by searching a specific meta attribute, and optionally the value. Parameters ---------- attr : str The meta attribute to query. value : None, str or list ...
[ "def", "search_meta", "(", "self", ",", "attr", ",", "value", "=", "None", ",", "stronly", "=", "False", ")", ":", "if", "stronly", ":", "qry", "=", "self", ".", "ses", ".", "query", "(", "Symbol", ".", "name", ")", ".", "join", "(", "SymbolMeta", ...
32.404255
18.382979
def configure(self, inputs, outputs): """Configure activity input and output. You need to provide a list of input and output :class:`Property`. Does not work with lists of propery id's. :param inputs: iterable of input property models :type inputs: list(:class:`Property`) :para...
[ "def", "configure", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "def", "_get_propertyset", "(", "proplist", ")", ":", "\"\"\"Make it into a unique list of properties to configure for either inputs or outputs.\"\"\"", "from", "pykechain", ".", "models", "import", ...
46.6
22.057143
def init_db(self): """Connect to the database, and create tables if necessary.""" # use detect_types so that timestamps return datetime objects self.db = sqlite3.connect(self.hist_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) self.db.execute("""CR...
[ "def", "init_db", "(", "self", ")", ":", "# use detect_types so that timestamps return datetime objects", "self", ".", "db", "=", "sqlite3", ".", "connect", "(", "self", ".", "hist_file", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", "|", "sqlite3", ...
59.411765
15.470588
def format_obj_keys(obj, formatter): """ Take a dictionary with string keys and recursively convert all keys from one form to another using the formatting function. The dictionary may contain lists as values, and any nested dictionaries within those lists will also be converted. :param object ...
[ "def", "format_obj_keys", "(", "obj", ",", "formatter", ")", ":", "if", "type", "(", "obj", ")", "==", "list", ":", "return", "[", "format_obj_keys", "(", "o", ",", "formatter", ")", "for", "o", "in", "obj", "]", "elif", "type", "(", "obj", ")", "=...
30.439024
19.658537
def make_hook_path(self): """ Compute the path to the hook URL """ token = self.settings()['token'] h = sha256() h.update(token.encode()) key = str(h.hexdigest()) return f'/hooks/telegram/{key}'
[ "def", "make_hook_path", "(", "self", ")", ":", "token", "=", "self", ".", "settings", "(", ")", "[", "'token'", "]", "h", "=", "sha256", "(", ")", "h", ".", "update", "(", "token", ".", "encode", "(", ")", ")", "key", "=", "str", "(", "h", "."...
25
9.2
def keysyms_from_strings(): """Yields the tuple ``(character, symbol name)`` for all keysyms. """ for number, codepoint, status, name in keysym_definitions(): # Ignore keysyms that do not map to unicode characters if all(c == '0' for c in codepoint): continue # Ignore ke...
[ "def", "keysyms_from_strings", "(", ")", ":", "for", "number", ",", "codepoint", ",", "status", ",", "name", "in", "keysym_definitions", "(", ")", ":", "# Ignore keysyms that do not map to unicode characters", "if", "all", "(", "c", "==", "'0'", "for", "c", "in"...
32.538462
17
def from_function(cls, func): """Constructs Signature for the given python function""" if not isinstance(func, types.FunctionType): raise TypeError("{!r} is not a Python function".format(func)) Parameter = cls._parameter_cls # Parameter information. func_code = fun...
[ "def", "from_function", "(", "cls", ",", "func", ")", ":", "if", "not", "isinstance", "(", "func", ",", "types", ".", "FunctionType", ")", ":", "raise", "TypeError", "(", "\"{!r} is not a Python function\"", ".", "format", "(", "func", ")", ")", "Parameter",...
34.864198
19.308642
def getTable(self, layer, where="1 = 1", fields=[], jsobj=None): """ Returns JSON for a Table type. You shouldn't use this directly -- it's an automatic falback from .get if there is no geometry """ base_where = where features = [] # We always want to run once, an...
[ "def", "getTable", "(", "self", ",", "layer", ",", "where", "=", "\"1 = 1\"", ",", "fields", "=", "[", "]", ",", "jsobj", "=", "None", ")", ":", "base_where", "=", "where", "features", "=", "[", "]", "# We always want to run once, and then break out as soon as...
48.590909
19.590909
def filter_user(user, using='records', interaction=None, part_of_week='allweek', part_of_day='allday'): """ Filter records of a User objects by interaction, part of week and day. Parameters ---------- user : User a bandicoot User object type : str, default 'records' ...
[ "def", "filter_user", "(", "user", ",", "using", "=", "'records'", ",", "interaction", "=", "None", ",", "part_of_week", "=", "'allweek'", ",", "part_of_day", "=", "'allday'", ")", ":", "if", "using", "==", "'recharges'", ":", "records", "=", "user", ".", ...
37.857143
18.206349
def assemble(self, ops): """ Assemble a list of operations into executable code. Arguments: ops(list): A list of shellcode operations. Returns: bytes: The executable code that implements the shellcode. """ return pwnypack.asm.asm(self.compile(op...
[ "def", "assemble", "(", "self", ",", "ops", ")", ":", "return", "pwnypack", ".", "asm", ".", "asm", "(", "self", ".", "compile", "(", "ops", ")", ",", "target", "=", "self", ".", "target", ")" ]
27.666667
22.833333
def _get_instance_key(self, host, namespace, wmi_class, other=None): """ Return an index key for a given instance. Useful for caching. """ if other: return "{host}:{namespace}:{wmi_class}-{other}".format( host=host, namespace=namespace, wmi_class=wmi_class, ot...
[ "def", "_get_instance_key", "(", "self", ",", "host", ",", "namespace", ",", "wmi_class", ",", "other", "=", "None", ")", ":", "if", "other", ":", "return", "\"{host}:{namespace}:{wmi_class}-{other}\"", ".", "format", "(", "host", "=", "host", ",", "namespace"...
44.3
28.1
def writer(datasets, dataset_names, output_dir): """Write the results.""" for dataset, dataset_name in zip(datasets, dataset_names): if dataset: filepath = output_dir + '/' + dataset_name + '.txt' with open(filepath, 'w+') as out_file: joined = '\n'.join(dataset) ...
[ "def", "writer", "(", "datasets", ",", "dataset_names", ",", "output_dir", ")", ":", "for", "dataset", ",", "dataset_name", "in", "zip", "(", "datasets", ",", "dataset_names", ")", ":", "if", "dataset", ":", "filepath", "=", "output_dir", "+", "'/'", "+", ...
47.111111
14
def from_headers(self, headers): """Generate a SpanContext object using the W3C Distributed Tracing headers. :type headers: dict :param headers: HTTP request headers. :rtype: :class:`~opencensus.trace.span_context.SpanContext` :returns: SpanContext generated from the trace cont...
[ "def", "from_headers", "(", "self", ",", "headers", ")", ":", "if", "headers", "is", "None", ":", "return", "SpanContext", "(", ")", "header", "=", "headers", ".", "get", "(", "_TRACEPARENT_HEADER_NAME", ")", "if", "header", "is", "None", ":", "return", ...
31.039216
17.235294
def vadd(v1, v2): """ Add two 3 dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vadd_c.html :param v1: First vector to be added. :type v1: 3-Element Array of floats :param v2: Second vector to be added. :type v2: 3-Element Array of floats :return: v1+v2 :r...
[ "def", "vadd", "(", "v1", ",", "v2", ")", ":", "v1", "=", "stypes", ".", "toDoubleVector", "(", "v1", ")", "v2", "=", "stypes", ".", "toDoubleVector", "(", "v2", ")", "vout", "=", "stypes", ".", "emptyDoubleVector", "(", "3", ")", "libspice", ".", ...
32.9375
9.125
def normalized(self): """:obj:`DualQuaternion`: This quaternion with qr normalized. """ qr = self.qr /1./ np.linalg.norm(self.qr) return DualQuaternion(qr, self.qd, True)
[ "def", "normalized", "(", "self", ")", ":", "qr", "=", "self", ".", "qr", "/", "1.", "/", "np", ".", "linalg", ".", "norm", "(", "self", ".", "qr", ")", "return", "DualQuaternion", "(", "qr", ",", "self", ".", "qd", ",", "True", ")" ]
39.6
7.2
def namespace_to_dict(o): """Convert an argparse namespace object to a dictionary.""" d = {} for k, v in o.__dict__.items(): if not callable(v): d[k] = v return d
[ "def", "namespace_to_dict", "(", "o", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "o", ".", "__dict__", ".", "items", "(", ")", ":", "if", "not", "callable", "(", "v", ")", ":", "d", "[", "k", "]", "=", "v", "return", "d" ]
27.428571
15.857143
def get(args): """ Get a river by name. """ m = RiverManager(args.hosts) r = m.get(args.name) if r: print(json.dumps(r, indent=2)) else: sys.exit(1)
[ "def", "get", "(", "args", ")", ":", "m", "=", "RiverManager", "(", "args", ".", "hosts", ")", "r", "=", "m", ".", "get", "(", "args", ".", "name", ")", "if", "r", ":", "print", "(", "json", ".", "dumps", "(", "r", ",", "indent", "=", "2", ...
18.3
15.1
def setup(self): """First time setup.""" super(RogersExperiment, self).setup() for net in random.sample(self.networks(role="experiment"), self.catch_repeats): net.role = "catch" for net in self.networks(): source = self.models.RogersSource(network=net) ...
[ "def", "setup", "(", "self", ")", ":", "super", "(", "RogersExperiment", ",", "self", ")", ".", "setup", "(", ")", "for", "net", "in", "random", ".", "sample", "(", "self", ".", "networks", "(", "role", "=", "\"experiment\"", ")", ",", "self", ".", ...
41.571429
19.928571
def _fetch_layer_uri(self, layer): """ Fetch the Layer Uri based on the LayerVersion Arn Parameters ---------- layer samcli.commands.local.lib.provider.LayerVersion LayerVersion to fetch Returns ------- str The Uri to download the...
[ "def", "_fetch_layer_uri", "(", "self", ",", "layer", ")", ":", "try", ":", "layer_version_response", "=", "self", ".", "lambda_client", ".", "get_layer_version", "(", "LayerName", "=", "layer", ".", "layer_arn", ",", "VersionNumber", "=", "layer", ".", "versi...
40.475
28.625
def starts_with(ctx, full, part): ''' Yields one boolean, whether the first string starts with the second ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield full.startswith(part)
[ "def", "starts_with", "(", "ctx", ",", "full", ",", "part", ")", ":", "full", "=", "next", "(", "string_arg", "(", "ctx", ",", "full", ")", ",", "''", ")", "part", "=", "next", "(", "string_arg", "(", "ctx", ",", "part", ")", ",", "''", ")", "y...
33.285714
16.714286
def get_decoder(libdir=None, modeldir=None, lang='en-us'): """ Create a decoder with the requested language model """ modeldir = modeldir or (os.path.join(libdir, 'model') if libdir else MODELDIR) libdir = os.path.dirname(modeldir) config = ps.Decoder.default_config() config.set_string('-hmm', os.pa...
[ "def", "get_decoder", "(", "libdir", "=", "None", ",", "modeldir", "=", "None", ",", "lang", "=", "'en-us'", ")", ":", "modeldir", "=", "modeldir", "or", "(", "os", ".", "path", ".", "join", "(", "libdir", ",", "'model'", ")", "if", "libdir", "else",...
53.8
18.8
def _qr_factor_full(a, dtype=np.float): """Compute the QR factorization of a matrix, with pivoting. Parameters: a - An n-by-m arraylike, m >= n. dtype - (optional) The data type to use for computations. Default is np.float. Returns: q - An m-by-m orthogonal matrix (q q^T = ident) r - An n-by-m u...
[ "def", "_qr_factor_full", "(", "a", ",", "dtype", "=", "np", ".", "float", ")", ":", "n", ",", "m", "=", "a", ".", "shape", "# Compute the packed Q and R matrix information.", "packed", ",", "pmut", ",", "rdiag", ",", "acnorm", "=", "_manual_qr_factor_packed",...
28.916667
22.883333
def hybrid_forward(self, F, inputs, states, i2h_weight, h2h_weight, h2r_weight, i2h_bias, h2h_bias): r"""Hybrid forward computation for Long-Short Term Memory Projected network cell with cell clip and projection clip. Parameters ---------- inputs : input t...
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "states", ",", "i2h_weight", ",", "h2h_weight", ",", "h2r_weight", ",", "i2h_bias", ",", "h2h_bias", ")", ":", "prefix", "=", "'t%d_'", "%", "self", ".", "_counter", "i2h", "=", "F", "...
56.275
27.5
def telnet_sa_telnet_server_standby_enable(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") telnet_sa = ET.SubElement(config, "telnet-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services") telnet = ET.SubElement(telnet_sa, "telnet") server = ET.S...
[ "def", "telnet_sa_telnet_server_standby_enable", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "telnet_sa", "=", "ET", ".", "SubElement", "(", "config", ",", "\"telnet-sa\"", ",", "xmlns", "=", ...
44
15.916667
def urlretrieve(url, filename=None, reporthook=None, data=None): """ Retrieve a URL into a temporary location on disk. Requires a URL argument. If a filename is passed, it is used as the temporary file location. The reporthook argument should be a callable that accepts a block number, a read size, ...
[ "def", "urlretrieve", "(", "url", ",", "filename", "=", "None", ",", "reporthook", "=", "None", ",", "data", "=", "None", ")", ":", "url_type", ",", "path", "=", "splittype", "(", "url", ")", "with", "contextlib", ".", "closing", "(", "urlopen", "(", ...
32.645161
18.387097
def get_table_frame(self, prefix="", table_id="sspdtable", *args, **kwargs): """ render the structure (or structure_for_superuser) and an instance of the footer form :param prefix: str: used for unifying the rendered parameter's name, such that the template of se...
[ "def", "get_table_frame", "(", "self", ",", "prefix", "=", "\"\"", ",", "table_id", "=", "\"sspdtable\"", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "table_id", ":", "raise", "ValueError", "(", "\"table_id parameter can not be an empty s...
37.461538
22.076923
def __regrab(changes): """ Takes a dictionary of changes (mapping old keycode to new keycode) and regrabs any keys that have been changed with the updated keycode. :param changes: Mapping of changes from old keycode to new keycode. :type changes: dict :rtype: void """ for wid, mods, kc ...
[ "def", "__regrab", "(", "changes", ")", ":", "for", "wid", ",", "mods", ",", "kc", "in", "__keybinds", ".", "keys", "(", ")", ":", "if", "kc", "in", "changes", ":", "ungrab_key", "(", "wid", ",", "mods", ",", "kc", ")", "grab_key", "(", "wid", ",...
32.722222
15.611111
def setEditorData( self, editor, value ): """ Sets the value for the given editor to the inputed value. :param editor | <QWidget> value | <variant> """ # set the data for a multitagedit if ( isinstance(editor, XMultiTag...
[ "def", "setEditorData", "(", "self", ",", "editor", ",", "value", ")", ":", "# set the data for a multitagedit\r", "if", "(", "isinstance", "(", "editor", ",", "XMultiTagEdit", ")", ")", ":", "if", "(", "not", "isinstance", "(", "value", ",", "list", ")", ...
35.321429
11.035714
def insert(objects, collection, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Insert an object or list of objects into a collection CLI Example: .. code-block:: bash salt '*' mongodb.insert '[{"foo": "FOO", "bar": "BAR"}, {"foo": "BAZ", "bar": ...
[ "def", "insert", "(", "objects", ",", "collection", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_co...
32.333333
27.4
def inflate(cls, rel): """ Inflate a neo4j_driver relationship object to a neomodel object :param rel: :return: StructuredRel """ props = {} for key, prop in cls.defined_properties(aliases=False, rels=False).items(): if key in rel: prop...
[ "def", "inflate", "(", "cls", ",", "rel", ")", ":", "props", "=", "{", "}", "for", "key", ",", "prop", "in", "cls", ".", "defined_properties", "(", "aliases", "=", "False", ",", "rels", "=", "False", ")", ".", "items", "(", ")", ":", "if", "key",...
33.894737
14.947368
def orderc(array, ndim=None): """ Determine the order of elements in an array of character strings. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/orderc_c.html :param array: Input array. :type array: Array of strings. :param ndim: Optional Length of input array :type ndim: int ...
[ "def", "orderc", "(", "array", ",", "ndim", "=", "None", ")", ":", "if", "ndim", "is", "None", ":", "ndim", "=", "ctypes", ".", "c_int", "(", "len", "(", "array", ")", ")", "else", ":", "ndim", "=", "ctypes", ".", "c_int", "(", "ndim", ")", "le...
32.772727
14.5
def get_user_application_data_directory(): """ | Returns the user Application directory. | The difference between :func:`get_user_application_data_directory` and :func:`get_system_application_data_directory` definitions is that :func:`get_user_application_data_directory` definition will appe...
[ "def", "get_user_application_data_directory", "(", ")", ":", "system_application_data_directory", "=", "get_system_application_data_directory", "(", ")", "if", "not", "foundations", ".", "common", ".", "path_exists", "(", "system_application_data_directory", ")", ":", "LOGG...
56.060606
35.878788
def send_to_output(master_dict, mash_output, sample_id, assembly_file): """Send dictionary to output json file This function sends master_dict dictionary to a json file if master_dict is populated with entries, otherwise it won't create the file Parameters ---------- master_dict: dict d...
[ "def", "send_to_output", "(", "master_dict", ",", "mash_output", ",", "sample_id", ",", "assembly_file", ")", ":", "plot_dict", "=", "{", "}", "# create a new file only if master_dict is populated", "if", "master_dict", ":", "out_file", "=", "open", "(", "\"{}.json\""...
31.136364
21.121212
def hexdump(stream): ''' Display stream contents in hexadecimal and ASCII format. The ``stream`` specified must either be a file-like object that supports the ``read`` method to receive bytes, or it can be a string. To dump a file:: >>> hexdump(file(filename)) # doctest: +SKIP Or ...
[ "def", "hexdump", "(", "stream", ")", ":", "if", "isinstance", "(", "stream", ",", "six", ".", "string_types", ")", ":", "stream", "=", "BytesIO", "(", "stream", ")", "row", "=", "0", "while", "True", ":", "data", "=", "stream", ".", "read", "(", "...
25.27027
24.459459
def import_item(self, item, crawler='wiki', truncate_strings=True, verbosity=0): """Import a single record from a Scrapy Item dict >> WikiItem().import_item({'url': 'http://test.com', 'modified': '13 January 2014 00:15', 'crawler': 'more than thirty characters in this silly name'}) # doctest: +ELLIPSI...
[ "def", "import_item", "(", "self", ",", "item", ",", "crawler", "=", "'wiki'", ",", "truncate_strings", "=", "True", ",", "verbosity", "=", "0", ")", ":", "item", "=", "dict", "(", "item", ")", "self", ".", "crawler", "=", "str", "(", "crawler", ")",...
49.354839
24.83871
def overall_error_rate(self): """Overall error rate metrics (error_rate, substitution_rate, deletion_rate, and insertion_rate) Returns ------- dict results in a dictionary format """ substitution_rate = metric.substitution_rate( Nref=self.overal...
[ "def", "overall_error_rate", "(", "self", ")", ":", "substitution_rate", "=", "metric", ".", "substitution_rate", "(", "Nref", "=", "self", ".", "overall", "[", "'Nref'", "]", ",", "Nsubstitutions", "=", "self", ".", "overall", "[", "'Nsubs'", "]", ")", "d...
28.162162
17.378378
def parse_cmdline(): """Parse command-line arguments for script.""" parser = ArgumentParser(prog="average_nucleotide_identity.py") parser.add_argument( "--version", action="version", version="%(prog)s: pyani " + VERSION ) parser.add_argument( "-o", "--outdir", dest="o...
[ "def", "parse_cmdline", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "prog", "=", "\"average_nucleotide_identity.py\"", ")", "parser", ".", "add_argument", "(", "\"--version\"", ",", "action", "=", "\"version\"", ",", "version", "=", "\"%(prog)s: pyani \"", ...
26.063745
18.717131
def check_input_sample(input_sample, num_params, num_samples): """Check the `input_sample` is valid Checks input sample is: - the correct size - values between 0 and 1 Arguments --------- input_sample : numpy.ndarray num_params : int num_...
[ "def", "check_input_sample", "(", "input_sample", ",", "num_params", ",", "num_samples", ")", ":", "assert", "type", "(", "input_sample", ")", "==", "np", ".", "ndarray", ",", "\"Input sample is not an numpy array\"", "assert", "input_sample", ".", "shape", "[", "...
36.842105
17.526316
def add_bias(X): """Helper function to add a bias column to the input array X Parameters: X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray with 2 dimension wheres every row corresponds to one example of the data set, every column, one different feature. Returns: num...
[ "def", "add_bias", "(", "X", ")", ":", "return", "numpy", ".", "hstack", "(", "(", "numpy", ".", "ones", "(", "(", "len", "(", "X", ")", ",", "1", ")", ",", "dtype", "=", "X", ".", "dtype", ")", ",", "X", ")", ")" ]
24
29.947368
def open_file(self, store=current_store, use_seek=False): """Opens the file-like object which is a context manager (that means it can used for :keyword:`with` statement). If ``use_seek`` is :const:`True` (though :const:`False` by default) it guarentees the returned file-like object is a...
[ "def", "open_file", "(", "self", ",", "store", "=", "current_store", ",", "use_seek", "=", "False", ")", ":", "if", "not", "isinstance", "(", "store", ",", "Store", ")", ":", "raise", "TypeError", "(", "'store must be an instance of '", "'sqlalchemy_imageattach....
42.515152
18.969697
def _normalize_sampling_points(sampling_points, ndim): """Normalize points to an ndim-long list of linear index arrays. This helper converts sampling indices for `SamplingOperator` from integers or array-like objects to a list of length ``ndim``, where each entry is a `numpy.ndarray` with ``dtype=int``...
[ "def", "_normalize_sampling_points", "(", "sampling_points", ",", "ndim", ")", ":", "sampling_points_in", "=", "sampling_points", "if", "ndim", "==", "0", ":", "sampling_points", "=", "[", "np", ".", "array", "(", "sampling_points", ",", "dtype", "=", "int", "...
44.528302
19.641509
def setup_proxy_model(self): """Setup proxy model""" self.proxymodel = ProxyModel(self) self.proxymodel.setSourceModel(self.fsmodel)
[ "def", "setup_proxy_model", "(", "self", ")", ":", "self", ".", "proxymodel", "=", "ProxyModel", "(", "self", ")", "self", ".", "proxymodel", ".", "setSourceModel", "(", "self", ".", "fsmodel", ")" ]
39
6.5
def jsma_symbolic(x, y_target, model, theta, gamma, clip_min, clip_max): """ TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528 for details about the algorithm design choices). :param x: the input placeholder :param y_target: the target tensor :param model: a cleverhans.model.Model...
[ "def", "jsma_symbolic", "(", "x", ",", "y_target", ",", "model", ",", "theta", ",", "gamma", ",", "clip_min", ",", "clip_max", ")", ":", "nb_classes", "=", "int", "(", "y_target", ".", "shape", "[", "-", "1", "]", ".", "value", ")", "nb_features", "=...
38.093333
20.693333
def sanitize(self, table_name, column_name, value): """ Sanitizes given value extracted from the database according to the sanitation configuration. TODO: Add support for dates, booleans and other types found in SQL than string. :param table_name: Name of the database t...
[ "def", "sanitize", "(", "self", ",", "table_name", ",", "column_name", ",", "value", ")", ":", "sanitizer_callback", "=", "self", ".", "get_sanitizer_for", "(", "table_name", ",", "column_name", ")", "return", "sanitizer_callback", "(", "value", ")", "if", "sa...
37.08
23
def has_role(self, identifiers, required_role_s): """ Confirms whether a subject is a member of one or more roles. If the authorization info cannot be obtained from the accountstore, role check tuple yields False. :type identifiers: subject_abcs.IdentifierCollection :...
[ "def", "has_role", "(", "self", ",", "identifiers", ",", "required_role_s", ")", ":", "identifier", "=", "identifiers", ".", "primary_identifier", "# assigned_role_s is a set", "assigned_role_s", "=", "self", ".", "get_authzd_roles", "(", "identifier", ")", "if", "n...
34.586207
17.965517
def _volumes(self): """ returns a map {volume_id: {serial:, vendor_id:, product_id:, tty:}""" # to find all the possible mbed volumes, we look for registry entries # under all possible USB tree which have a "BSD Name" that starts with # "disk" # (i.e. this is a USB disk), and have a IOR...
[ "def", "_volumes", "(", "self", ")", ":", "# to find all the possible mbed volumes, we look for registry entries", "# under all possible USB tree which have a \"BSD Name\" that starts with", "# \"disk\" # (i.e. this is a USB disk), and have a IORegistryEntryName that", "# matches /\\cmbed/", "# ...
36.764706
20.509804
def _date_by_len(self, string): """ Parses a date from a string based on its length :param string: A unicode string to parse :return: A datetime.datetime object or a unicode string """ strlen = len(string) year_num = int(string[0:2]) ...
[ "def", "_date_by_len", "(", "self", ",", "string", ")", ":", "strlen", "=", "len", "(", "string", ")", "year_num", "=", "int", "(", "string", "[", "0", ":", "2", "]", ")", "if", "year_num", "<", "50", ":", "prefix", "=", "'20'", "else", ":", "pre...
22.961538
21.653846
def get_bottom(modality_type, value=None): """Gets default bottom transformation; if none available, return value.""" if modality_type == ModalityType.AUDIO: return audio_bottom elif modality_type == ModalityType.AUDIO_SPECTRAL: return audio_spectral_bottom elif modality_type in (ModalityType.CLASS_LABE...
[ "def", "get_bottom", "(", "modality_type", ",", "value", "=", "None", ")", ":", "if", "modality_type", "==", "ModalityType", ".", "AUDIO", ":", "return", "audio_bottom", "elif", "modality_type", "==", "ModalityType", ".", "AUDIO_SPECTRAL", ":", "return", "audio_...
46.607843
13.392157
def import_from_hdf5(network, path, skip_time=False): """ Import network data from HDF5 store at `path`. Parameters ---------- path : string Name of HDF5 store skip_time : bool, default False Skip reading in time dependent attributes """ basename = os.path.basename(path...
[ "def", "import_from_hdf5", "(", "network", ",", "path", ",", "skip_time", "=", "False", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "with", "ImporterHDF5", "(", "path", ")", "as", "importer", ":", "_import_from_importer...
29.133333
17.133333
def sort_by_abundance_usearch61(seq_path, output_dir='.', rev=False, minlen=64, remove_usearch_logs=False, HALT_EXEC=False, outp...
[ "def", "sort_by_abundance_usearch61", "(", "seq_path", ",", "output_dir", "=", "'.'", ",", "rev", "=", "False", ",", "minlen", "=", "64", ",", "remove_usearch_logs", "=", "False", ",", "HALT_EXEC", "=", "False", ",", "output_fna_filepath", "=", "None", ",", ...
39.076923
17.923077
def _get_request_params(self, **kwargs): """Merge shared params and new params.""" request_params = copy.deepcopy(self._shared_request_params) for key, value in iteritems(kwargs): if isinstance(value, dict) and key in request_params: # ensure we don't lose dict values...
[ "def", "_get_request_params", "(", "self", ",", "*", "*", "kwargs", ")", ":", "request_params", "=", "copy", ".", "deepcopy", "(", "self", ".", "_shared_request_params", ")", "for", "key", ",", "value", "in", "iteritems", "(", "kwargs", ")", ":", "if", "...
47.7
13.6
def secret_hex(self, secret_hex): """ Sets the secret_hex of this PreSharedKey. The secret of the pre-shared key in hexadecimal. It is not case sensitive; 4a is same as 4A, and it is allowed with or without 0x in the beginning. The minimum length of the secret is 128 bits and maximum 256 bits. ...
[ "def", "secret_hex", "(", "self", ",", "secret_hex", ")", ":", "if", "secret_hex", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `secret_hex`, must not be `None`\"", ")", "if", "secret_hex", "is", "not", "None", "and", "not", "re", ".", "se...
56.071429
37.642857
def _update_progress_bar(self): # type: (SyncCopy) -> None """Update progress bar :param SyncCopy self: this """ blobxfer.operations.progress.update_progress_bar( self._general_options, 'synccopy', self._synccopy_start_time, self._s...
[ "def", "_update_progress_bar", "(", "self", ")", ":", "# type: (SyncCopy) -> None", "blobxfer", ".", "operations", ".", "progress", ".", "update_progress_bar", "(", "self", ".", "_general_options", ",", "'synccopy'", ",", "self", ".", "_synccopy_start_time", ",", "s...
31.785714
7.857143
def compare2(args): """ %prog compare2 Compare performances of various variant callers on simulated STR datasets. """ p = OptionParser(compare2.__doc__) p.add_option('--maxinsert', default=300, type="int", help="Maximum number of repeats") add_simulate_options(p) opts, ...
[ "def", "compare2", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "compare2", ".", "__doc__", ")", "p", ".", "add_option", "(", "'--maxinsert'", ",", "default", "=", "300", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Maximum number of repeats\...
36.04
19.56
def _inform_if_path_does_not_exist(path): """ If the path does not exist, print a message saying so. This is intended to be helpful to users if they specify a custom path that eg cannot find. """ expanded_path = get_expanded_path(path) if not os.path.exists(expanded_path): print('Could n...
[ "def", "_inform_if_path_does_not_exist", "(", "path", ")", ":", "expanded_path", "=", "get_expanded_path", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "expanded_path", ")", ":", "print", "(", "'Could not find custom path at: {}'", ".", ...
45.375
13.625
def expects_call(self): """The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: ...
[ "def", "expects_call", "(", "self", ")", ":", "self", ".", "_callable", "=", "ExpectedCall", "(", "self", ",", "call_name", "=", "self", ".", "_name", ",", "callable", "=", "True", ")", "return", "self" ]
26.517241
19.827586
def _visit_step( self, number, step_config, visited_steps=None, parent_options=None, parent_ui_options=None, from_flow=None, ): """ for each step (as defined in the flow YAML), _visit_step is called with only the first two parameters. t...
[ "def", "_visit_step", "(", "self", ",", "number", ",", "step_config", ",", "visited_steps", "=", "None", ",", "parent_options", "=", "None", ",", "parent_ui_options", "=", "None", ",", "from_flow", "=", "None", ",", ")", ":", "number", "=", "LooseVersion", ...
43.091603
24.053435
def add_tags(self, ID3=None): """Add an empty ID3 tag to the file. Args: ID3 (ID3): An ID3 subclass to use or `None` to use the one that used when loading. A custom tag reader may be used in instead of the default `ID3` object, e.g. an `mutagen.easyid3.EasyI...
[ "def", "add_tags", "(", "self", ",", "ID3", "=", "None", ")", ":", "if", "ID3", "is", "None", ":", "ID3", "=", "self", ".", "ID3", "if", "self", ".", "tags", "is", "None", ":", "self", ".", "ID3", "=", "ID3", "self", ".", "tags", "=", "ID3", ...
29.555556
19.055556
def xlsw_write_row(ws, row_idx, row, fmt=None): """ ws: row_idx: row number row: a list, data to write fmt: format for cell """ for col_idx in range(len(row)): ws.write(row_idx, col_idx, row[col_idx], fmt) row_idx += 1 return row_idx
[ "def", "xlsw_write_row", "(", "ws", ",", "row_idx", ",", "row", ",", "fmt", "=", "None", ")", ":", "for", "col_idx", "in", "range", "(", "len", "(", "row", ")", ")", ":", "ws", ".", "write", "(", "row_idx", ",", "col_idx", ",", "row", "[", "col_i...
24.272727
13.363636
def Pr(self): r'''Prandtl number of the chemical at its current temperature, pressure, and phase; [dimensionless]. .. math:: Pr = \frac{C_p \mu}{k} Examples -------- >>> Chemical('acetone').Pr 4.183039103542709 ''' return phase_select...
[ "def", "Pr", "(", "self", ")", ":", "return", "phase_select_property", "(", "phase", "=", "self", ".", "phase", ",", "l", "=", "self", ".", "Prl", ",", "g", "=", "self", ".", "Prg", ")" ]
27.615385
23.615385
def current_grid_empty(self): """ Check to see if grid is empty except for default values """ empty = True # df IS empty if there are no rows if not any(self.magic_dataframe.df.index): empty = True # df is NOT empty if there are at least two rows ...
[ "def", "current_grid_empty", "(", "self", ")", ":", "empty", "=", "True", "# df IS empty if there are no rows", "if", "not", "any", "(", "self", ".", "magic_dataframe", ".", "df", ".", "index", ")", ":", "empty", "=", "True", "# df is NOT empty if there are at lea...
38.958333
14.375
def _ip_setter(self, ipaddr_name, ipaddrs_name, ips): """Setter for ip fields Accept as input string or list of IP instances. String case: only ipvXaddr is going to be filled, that is enough to perform host record search using ip List of IP instances case: ...
[ "def", "_ip_setter", "(", "self", ",", "ipaddr_name", ",", "ipaddrs_name", ",", "ips", ")", ":", "if", "isinstance", "(", "ips", ",", "six", ".", "string_types", ")", ":", "setattr", "(", "self", ",", "ipaddr_name", ",", "ips", ")", "elif", "isinstance",...
44.214286
14.642857
def CheckHashes(hash_ids): """Checks if files with given hashes are present in the file store. Args: hash_ids: A list of SHA256HashID objects. Returns: A dict where SHA256HashID objects are keys. Corresponding values may be False (if hash id is not present) or True if it is not present. """ retu...
[ "def", "CheckHashes", "(", "hash_ids", ")", ":", "return", "{", "k", ":", "bool", "(", "v", ")", "for", "k", ",", "v", "in", "data_store", ".", "REL_DB", ".", "ReadHashBlobReferences", "(", "hash_ids", ")", ".", "items", "(", ")", "}" ]
29.214286
25.071429
def write_data(fo, datum, schema): """Write a datum of data to output stream. Paramaters ---------- fo: file-like Output file datum: object Data to write schema: dict Schemda to use """ record_type = extract_record_type(schema) logical_type = extract_logical...
[ "def", "write_data", "(", "fo", ",", "datum", ",", "schema", ")", ":", "record_type", "=", "extract_record_type", "(", "schema", ")", "logical_type", "=", "extract_logical_type", "(", "schema", ")", "fn", "=", "WRITERS", ".", "get", "(", "record_type", ")", ...
24.68
18.64
def _populateHistogram(self): """Call the C-code that actually populates the histogram""" try : buildHistogram.populate1DHist(self._data, self.histogram, self.minValue, self.maxValue, self.binWidth) except: if ((self._data.max() - self._data.min()) < self....
[ "def", "_populateHistogram", "(", "self", ")", ":", "try", ":", "buildHistogram", ".", "populate1DHist", "(", "self", ".", "_data", ",", "self", ".", "histogram", ",", "self", ".", "minValue", ",", "self", ".", "maxValue", ",", "self", ".", "binWidth", "...
53.071429
23.428571
def task(self, task_name): """ Returns an ENVI Py Engine Task object. See ENVI Py Engine Task for examples. :param task_name: The name of the task to retrieve. :return: An ENVI Py Engine Task object. """ return Task(uri=':'.join((self._engine_name, task_name)), cwd=self....
[ "def", "task", "(", "self", ",", "task_name", ")", ":", "return", "Task", "(", "uri", "=", "':'", ".", "join", "(", "(", "self", ".", "_engine_name", ",", "task_name", ")", ")", ",", "cwd", "=", "self", ".", "_cwd", ")" ]
39.75
20.5
def diag_port(self, context, port_id, **kwargs): """Diagnose a port. :param context: neutron api request context. :param port_id: neutron port id. :param kwargs: optional kwargs. :raises IronicException: If the client is unable to fetch the downstream port for any re...
[ "def", "diag_port", "(", "self", ",", "context", ",", "port_id", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "info", "(", "\"diag_port %s\"", "%", "port_id", ")", "try", ":", "port", "=", "self", ".", "_client", ".", "show_port", "(", "port_id", "...
39.388889
11.611111