text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _cleanup(self): """Clean up resources used by the session. """ self.exit() workspace = osp.join(os.getcwd(), 'octave-workspace') if osp.exists(workspace): os.remove(workspace)
[ "def", "_cleanup", "(", "self", ")", ":", "self", ".", "exit", "(", ")", "workspace", "=", "osp", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'octave-workspace'", ")", "if", "osp", ".", "exists", "(", "workspace", ")", ":", "os", ".", ...
33
10.857143
def stop(self): """ Force the next() method to return while in another thread. The return value of next() will be None. """ with self.condition: self.running = False self.condition.notify_all()
[ "def", "stop", "(", "self", ")", ":", "with", "self", ".", "condition", ":", "self", ".", "running", "=", "False", "self", ".", "condition", ".", "notify_all", "(", ")" ]
31.25
10
def checkOptions(options, parser): """ Check options, throw parser.error() if something goes wrong """ if options.jobStore == None: parser.error("Specify --jobStore") defaultCategories = ["time", "clock", "wait", "memory"] if options.categories is None: options.categories = defaultC...
[ "def", "checkOptions", "(", "options", ",", "parser", ")", ":", "if", "options", ".", "jobStore", "==", "None", ":", "parser", ".", "error", "(", "\"Specify --jobStore\"", ")", "defaultCategories", "=", "[", "\"time\"", ",", "\"clock\"", ",", "\"wait\"", ","...
45.740741
14.111111
def remove_hwpack(name): """remove hardware package. :param name: hardware package name (e.g. 'Sanguino') :rtype: None """ targ_dlib = hwpack_dir() / name log.debug('remove %s', targ_dlib) targ_dlib.rmtree()
[ "def", "remove_hwpack", "(", "name", ")", ":", "targ_dlib", "=", "hwpack_dir", "(", ")", "/", "name", "log", ".", "debug", "(", "'remove %s'", ",", "targ_dlib", ")", "targ_dlib", ".", "rmtree", "(", ")" ]
22.8
16.2
def get_coiledcoil_region(self, cc_number=0, cutoff=7.0, min_kihs=2): """ Assembly containing only assigned regions (i.e. regions with contiguous KnobsIntoHoles. """ g = self.filter_graph(self.graph, cutoff=cutoff, min_kihs=min_kihs) ccs = sorted(networkx.connected_component_subgraphs(g, copy=Tr...
[ "def", "get_coiledcoil_region", "(", "self", ",", "cc_number", "=", "0", ",", "cutoff", "=", "7.0", ",", "min_kihs", "=", "2", ")", ":", "g", "=", "self", ".", "filter_graph", "(", "self", ".", "graph", ",", "cutoff", "=", "cutoff", ",", "min_kihs", ...
75.5
31.8
def _do_eval(self, cmd, args): """\ Evaluate python code. e <expr> Evaluate <expr>. """ code = args[0].lstrip() if not code: self.stderr.write('e: cannot evalutate empty expression\n') return try: eval(code) e...
[ "def", "_do_eval", "(", "self", ",", "cmd", ",", "args", ")", ":", "code", "=", "args", "[", "0", "]", ".", "lstrip", "(", ")", "if", "not", "code", ":", "self", ".", "stderr", ".", "write", "(", "'e: cannot evalutate empty expression\\n'", ")", "retur...
36
20.5
async def encoder_read(self, command): """ This is a polling method to read the last cached FirmataPlus encoder value. Normally not used. See encoder config for the asynchronous report message format. :param command: {"method": "encoder_read", "params": [PIN_A]} :returns: {"meth...
[ "async", "def", "encoder_read", "(", "self", ",", "command", ")", ":", "pin", "=", "int", "(", "command", "[", "0", "]", ")", "val", "=", "await", "self", ".", "core", ".", "encoder_read", "(", "pin", ")", "reply", "=", "json", ".", "dumps", "(", ...
48.583333
22.25
def slurp_properties(source, destination, ignore=[], srckeys=None): """Copy properties from *source* (assumed to be a module) to *destination* (assumed to be a dict). *ignore* lists properties that should not be thusly copied. *srckeys* is a list of keys to copy, if the source's __all__ is untrustw...
[ "def", "slurp_properties", "(", "source", ",", "destination", ",", "ignore", "=", "[", "]", ",", "srckeys", "=", "None", ")", ":", "if", "srckeys", "is", "None", ":", "srckeys", "=", "source", ".", "__all__", "destination", ".", "update", "(", "dict", ...
42.857143
17.214286
def make_cashed(self): """ Включает кэширование запросов к descend """ self._descendance_cash = [dict() for _ in self.graph] self.descend = self._descend_cashed
[ "def", "make_cashed", "(", "self", ")", ":", "self", ".", "_descendance_cash", "=", "[", "dict", "(", ")", "for", "_", "in", "self", ".", "graph", "]", "self", ".", "descend", "=", "self", ".", "_descend_cashed" ]
32.5
8.166667
def parse_event_out(self, node): """ Parses <EventOut> @param node: Node containing the <EventOut> element @type node: xml.etree.Element """ try: port = node.lattrib['port'] except: self.raise_error('<EventOut> must be specify a port.') ...
[ "def", "parse_event_out", "(", "self", ",", "node", ")", ":", "try", ":", "port", "=", "node", ".", "lattrib", "[", "'port'", "]", "except", ":", "self", ".", "raise_error", "(", "'<EventOut> must be specify a port.'", ")", "action", "=", "EventOut", "(", ...
24.4375
19.1875
def _load_wordlist(name, stream): """ Loads list of words or phrases from file. Returns "words" or "phrases" dictionary, the same as used in config. Raises Exception if file is missing or invalid. """ items = [] max_length = None multiword = False multiword_start = None number_o...
[ "def", "_load_wordlist", "(", "name", ",", "stream", ")", ":", "items", "=", "[", "]", "max_length", "=", "None", "multiword", "=", "False", "multiword_start", "=", "None", "number_of_words", "=", "None", "for", "i", ",", "line", "in", "enumerate", "(", ...
43.60274
18.890411
def split_crawl_tasks(tasks, concurrency): """ Reorganize tasks according to the tasks max concurrency value. :param tasks: sub-tasks to execute, can be either a list of tasks of a list of list of tasks :param int concurrency: Maximum number of tasks that might be executed in parallel. ...
[ "def", "split_crawl_tasks", "(", "tasks", ",", "concurrency", ")", ":", "if", "any", "(", "tasks", ")", "and", "isinstance", "(", "tasks", "[", "0", "]", ",", "list", ")", ":", "for", "seq", "in", "tasks", ":", "if", "not", "isinstance", "(", "seq", ...
29.931034
18.103448
def _other_dpss_method(N, NW, Kmax): """Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1] for a given frequency-spacing multiple NW and sequence length N. See dpss function that is the official version. This version is indepedant of the C code and relies on Scipy function. However,...
[ "def", "_other_dpss_method", "(", "N", ",", "NW", ",", "Kmax", ")", ":", "# here we want to set up an optimization problem to find a sequence", "# whose energy is maximally concentrated within band [-W,W].", "# Thus, the measure lambda(T,W) is the ratio between the energy within", "# that ...
43.366667
21.733333
def purge_all(user=None, fast=False): """ Remove all calculations of the given user """ user = user or getpass.getuser() if os.path.exists(datadir): if fast: shutil.rmtree(datadir) print('Removed %s' % datadir) else: for fname in os.listdir(datadir...
[ "def", "purge_all", "(", "user", "=", "None", ",", "fast", "=", "False", ")", ":", "user", "=", "user", "or", "getpass", ".", "getuser", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "datadir", ")", ":", "if", "fast", ":", "shutil", ".",...
32.8
7.733333
def convert_flatten(builder, layer, input_names, output_names, keras_layer): """ Convert a flatten layer from keras to coreml. ---------- Parameters keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, ou...
[ "def", "convert_flatten", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "# blob_order ==...
39.694444
22.75
def transform_audio(self, y): '''Compute the CQT Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape = (n_frames, n_bins) The CQT magnitude data['p...
[ "def", "transform_audio", "(", "self", ",", "y", ")", ":", "n_frames", "=", "self", ".", "n_frames", "(", "get_duration", "(", "y", "=", "y", ",", "sr", "=", "self", ".", "sr", ")", ")", "C", "=", "cqt", "(", "y", "=", "y", ",", "sr", "=", "s...
29
22.625
def extract_error_message(error): """ Extract a useful message from an error. Prefer the description attribute, then the message attribute, then the errors string conversion. In each case, fall back to the error class's name in the event that the attribute value was set to a uselessly empty string....
[ "def", "extract_error_message", "(", "error", ")", ":", "try", ":", "return", "error", ".", "description", "or", "error", ".", "__class__", ".", "__name__", "except", "AttributeError", ":", "try", ":", "return", "str", "(", "error", ".", "message", ")", "o...
36.1875
21.6875
def jid_to_time(jid): ''' Convert a salt job id into the time when the job was invoked ''' jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return '' year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] ...
[ "def", "jid_to_time", "(", "jid", ")", ":", "jid", "=", "six", ".", "text_type", "(", "jid", ")", "if", "len", "(", "jid", ")", "!=", "20", "and", "(", "len", "(", "jid", ")", "<=", "21", "or", "jid", "[", "20", "]", "!=", "'_'", ")", ":", ...
32.695652
20.695652
def send_setpoint(self, roll, pitch, yaw, thrust): """ Send a new control setpoint for roll/pitch/yaw/thrust to the copter The arguments roll/pitch/yaw/trust is the new setpoints that should be sent to the copter """ if thrust > 0xFFFF or thrust < 0: raise Va...
[ "def", "send_setpoint", "(", "self", ",", "roll", ",", "pitch", ",", "yaw", ",", "thrust", ")", ":", "if", "thrust", ">", "0xFFFF", "or", "thrust", "<", "0", ":", "raise", "ValueError", "(", "'Thrust must be between 0 and 0xFFFF'", ")", "if", "self", ".", ...
36.058824
19.941176
def main_cli(): """ Actualiza la base de datos de PVPC/DEMANDA almacenados como dataframe en local, creando una nueva si no existe o hubiere algún problema. Los datos registrados se guardan en HDF5 """ def _get_parser_args(): p = argparse.ArgumentParser(description='Gestor de DB de PVPC/D...
[ "def", "main_cli", "(", ")", ":", "def", "_get_parser_args", "(", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Gestor de DB de PVPC/DEMANDA (esios.ree.es)'", ")", "p", ".", "add_argument", "(", "'-d'", ",", "'--dem'", ",", ...
49.042254
25.43662
def get_entry_by_material_id(self, material_id, compatible_only=True, inc_structure=None, property_data=None, conventional_unit_cell=False): """ Get a ComputedEntry corresponding to a material_id. Args: material_id (s...
[ "def", "get_entry_by_material_id", "(", "self", ",", "material_id", ",", "compatible_only", "=", "True", ",", "inc_structure", "=", "None", ",", "property_data", "=", "None", ",", "conventional_unit_cell", "=", "False", ")", ":", "data", "=", "self", ".", "get...
51.411765
24.235294
def deconstruct(self): """Deconstruct operation.""" return ( self.__class__.__name__, [], { 'process': self.process, 'field': self._raw_field, 'schema': self.schema, 'default': self.default, }...
[ "def", "deconstruct", "(", "self", ")", ":", "return", "(", "self", ".", "__class__", ".", "__name__", ",", "[", "]", ",", "{", "'process'", ":", "self", ".", "process", ",", "'field'", ":", "self", ".", "_raw_field", ",", "'schema'", ":", "self", "....
26.583333
13.25
def stop_image_acquisition(self): """ Stops image acquisition. :return: None. """ if self.is_acquiring_images: # self._is_acquiring_images = False # if self.thread_image_acquisition.is_running: # TODO self.thread_...
[ "def", "stop_image_acquisition", "(", "self", ")", ":", "if", "self", ".", "is_acquiring_images", ":", "#", "self", ".", "_is_acquiring_images", "=", "False", "#", "if", "self", ".", "thread_image_acquisition", ".", "is_running", ":", "# TODO", "self", ".", "t...
32.327869
20.95082
def get_all_blockstack_ops_at( self, block_number, offset=None, count=None, include_history=None, restore_history=None ): """ Get all name, namespace, and account records affected at a particular block, in the state they were at the given block number. Paginate if offset, count ...
[ "def", "get_all_blockstack_ops_at", "(", "self", ",", "block_number", ",", "offset", "=", "None", ",", "count", "=", "None", ",", "include_history", "=", "None", ",", "restore_history", "=", "None", ")", ":", "if", "include_history", "is", "not", "None", ":"...
39.909091
25.818182
def process_bind_param(self, obj, dialect): """Get a flask_cloudy.Object and save it as a dict""" value = obj or {} if isinstance(obj, flask_cloudy.Object): value = {} for k in self.DEFAULT_KEYS: value[k] = getattr(obj, k) return super(self.__clas...
[ "def", "process_bind_param", "(", "self", ",", "obj", ",", "dialect", ")", ":", "value", "=", "obj", "or", "{", "}", "if", "isinstance", "(", "obj", ",", "flask_cloudy", ".", "Object", ")", ":", "value", "=", "{", "}", "for", "k", "in", "self", "."...
39.666667
13.777778
def color(self, key=None): """ Returns the color for this data set. :return <QColor> """ if key is not None: return self._colorMap.get(nativestring(key), self._color) return self._color
[ "def", "color", "(", "self", ",", "key", "=", "None", ")", ":", "if", "key", "is", "not", "None", ":", "return", "self", ".", "_colorMap", ".", "get", "(", "nativestring", "(", "key", ")", ",", "self", ".", "_color", ")", "return", "self", ".", "...
28.666667
12.888889
def deflections_from_grid(self, grid): """ Calculate the deflection angles at a given set of arc-second gridded coordinates. Parameters ---------- grid : grids.RegularGrid The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ ...
[ "def", "deflections_from_grid", "(", "self", ",", "grid", ")", ":", "eta", "=", "self", ".", "grid_to_grid_radii", "(", "grid", "=", "grid", ")", "deflection", "=", "np", ".", "multiply", "(", "2.", "*", "self", ".", "einstein_radius_rescaled", ",", "np", ...
50.142857
27.714286
def check_syntax(self, app_path=None): """Run syntax on each ".py" and ".json" file. Args: app_path (str, optional): Defaults to None. The path of Python files. """ app_path = app_path or '.' for filename in sorted(os.listdir(app_path)): error = None ...
[ "def", "check_syntax", "(", "self", ",", "app_path", "=", "None", ")", ":", "app_path", "=", "app_path", "or", "'.'", "for", "filename", "in", "sorted", "(", "os", ".", "listdir", "(", "app_path", ")", ")", ":", "error", "=", "None", "status", "=", "...
35.52381
16.761905
def default(self, obj): """Default object encoder function Args: obj (:obj:`Any`): Object to be serialized Returns: JSON string """ if isinstance(obj, datetime): return obj.isoformat() if issubclass(obj.__class__, Enum.__class__): ...
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ")", ":", "return", "obj", ".", "isoformat", "(", ")", "if", "issubclass", "(", "obj", ".", "__class__", ",", "Enum", ".", "__class__", ")", ":", ...
25.291667
19.25
def sphcyl(radius, colat, slon): """ This routine converts from spherical coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphcyl_c.html :param radius: Distance of point from origin. :type radius: float :param colat: Polar angle (co-latitude i...
[ "def", "sphcyl", "(", "radius", ",", "colat", ",", "slon", ")", ":", "radius", "=", "ctypes", ".", "c_double", "(", "radius", ")", "colat", "=", "ctypes", ".", "c_double", "(", "colat", ")", "slon", "=", "ctypes", ".", "c_double", "(", "slon", ")", ...
33.678571
16.178571
def manage_delObjects(self, ids=None, REQUEST=None): """Overrides parent function. If the ids passed in are from Attachment types, the function ignores the DeleteObjects permission. For the rest of types, it works as usual (checks the permission) """ if ids is None: i...
[ "def", "manage_delObjects", "(", "self", ",", "ids", "=", "None", ",", "REQUEST", "=", "None", ")", ":", "if", "ids", "is", "None", ":", "ids", "=", "[", "]", "if", "isinstance", "(", "ids", ",", "basestring", ")", ":", "ids", "=", "[", "ids", "]...
42.578947
16.631579
def countdown(template, duration=datetime.timedelta(seconds=5)): """ Do a countdown for duration, printing the template (which may accept one positional argument). Template should be something like ``countdown complete in {} seconds.`` """ now = datetime.datetime.now() deadline = now + duration remaining = dead...
[ "def", "countdown", "(", "template", ",", "duration", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "5", ")", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "deadline", "=", "now", "+", "duration", "remaining", "=", ...
32.789474
14.789474
def sync_networks(self): """sync networks. It will retrieve networks from neutron and populate them in dfa database and dcnm """ nets = self.neutronclient.list_networks() for net in nets.get("networks"): LOG.info("Syncing network %s", net["id"]) s...
[ "def", "sync_networks", "(", "self", ")", ":", "nets", "=", "self", ".", "neutronclient", ".", "list_networks", "(", ")", "for", "net", "in", "nets", ".", "get", "(", "\"networks\"", ")", ":", "LOG", ".", "info", "(", "\"Syncing network %s\"", ",", "net"...
37.714286
9.571429
async def RemoteApplicationInfo(self, offer_urls): ''' offer_urls : typing.Sequence[str] Returns -> typing.Sequence[~RemoteApplicationInfoResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='ApplicationOffers', request='Rem...
[ "async", "def", "RemoteApplicationInfo", "(", "self", ",", "offer_urls", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'ApplicationOffers'", ",", "request", "=", "'RemoteApplicationInfo'", ",", ...
35.142857
12.285714
def library_directories(self): """Return a list of directories containing any static libraries built by this IOTile.""" libs = self.find_products('library') if len(libs) > 0: return [os.path.join(self.output_folder)] return []
[ "def", "library_directories", "(", "self", ")", ":", "libs", "=", "self", ".", "find_products", "(", "'library'", ")", "if", "len", "(", "libs", ")", ">", "0", ":", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "output_folder", ")"...
29.444444
20.555556
def import_experience(self, states, internals, actions, terminal, reward): """ Stores experiences. """ fetches = self.import_experience_output feed_dict = self.get_feed_dict( states=states, internals=internals, actions=actions, ter...
[ "def", "import_experience", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ")", ":", "fetches", "=", "self", ".", "import_experience_output", "feed_dict", "=", "self", ".", "get_feed_dict", "(", "states", "=", "...
28.733333
17.133333
def parse(self, text, as_html=True): """ Get entity value with markup :param text: original text :param as_html: as html? :return: entity text with markup """ if not text: return text entity_text = self.get_text(text) if self.type == ...
[ "def", "parse", "(", "self", ",", "text", ",", "as_html", "=", "True", ")", ":", "if", "not", "text", ":", "return", "text", "entity_text", "=", "self", ".", "get_text", "(", "text", ")", "if", "self", ".", "type", "==", "MessageEntityType", ".", "BO...
38.128205
12.692308
def find_mismatch(first, second, indent=''): """ Finds where two objects differ, iterating down into nested containers (i.e. dicts, lists and tuples) They can be nested containers any combination of primary dtypes, str, int, float, dict and lists Parameters ---------- first : dict | list | ...
[ "def", "find_mismatch", "(", "first", ",", "second", ",", "indent", "=", "''", ")", ":", "# Basic case where we are dealing with non-containers", "if", "not", "(", "isinstance", "(", "first", ",", "type", "(", "second", ")", ")", "or", "isinstance", "(", "seco...
41.75
19.285714
def league_header(self, league): """Prints the league header""" league_name = " {0} ".format(league) click.secho("{:=^62}".format(league_name), fg=self.colors.MISC) click.echo()
[ "def", "league_header", "(", "self", ",", "league", ")", ":", "league_name", "=", "\" {0} \"", ".", "format", "(", "league", ")", "click", ".", "secho", "(", "\"{:=^62}\"", ".", "format", "(", "league_name", ")", ",", "fg", "=", "self", ".", "colors", ...
41
12.6
def _classify_target_compile_workflow(self, target): """Return the compile workflow to use for this target.""" if target.has_sources('.java') or target.has_sources('.scala'): return self.get_scalar_mirrored_target_option('workflow', target) return None
[ "def", "_classify_target_compile_workflow", "(", "self", ",", "target", ")", ":", "if", "target", ".", "has_sources", "(", "'.java'", ")", "or", "target", ".", "has_sources", "(", "'.scala'", ")", ":", "return", "self", ".", "get_scalar_mirrored_target_option", ...
53.2
19
def build_gui(self, container): """Build GUI such that image list area is maximized.""" vbox, sw, orientation = Widgets.get_oriented_box(container) captions = (('Channel:', 'label', 'Channel Name', 'combobox', 'Modified only', 'checkbutton'), ) w, b = Widgets.build...
[ "def", "build_gui", "(", "self", ",", "container", ")", ":", "vbox", ",", "sw", ",", "orientation", "=", "Widgets", ".", "get_oriented_box", "(", "container", ")", "captions", "=", "(", "(", "'Channel:'", ",", "'label'", ",", "'Channel Name'", ",", "'combo...
39.1
21.1375
def printConcordance(concordance, prefix, tped, snps): """Print the concordance. :param concordance: the concordance. :param prefix: the prefix if the output files. :param tped: a representation of the ``tped`` of duplicated markers. :param snps: the position of the duplicated markers in the ``tped...
[ "def", "printConcordance", "(", "concordance", ",", "prefix", ",", "tped", ",", "snps", ")", ":", "outFile", "=", "None", "try", ":", "outFile", "=", "open", "(", "prefix", "+", "\".concordance\"", ",", "\"w\"", ")", "except", "IOError", ":", "msg", "=",...
35.142857
22.904762
def dns_name(self): """Get the DNS name for this machine. This is a best guess based on the addresses available in current data. May return None if no suitable address is found. """ for scope in ['public', 'local-cloud']: addresses = self.safe_data['addresses'] or []...
[ "def", "dns_name", "(", "self", ")", ":", "for", "scope", "in", "[", "'public'", ",", "'local-cloud'", "]", ":", "addresses", "=", "self", ".", "safe_data", "[", "'addresses'", "]", "or", "[", "]", "addresses", "=", "[", "address", "for", "address", "i...
39.384615
13.538462
def save(self, directory=None, append_timestep=True): """ Save TensorFlow model. If no checkpoint directory is given, the model's default saver directory is used. Optionally appends current timestep to prevent overwriting previous checkpoint files. Turn off to be able to load model from ...
[ "def", "save", "(", "self", ",", "directory", "=", "None", ",", "append_timestep", "=", "True", ")", ":", "if", "self", ".", "flush_summarizer", "is", "not", "None", ":", "self", ".", "monitored_session", ".", "run", "(", "fetches", "=", "self", ".", "...
42.538462
25
def populate_development(version): """Populates ``DEVELOPMENT.rst`` with release-specific data. This is because ``DEVELOPMENT.rst`` is used in the Sphinx documentation. Args: version (str): The current version. """ with open(DEVELOPMENT_TEMPLATE, "r") as file_obj: template = file_o...
[ "def", "populate_development", "(", "version", ")", ":", "with", "open", "(", "DEVELOPMENT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "contents", "=", "template", ".", "format", "(", "revision", ...
36.153846
17
def get_repo(self, name): """ :calls: `GET /repos/:owner/:repo <http://developer.github.com/v3/repos>`_ :param name: string :rtype: :class:`github.Repository.Repository` """ assert isinstance(name, (str, unicode)), name headers, data = self._requester.requestJsonA...
[ "def", "get_repo", "(", "self", ",", "name", ")", ":", "assert", "isinstance", "(", "name", ",", "(", "str", ",", "unicode", ")", ")", ",", "name", "headers", ",", "data", "=", "self", ".", "_requester", ".", "requestJsonAndCheck", "(", "\"GET\"", ",",...
40.5
18.833333
def auto_find_instance_path(self): """Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named ``instance`` next to your main file or the package. .. versionadded:: 0.8 "...
[ "def", "auto_find_instance_path", "(", "self", ")", ":", "prefix", ",", "package_path", "=", "find_package", "(", "self", ".", "import_name", ")", "if", "prefix", "is", "None", ":", "return", "os", ".", "path", ".", "join", "(", "package_path", ",", "'inst...
43.833333
18.583333
def _imread(self, file): """Proxy to skimage.io.imread with some fixes.""" # For now, we have to select the imageio plugin to read image from byte stream # When ski-image v0.15 is released, imageio will be the default plugin, so this # code can be simplified at that time. See issue repo...
[ "def", "_imread", "(", "self", ",", "file", ")", ":", "# For now, we have to select the imageio plugin to read image from byte stream", "# When ski-image v0.15 is released, imageio will be the default plugin, so this", "# code can be simplified at that time. See issue report and pull request:",...
63.166667
28.083333
def lag_matrix(blk, max_lag=None): """ Finds the lag matrix for a given 1-D block sequence. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! max_lag : The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``, the...
[ "def", "lag_matrix", "(", "blk", ",", "max_lag", "=", "None", ")", ":", "if", "max_lag", "is", "None", ":", "max_lag", "=", "len", "(", "blk", ")", "-", "1", "elif", "max_lag", ">=", "len", "(", "blk", ")", ":", "raise", "ValueError", "(", "\"Block...
30.785714
24.285714
def _recv(self, rm_colon=False, blocking=True, expected_replies=None, default_rvalue=[''], ignore_unexpected_replies=True, rm_first=True, recur_limit=10): """ Receives and processes an IRC protocol message. Optional arguments: * rm_colon=False - If True: ...
[ "def", "_recv", "(", "self", ",", "rm_colon", "=", "False", ",", "blocking", "=", "True", ",", "expected_replies", "=", "None", ",", "default_rvalue", "=", "[", "''", "]", ",", "ignore_unexpected_replies", "=", "True", ",", "rm_first", "=", "True", ",", ...
40.164179
15.38806
def run_helper_process(python_file, metadata_queue, quit_event, options): """ :param python_file: The absolute path of a python file containing the helper process that should be run. It must define a class which is a subclass of BotHelperProcess. :param metadata_queue: A queue from which the helper proc...
[ "def", "run_helper_process", "(", "python_file", ",", "metadata_queue", ",", "quit_event", ",", "options", ")", ":", "class_wrapper", "=", "import_class_with_base", "(", "python_file", ",", "BotHelperProcess", ")", "helper_class", "=", "class_wrapper", ".", "get_loade...
61.916667
31.083333
def get_init_container(self, init_command, init_args, env_vars, context_mounts, persistence_outputs, persistence_data): """Pod init container for sett...
[ "def", "get_init_container", "(", "self", ",", "init_command", ",", "init_args", ",", "env_vars", ",", "context_mounts", ",", "persistence_outputs", ",", "persistence_data", ")", ":", "env_vars", "=", "to_list", "(", "env_vars", ",", "check_none", "=", "True", "...
48.857143
12.071429
def _is_raising(body: typing.List) -> bool: """Return true if the given statement node raise an exception""" for node in body: if isinstance(node, astroid.Raise): return True return False
[ "def", "_is_raising", "(", "body", ":", "typing", ".", "List", ")", "->", "bool", ":", "for", "node", "in", "body", ":", "if", "isinstance", "(", "node", ",", "astroid", ".", "Raise", ")", ":", "return", "True", "return", "False" ]
35.666667
11
def examples(directory): """ Generate example strategies to target folder """ source_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "examples") try: shutil.copytree(source_dir, os.path.join(directory, "examples")) except OSError as e: if e.errno == errno.EEXIST:...
[ "def", "examples", "(", "directory", ")", ":", "source_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "\"examples\"", ")", "try", ":", "shu...
33
18.818182
def update_to_v24(self): """Convert older tags into an ID3v2.4 tag. This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to TDRC). If you intend to save tags, you must call this function at some point; it is called by default when loading the tag. """ self.__update_...
[ "def", "update_to_v24", "(", "self", ")", ":", "self", ".", "__update_common", "(", ")", "# TDAT, TYER, and TIME have been turned into TDRC.", "try", ":", "date", "=", "text_type", "(", "self", ".", "get", "(", "\"TYER\"", ",", "\"\"", ")", ")", "if", "date", ...
36.696429
15.928571
def is_attribute_applicable_to_object_type(self, attribute, object_type): """ Check if the attribute is supported by the given object type. Args: attribute (string): The name of the attribute (e.g., 'Name'). Required. object_type (ObjectType): An ObjectTy...
[ "def", "is_attribute_applicable_to_object_type", "(", "self", ",", "attribute", ",", "object_type", ")", ":", "# TODO (peterhamilton) Handle applicability between certificate types", "rule_set", "=", "self", ".", "_attribute_rule_sets", ".", "get", "(", "attribute", ")", "i...
40.684211
22.052632
def add_to_toolbar(self, toolbar, widget): """Add widget actions to toolbar""" actions = widget.toolbar_actions if actions is not None: add_actions(toolbar, actions)
[ "def", "add_to_toolbar", "(", "self", ",", "toolbar", ",", "widget", ")", ":", "actions", "=", "widget", ".", "toolbar_actions", "if", "actions", "is", "not", "None", ":", "add_actions", "(", "toolbar", ",", "actions", ")" ]
40.2
2.6
def calc_stress_tf(self, lin, lout, damped): """Compute the stress transfer function. Parameters ---------- lin : :class:`~site.Location` Location of input lout : :class:`~site.Location` Location of output. Note that this would typically be midheight ...
[ "def", "calc_stress_tf", "(", "self", ",", "lin", ",", "lout", ",", "damped", ")", ":", "tf", "=", "self", ".", "calc_strain_tf", "(", "lin", ",", "lout", ")", "if", "damped", ":", "# Scale by complex shear modulus to include the influence of", "# damping", "tf"...
28.952381
17.380952
def ParseMultiple(self, result_dicts): """Parse the WMI Win32_UserAccount output.""" for result_dict in result_dicts: kb_user = rdf_client.User() for wmi_key, kb_key in iteritems(self.account_mapping): try: kb_user.Set(kb_key, result_dict[wmi_key]) except KeyError: ...
[ "def", "ParseMultiple", "(", "self", ",", "result_dicts", ")", ":", "for", "result_dict", "in", "result_dicts", ":", "kb_user", "=", "rdf_client", ".", "User", "(", ")", "for", "wmi_key", ",", "kb_key", "in", "iteritems", "(", "self", ".", "account_mapping",...
42.733333
17.2
def analyze(output_dir, dataset, cloud=False, project_id=None): """Blocking version of analyze_async. See documentation of analyze_async.""" job = analyze_async( output_dir=output_dir, dataset=dataset, cloud=cloud, project_id=project_id) job.wait() print('Analyze: ' + str(job.state))
[ "def", "analyze", "(", "output_dir", ",", "dataset", ",", "cloud", "=", "False", ",", "project_id", "=", "None", ")", ":", "job", "=", "analyze_async", "(", "output_dir", "=", "output_dir", ",", "dataset", "=", "dataset", ",", "cloud", "=", "cloud", ",",...
34.222222
15.111111
def _index(self, refresh_time=None): """Bottle callback for index.html (/) file.""" if refresh_time is None or refresh_time < 1: refresh_time = self.args.time # Update the stat self.__update__() # Display return template("index.html", refresh_time=refresh_t...
[ "def", "_index", "(", "self", ",", "refresh_time", "=", "None", ")", ":", "if", "refresh_time", "is", "None", "or", "refresh_time", "<", "1", ":", "refresh_time", "=", "self", ".", "args", ".", "time", "# Update the stat", "self", ".", "__update__", "(", ...
28.545455
19.454545
def repeat(self, target, sender, **kwargs): "will repeat whatever yo say" if target.startswith("#"): self.message(target, kwargs["msg"]) else: self.message(sender, kwargs["msg"])
[ "def", "repeat", "(", "self", ",", "target", ",", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "target", ".", "startswith", "(", "\"#\"", ")", ":", "self", ".", "message", "(", "target", ",", "kwargs", "[", "\"msg\"", "]", ")", "else", ":", ...
36.833333
8.833333
def send_results(self): ''' send results ''' for server in self.servers: if self.servers[server]['results']: if len(self.servers[server]['results']) == 1: msg = MIMEText('') msg['Subject'] = '[%(custom_fqdn)s] [%(servic...
[ "def", "send_results", "(", "self", ")", ":", "for", "server", "in", "self", ".", "servers", ":", "if", "self", ".", "servers", "[", "server", "]", "[", "'results'", "]", ":", "if", "len", "(", "self", ".", "servers", "[", "server", "]", "[", "'res...
55.529412
31.941176
def convert_type(self, type): """Convert type to SQL """ # Default dialect mapping = { 'any': sa.Text, 'array': None, 'boolean': sa.Boolean, 'date': sa.Date, 'datetime': sa.DateTime, 'duration': None, 'g...
[ "def", "convert_type", "(", "self", ",", "type", ")", ":", "# Default dialect", "mapping", "=", "{", "'any'", ":", "sa", ".", "Text", ",", "'array'", ":", "None", ",", "'boolean'", ":", "sa", ".", "Boolean", ",", "'date'", ":", "sa", ".", "Date", ","...
27.052632
14.394737
def set_plot_CC_T_rho_new(self,fig='CC evol',linestyle=['-'],burn_limit=0.997,color=['r'],marker=['o'],markevery=500): ''' Plots end_model - array, control how far in models a run is plottet, if -1 till end symbs_1 - set symbols of runs ''' if len(linestyle)==0: linestyle=200*['-'] plt.figure(fig...
[ "def", "set_plot_CC_T_rho_new", "(", "self", ",", "fig", "=", "'CC evol'", ",", "linestyle", "=", "[", "'-'", "]", ",", "burn_limit", "=", "0.997", ",", "color", "=", "[", "'r'", "]", ",", "marker", "=", "[", "'o'", "]", ",", "markevery", "=", "500",...
38.62069
20.781609
def getchar(echo=False): """Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason ...
[ "def", "getchar", "(", "echo", "=", "False", ")", ":", "f", "=", "_getchar", "if", "f", "is", "None", ":", "from", ".", "_termui_impl", "import", "getchar", "as", "f", "return", "f", "(", "echo", ")" ]
42.291667
24.208333
def create_event_handler(event_type, handler): """Register a comm and return a serializable object with target name""" target_name = '{hash}_{event_type}'.format(hash=hash(handler), event_type=event_type) def handle_comm_opened(comm, msg): @comm.on_msg def _handle_msg(msg): dat...
[ "def", "create_event_handler", "(", "event_type", ",", "handler", ")", ":", "target_name", "=", "'{hash}_{event_type}'", ".", "format", "(", "hash", "=", "hash", "(", "handler", ")", ",", "event_type", "=", "event_type", ")", "def", "handle_comm_opened", "(", ...
36.090909
21.318182
def set(self, key, value, expires=None, future=None): """Set a value """ # assert the values above with self._lock: try: self._dict[key].set(value, expires=expires, future=future) except KeyError: self._dict[key] = moment(value, exp...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "expires", "=", "None", ",", "future", "=", "None", ")", ":", "# assert the values above", "with", "self", ".", "_lock", ":", "try", ":", "self", ".", "_dict", "[", "key", "]", ".", "set", "...
38.1
17.8
def xmlGenBinaryDataArrayList(binaryDataInfo, binaryDataDict, compression='zlib', arrayTypes=None): """ #TODO: docstring :params binaryDataInfo: #TODO: docstring :params binaryDataDict: #TODO: docstring :params compression: #TODO: docstring :params arrayTypes: #TODO: d...
[ "def", "xmlGenBinaryDataArrayList", "(", "binaryDataInfo", ",", "binaryDataDict", ",", "compression", "=", "'zlib'", ",", "arrayTypes", "=", "None", ")", ":", "#Note: any other value for \"compression\" than \"zlib\" results in no", "# compression", "#Note: Use arrayTypes param...
43.8
17.784615
def dir(): """Return the list of patched function names. Used for patching functions imported from the module. """ dir = [ 'abspath', 'dirname', 'exists', 'expanduser', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink'...
[ "def", "dir", "(", ")", ":", "dir", "=", "[", "'abspath'", ",", "'dirname'", ",", "'exists'", ",", "'expanduser'", ",", "'getatime'", ",", "'getctime'", ",", "'getmtime'", ",", "'getsize'", ",", "'isabs'", ",", "'isdir'", ",", "'isfile'", ",", "'islink'", ...
38.8
18.133333
def create(self, **fields): """Create and return a new record in associated app and return the newly created Record instance Args: **fields: Field names and values to be validated and sent to server with create request Notes: Keyword arguments should be field names with...
[ "def", "create", "(", "self", ",", "*", "*", "fields", ")", ":", "new_record", "=", "record_factory", "(", "self", ".", "_app", ",", "fields", ")", "new_record", ".", "save", "(", ")", "return", "new_record" ]
31.136364
27.840909
def compute_edges(edges): """ Computes edges as midpoints of the bin centers. The first and last boundaries are equidistant from the first and last midpoints respectively. """ edges = np.asarray(edges) if edges.dtype.kind == 'i': edges = edges.astype('f') midpoints = (edges[:-1]...
[ "def", "compute_edges", "(", "edges", ")", ":", "edges", "=", "np", ".", "asarray", "(", "edges", ")", "if", "edges", ".", "dtype", ".", "kind", "==", "'i'", ":", "edges", "=", "edges", ".", "astype", "(", "'f'", ")", "midpoints", "=", "(", "edges"...
39.333333
15.666667
def DeserializeUnsigned(self, reader): """ Deserialize object. Args: reader (neo.IO.BinaryReader): Raises: Exception: if transaction type is incorrect. """ txtype = reader.ReadByte() if txtype != int.from_bytes(self.Type, 'little'): ...
[ "def", "DeserializeUnsigned", "(", "self", ",", "reader", ")", ":", "txtype", "=", "reader", ".", "ReadByte", "(", ")", "if", "txtype", "!=", "int", ".", "from_bytes", "(", "self", ".", "Type", ",", "'little'", ")", ":", "raise", "Exception", "(", "'in...
33.214286
19.214286
def parse(self, source: str=None, entry: str=None) -> parsing.Node: """Parse source using the grammar""" self.from_string = True if source is not None: self.parsed_stream(source) if entry is None: entry = self.entry if entry is None: raise Valu...
[ "def", "parse", "(", "self", ",", "source", ":", "str", "=", "None", ",", "entry", ":", "str", "=", "None", ")", "->", "parsing", ".", "Node", ":", "self", ".", "from_string", "=", "True", "if", "source", "is", "not", "None", ":", "self", ".", "p...
39.909091
11.363636
def qaoa_ansatz(gammas, betas): """ Function that returns a QAOA ansatz program for a list of angles betas and gammas. len(betas) == len(gammas) == P for a QAOA program of order P. :param list(float) gammas: Angles over which to parameterize the cost Hamiltonian. :param list(float) betas: Angles ov...
[ "def", "qaoa_ansatz", "(", "gammas", ",", "betas", ")", ":", "return", "Program", "(", "[", "exponentiate_commuting_pauli_sum", "(", "h_cost", ")", "(", "g", ")", "+", "exponentiate_commuting_pauli_sum", "(", "h_driver", ")", "(", "b", ")", "for", "g", ",", ...
46.769231
22.923077
def reflect_runtime_member(self, name): """Reflect 'name' using ONLY runtime reflection. You most likely want to use ScopeStack.reflect instead. Returns: Type of 'name', or protocol.AnyType. """ for scope in reversed(self.scopes): try: re...
[ "def", "reflect_runtime_member", "(", "self", ",", "name", ")", ":", "for", "scope", "in", "reversed", "(", "self", ".", "scopes", ")", ":", "try", ":", "return", "structured", ".", "reflect_runtime_member", "(", "scope", ",", "name", ")", "except", "(", ...
32.2
18.933333
def writeRoot(self, root): """ Strategy is: - write header - wrap root object so everything is hashable - compute size of objects which will be written - need to do this in order to know how large the object refs will be in the list/dict/set reference lists ...
[ "def", "writeRoot", "(", "self", ",", "root", ")", ":", "output", "=", "self", ".", "header", "wrapped_root", "=", "self", ".", "wrapRoot", "(", "root", ")", "self", ".", "computeOffsets", "(", "wrapped_root", ",", "asReference", "=", "True", ",", "isRoo...
43.628571
16.771429
def python_executable_changed(self, pyexec): """Custom Python executable value has been changed""" if not self.cus_exec_radio.isChecked(): return False def_pyexec = get_python_executable() if not is_text_string(pyexec): pyexec = to_text_string(pyexec.toUtf8(...
[ "def", "python_executable_changed", "(", "self", ",", "pyexec", ")", ":", "if", "not", "self", ".", "cus_exec_radio", ".", "isChecked", "(", ")", ":", "return", "False", "def_pyexec", "=", "get_python_executable", "(", ")", "if", "not", "is_text_string", "(", ...
48.777778
15.777778
def attachIterator(self, login, tableName, setting, scopes): """ Parameters: - login - tableName - setting - scopes """ self.send_attachIterator(login, tableName, setting, scopes) self.recv_attachIterator()
[ "def", "attachIterator", "(", "self", ",", "login", ",", "tableName", ",", "setting", ",", "scopes", ")", ":", "self", ".", "send_attachIterator", "(", "login", ",", "tableName", ",", "setting", ",", "scopes", ")", "self", ".", "recv_attachIterator", "(", ...
23.7
18.3
def _kaiser(n, beta): """Independant Kaiser window For the definition of the Kaiser window, see A. V. Oppenheim & R. W. Schafer, "Discrete-Time Signal Processing". The continuous version of width n centered about x=0 is: .. note:: 2 times slower than scipy.kaiser """ from scipy.special import...
[ "def", "_kaiser", "(", "n", ",", "beta", ")", ":", "from", "scipy", ".", "special", "import", "iv", "as", "besselI", "m", "=", "n", "-", "1", "k", "=", "arange", "(", "0", ",", "m", ")", "k", "=", "2.", "*", "beta", "/", "m", "*", "sqrt", "...
30.266667
21.533333
def addPattern(self, word, vector): """ Adds a pattern with key word. Example: net.addPattern("tom", [0, 0, 0, 1]) """ if word in self.patterns: raise NetworkError('Pattern key already in use. Call delPattern to free key.', word) else: se...
[ "def", "addPattern", "(", "self", ",", "word", ",", "vector", ")", ":", "if", "word", "in", "self", ".", "patterns", ":", "raise", "NetworkError", "(", "'Pattern key already in use. Call delPattern to free key.'", ",", "word", ")", "else", ":", "self", ".", "p...
30.545455
16.545455
def get_packages(self, feed_id, protocol_type=None, package_name_query=None, normalized_package_name=None, include_urls=None, include_all_versions=None, is_listed=None, get_top_package_versions=None, is_release=None, include_description=None, top=None, skip=None, include_deleted=None, is_cached=None, direct_upstream_id...
[ "def", "get_packages", "(", "self", ",", "feed_id", ",", "protocol_type", "=", "None", ",", "package_name_query", "=", "None", ",", "normalized_package_name", "=", "None", ",", "include_urls", "=", "None", ",", "include_all_versions", "=", "None", ",", "is_liste...
89.5
53.844828
def get_multiplicon_seeds(self, redundant=False): """ Return a generator of the IDs of multiplicons that are initial seeding 'pairs' in level 2 multiplicons. Arguments: o redundant - if true, report redundant multiplicons """ for node in self._multiplicon_gr...
[ "def", "get_multiplicon_seeds", "(", "self", ",", "redundant", "=", "False", ")", ":", "for", "node", "in", "self", ".", "_multiplicon_graph", ".", "nodes", "(", ")", ":", "if", "not", "len", "(", "self", ".", "_multiplicon_graph", ".", "in_edges", "(", ...
34.833333
16.444444
def get_node(self): """return etree Element representing this slide""" # already added title, text frames # add animation chunks if self.animations: anim_par = el("anim:par", attrib={"presentation:node-type": "timing-root"}) self._page.append(anim_par) ...
[ "def", "get_node", "(", "self", ")", ":", "# already added title, text frames", "# add animation chunks", "if", "self", ".", "animations", ":", "anim_par", "=", "el", "(", "\"anim:par\"", ",", "attrib", "=", "{", "\"presentation:node-type\"", ":", "\"timing-root\"", ...
39.714286
15.714286
def find(self, spec=None, fields=None, skip=0, limit=0, timeout=True, snapshot=False, tailable=False, sort=None, max_scan=None, slave_okay=False, _must_use_master=False, _is_command=False, hint=None, debug=False, comment=None, callback=None): "...
[ "def", "find", "(", "self", ",", "spec", "=", "None", ",", "fields", "=", "None", ",", "skip", "=", "0", ",", "limit", "=", "0", ",", "timeout", "=", "True", ",", "snapshot", "=", "False", ",", "tailable", "=", "False", ",", "sort", "=", "None", ...
44.625
19.023438
def p_ex_list_item_id(self, p): 'ex_list_item : ID' p[0] = AstExampleRef(self.path, p.lineno(1), p.lexpos(1), p[1])
[ "def", "p_ex_list_item_id", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "AstExampleRef", "(", "self", ".", "path", ",", "p", ".", "lineno", "(", "1", ")", ",", "p", ".", "lexpos", "(", "1", ")", ",", "p", "[", "1", "]", ")" ]
43
17.666667
def verify_path(self, mold_id_path): """ Lookup and verify path. """ try: path = self.lookup_path(mold_id_path) if not exists(path): raise KeyError except KeyError: raise_os_error(ENOENT) return path
[ "def", "verify_path", "(", "self", ",", "mold_id_path", ")", ":", "try", ":", "path", "=", "self", ".", "lookup_path", "(", "mold_id_path", ")", "if", "not", "exists", "(", "path", ")", ":", "raise", "KeyError", "except", "KeyError", ":", "raise_os_error",...
24.083333
12.583333
def file_strip_ext( afile, skip_version=False, only_known_extensions=False, allow_subformat=True): """ Strip in the best way the extension from a filename. >>> file_strip_ext("foo.tar.gz") 'foo' >>> file_strip_ext("foo.buz.gz") 'foo.buz' >>> file_strip_ext("f...
[ "def", "file_strip_ext", "(", "afile", ",", "skip_version", "=", "False", ",", "only_known_extensions", "=", "False", ",", "allow_subformat", "=", "True", ")", ":", "import", "os", "afile", "=", "afile", ".", "split", "(", "';'", ")", "if", "len", "(", "...
33.153846
17.038462
def fromkeys(cls, keys, value=None, names=None): ''' Create a new dictionary with keys from ``keys`` and values set to ``value``. fromkeys() is a class method that returns a new dictionary. ``value`` defaults to None. Length of ``keys`` must not exceed one because no duplicate values a...
[ "def", "fromkeys", "(", "cls", ",", "keys", ",", "value", "=", "None", ",", "names", "=", "None", ")", ":", "N", "=", "len", "(", "keys", ")", "if", "N", ">", "1", ":", "raise", "ValueError", "(", "'Length of keys (%s) must not exceed one because '", "'n...
42.5
31
def group_callback(self, iocb): """Callback when a child iocb completes.""" if _debug: IOGroup._debug("group_callback %r", iocb) # check all the members for iocb in self.ioMembers: if not iocb.ioComplete.isSet(): if _debug: IOGroup._debug(" - waiting for c...
[ "def", "group_callback", "(", "self", ",", "iocb", ")", ":", "if", "_debug", ":", "IOGroup", ".", "_debug", "(", "\"group_callback %r\"", ",", "iocb", ")", "# check all the members", "for", "iocb", "in", "self", ".", "ioMembers", ":", "if", "not", "iocb", ...
37.571429
15.928571
async def deleteallreactions(self, ctx): """Removes a reaction""" data = self.config.get(ctx.message.server.id, {}) if data: await self.config.put(ctx.message.server.id, {}) await self.bot.responses.success(message="All reactions have been deleted.") else: ...
[ "async", "def", "deleteallreactions", "(", "self", ",", "ctx", ")", ":", "data", "=", "self", ".", "config", ".", "get", "(", "ctx", ".", "message", ".", "server", ".", "id", ",", "{", "}", ")", "if", "data", ":", "await", "self", ".", "config", ...
48.875
22.625
def get_location(self, location): """ For an index location return a dict of the index and value. This is optimized for speed because it does not need to lookup the index location with a search. Also can accept relative indexing from the end of the SEries in standard python notation [-3,...
[ "def", "get_location", "(", "self", ",", "location", ")", ":", "return", "{", "self", ".", "index_name", ":", "self", ".", "_index", "[", "location", "]", ",", "self", ".", "data_name", ":", "self", ".", "_data", "[", "location", "]", "}" ]
54.9
32.7
def logSystemInfo(self): """ A function to be called just after a logging object is instantiated to load the log up with info about the computer it is being ran on and the software version. This function utilizes the psutil and platform libraries, so they must be install for...
[ "def", "logSystemInfo", "(", "self", ")", ":", "t", "=", "datetime", ".", "date", ".", "today", "(", ")", "infoStr", "=", "'Date KMlogger object instantiated: '", "+", "t", ".", "strftime", "(", "'%b %d, %Y'", ")", "+", "'\\n\\n'", "infoStr", "+=", "\"\\n\""...
47.405405
20.297297
async def write(self, data): """ This method writes sends data to the IP device :param data: :return: None """ self.writer.write((bytes([ord(data)]))) await self.writer.drain()
[ "async", "def", "write", "(", "self", ",", "data", ")", ":", "self", ".", "writer", ".", "write", "(", "(", "bytes", "(", "[", "ord", "(", "data", ")", "]", ")", ")", ")", "await", "self", ".", "writer", ".", "drain", "(", ")" ]
25
13.222222
def idle_task(self): '''called on idle''' if self.module('console') is not None and not self.menu_added_console: self.menu_added_console = True self.module('console').add_menu(self.menu) if self.module('map') is not None and not self.menu_added_map: self.menu_...
[ "def", "idle_task", "(", "self", ")", ":", "if", "self", ".", "module", "(", "'console'", ")", "is", "not", "None", "and", "not", "self", ".", "menu_added_console", ":", "self", ".", "menu_added_console", "=", "True", "self", ".", "module", "(", "'consol...
47.5
16
def _win32_dir(path, star=''): """ Using the windows cmd shell to get information about a directory """ from ubelt import util_cmd import re wrapper = 'cmd /S /C "{}"' # the /S will preserve all inner quotes command = 'dir /-C "{}"{}'.format(path, star) wrapped = wrapper.format(command)...
[ "def", "_win32_dir", "(", "path", ",", "star", "=", "''", ")", ":", "from", "ubelt", "import", "util_cmd", "import", "re", "wrapper", "=", "'cmd /S /C \"{}\"'", "# the /S will preserve all inner quotes", "command", "=", "'dir /-C \"{}\"{}'", ".", "format", "(", "p...
38.135135
11.648649
def in6_addrtovendor(addr): """ Extract the MAC address from a modified EUI-64 constructed IPv6 address provided and use the IANA oui.txt file to get the vendor. The database used for the conversion is the one loaded by Scapy from a Wireshark installation if discovered in a well-known location. ...
[ "def", "in6_addrtovendor", "(", "addr", ")", ":", "mac", "=", "in6_addrtomac", "(", "addr", ")", "if", "mac", "is", "None", "or", "conf", ".", "manufdb", "is", "None", ":", "return", "None", "res", "=", "conf", ".", "manufdb", ".", "_get_manuf", "(", ...
34.833333
20.5
def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]: """ Return the next row from a cursor as an :class:`OrderedDict`, or ``None``. """ columns = get_fieldnames_from_cursor(cursor) row = cursor.fetchone() if not row: return None return OrderedDict(zip(columns, row))
[ "def", "dictfetchone", "(", "cursor", ":", "Cursor", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "columns", "=", "get_fieldnames_from_cursor", "(", "cursor", ")", "row", "=", "cursor", ".", "fetchone", "(", ")", "if", "no...
33.666667
14.111111
def set_proxy(self, host = "localhost", port = 0, user = "", password = ""): """ Sets a custom HTTP proxy to use for future requests. """ self.conn.issue_command("SetProxy", host, port, user, password)
[ "def", "set_proxy", "(", "self", ",", "host", "=", "\"localhost\"", ",", "port", "=", "0", ",", "user", "=", "\"\"", ",", "password", "=", "\"\"", ")", ":", "self", ".", "conn", ".", "issue_command", "(", "\"SetProxy\"", ",", "host", ",", "port", ","...
47
7
def free_norm(self, name, free=True, **kwargs): """Free/Fix normalization of a source. Parameters ---------- name : str Source name. free : bool Choose whether to free (free=True) or fix (free=False). """ name = self.get_source_name(nam...
[ "def", "free_norm", "(", "self", ",", "name", ",", "free", "=", "True", ",", "*", "*", "kwargs", ")", ":", "name", "=", "self", ".", "get_source_name", "(", "name", ")", "normPar", "=", "self", ".", "like", ".", "normPar", "(", "name", ")", ".", ...
26.6875
21